Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
/****************************************************************************** Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby, C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS Code, Compile, Run and Debug online from anywhere in world. *******************************************************************************/ #include <stdio.h> #include <bits/stdc++.h> int h,m,hh,mm; int a[]={0,1,5,-1,-1,2,-1,-1,8,-1}; bool check(int x,int y){ if(a[x/10]==-1||a[x%10]==-1||a[y%10]==-1||a[y/10]==-1) return false; int h1=(a[y%10]*10+a[y/10]),m1=(a[x%10]*10+a[x/10]); return h1<h && m1<m; } int main() { int test; scanf("%d",&test); while(test--){ scanf("%d %d",&h,&m); scanf("%d:%d",&hh,&mm); int hc=hh,mc=mm; while(hc!=0||mc!=0){ if(check(hc,mc)) break; else if(mc==m-1) hc=(hc+1)%h; mc=(mc+1)%m; } printf("%d%d:%d%d\n",hc/10,hc%10,mc/10,mc%10); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.*; import java.util.*; public class P1493B2 { static InputReader in = new InputReader(System.in); static PrintWriter pw = new PrintWriter(System.out); static long mod = (long) (Math.pow(10, 9)) + 7; static HashMap<Integer, List<Integer>> adjList = new HashMap<>(); static boolean[] visited; static HashMap<String, String> map; public static void main(String[] args) { int test = in.nextInt(); map = new HashMap<>(); map.put("0", "0"); map.put("1", "1"); map.put("2", "5"); map.put("5", "2"); map.put("8", "8"); while (test --> 0) { solve(); } pw.close(); } static void solve() { int h = in.nextInt(), m = in.nextInt(); String[] line = in.nextLine().split(":"); int hour = Integer.parseInt(line[0]), minute = Integer.parseInt(line[1]); int secs = hour * m + minute; int increase = secs + 1; if (check(secs, h, m)) { print(secs, h, m); return; } while (true) { if (check(increase, h, m)) { print(increase, h, m); return; } increase++; } } static void print(int secs, int h, int m) { secs = (secs + (h * m)) % (h * m); int hour = secs / m; int minutes = secs % m; String hourString, minuteString; if (hour < 10) { hourString = "0" + Integer.toString(hour); } else { hourString = Integer.toString(hour); } if (minutes < 10) { minuteString = "0" + minutes; } else { minuteString = Integer.toString(minutes); } pw.println(hourString + ":" + minuteString); } static boolean check(int secs, int h, int m) { secs = (secs + (h * m)) % (h * m); int hour = secs / m; int minutes = secs % m; String hourString, minuteString; if (hour < 10) { hourString = "0" + Integer.toString(hour); } else { hourString = Integer.toString(hour); } if (minutes < 10) { minuteString = "0" + minutes; } else { minuteString = Integer.toString(minutes); } String h1 = hourString.substring(0, 1); String h2 = hourString.substring(1, 2); String m1 = minuteString.substring(0, 1); String m2 = minuteString.substring(1, 2); if (!map.containsKey(h1) || !map.containsKey(h2) || !map.containsKey(m1) || !map.containsKey(m2)) { return false; } String reversedHour = map.get(m2) + map.get(m1); String reversedMinute = map.get(h2) + map.get(h1); int hourVal, minuteVal; if (reversedHour.substring(0, 1).equals("0")) { hourVal = Integer.parseInt(reversedHour.substring(1, 2)); } else { hourVal = Integer.parseInt(reversedHour); } if (reversedMinute.substring(0, 1).equals("0")) { minuteVal = Integer.parseInt(reversedMinute.substring(1, 2)); } else { minuteVal = Integer.parseInt(reversedMinute); } return hourVal < h && minuteVal < m; } static void print(int[] time) { pw.println(time[0] + ":" + time[1]); } static void ruffleSort(int[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } public static List<Long> getFactors(long num) { List<Long> res = new ArrayList(); res.add(num); for (long d = 2; d <= (long)Math.sqrt(num); d++) { if (num % d == 0) { res.add(d); if ((num / d) != d) { res.add(num / d); } } } return res; } static long choose(long a, long b) { if(b > a - b) return choose(a, a - b); long m = 1; long d = 1; long i; for(i = 0; i < b; i++) { m *= (a - i); m %= mod; d *= (i + 1); d %= mod; } long ans = m * fast_pow(d, mod - 2) % mod; return ans; } static long fast_pow(long a, long b) { if(b == 0) return 1L; long val = fast_pow(a, b / 2); if(b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void addEdge(int u, int v) { adjList.putIfAbsent(u, new ArrayList<>()); adjList.get(u).add(v); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static int lcm (int a, int b) { return a / gcd(a, b) * b; } static boolean[] sieve(int n) { boolean[] isPrime = new boolean[n + 1]; isPrime[0] = false; isPrime[1] = false; for (int i = 2; i <= n; i++) { if (isPrime[i] && i * i <= n) { for (int j = i * i; j <= n; j += i) { isPrime[i] = false; } } } return isPrime; } static boolean isPrime(int n) { for (int d = 2; d * d <= n; d++) { if (n % d == 0) { return false; } } return true; } //ternary search on a graph that is concave down static int high(int[] a) { int lo = 0, hi = a.length - 1; int error = 3; while (hi - lo > error) { int right = hi - (hi - lo) / 3; int left = lo + (hi - lo) / 3; if (a[left] < a[right]) { lo = left; } else { hi = right; } } //check for the lowest from a[l, h] int ans = lo; for (int i = lo; i <= hi; i++) { if (a[ans] < a[i]) { ans = i; } } return ans; } //ternary search on a concave up graph static int low(int[] a) { int lo = 0, hi = a.length - 1; int error = 3; while (hi - lo > error) { int right = hi - (hi - lo) / 3; int left = lo + (hi - lo) / 3; if (a[left] < a[right]) { hi = right; } else { lo = left; } } //check for the lowerst from a[l, h] int ans = lo; for (int i = lo; i <= hi; i++) { if (a[ans] > a[i]) { ans = i; } } return ans; } static boolean contains(int[] a, int key) { int ans = 0; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low) / 2; int midVal = a[mid]; if (midVal < key) { low = mid + 1; } else if (midVal > key) { high = mid - 1; } else if (midVal == key) { ans = 1; break; } } return ans == 1; } static int first(int[] a, int key) { int ans = -1; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { low = mid + 1; } else if (midVal > key) { high = mid - 1; } else if (midVal == key) { ans = mid; high = mid - 1; } } return ans; } static int last(int[] a, int key) { int ans = -1; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { low = mid + 1; } else if (midVal > key) { high = mid - 1; } else if (midVal == key) { ans = mid; low = mid + 1; } } return ans; } static int greaterOrEqual(int[] a, int key) { int ans = -1; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal < key) { low = mid + 1; } else if (midVal >= key) { ans = mid; high = mid - 1; } } return ans; } static int lesserOrEqual(int[] a, int key) { int ans = -1; int low = 0, high = a.length - 1; while (low <= high) { int mid = low + (high - low + 1) / 2; int midVal = a[mid]; if (midVal <= key) { ans = mid; low = mid + 1; } else if (midVal > key) { high = mid - 1; } } return ans; } static class SegTree { long st[]; public SegTree(long[] arr, int n) { int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); int max_size = 2 * (int) Math.pow(2, x) - 1; st = new long[max_size]; constructSTUtil(arr, 0, n - 1, 0); } int getMid(int s, int e) { return s + (e - s) / 2; } long getSumUtil(int ss, int se, int qs, int qe, int si) { if (qs <= ss && qe >= se) return st[si]; if (se < qs || ss > qe) return 0; int mid = getMid(ss, se); return getSumUtil(ss, mid, qs, qe, 2 * si + 1) + getSumUtil(mid + 1, se, qs, qe, 2 * si + 2); } void updateValueUtil(int ss, int se, int i, long diff, int si) { if (i < ss || i > se) return; st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(ss, mid, i, diff, 2 * si + 1); updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } void updateValue(long arr[], int n, int i, int new_val) { if (i < 0 || i > n - 1) { System.out.println("Invalid Input"); return; } long diff = new_val - arr[i]; arr[i] = new_val; updateValueUtil(0, n - 1, i, diff, 0); } long getSum(int n, int qs, int qe) { if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println("Invalid Input"); return -1; } return getSumUtil(0, n - 1, qs, qe, 0); } long constructSTUtil(long arr[], int ss, int se, int si) { if (ss == se) { st[si] = arr[ss]; return arr[ss]; } int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) + constructSTUtil(arr, mid + 1, se, si * 2 + 2); return st[si]; } } static class UnionFind { // Number of connected components private int count; // Store a tree private int[] parent; // Record the "weight" of the tree private int[] size; public UnionFind(int n) { this.count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // The small tree is more balanced under the big tree if (size[rootP] > size[rootQ]) { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } else { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } count--; } public boolean connected(int p, int q) { int rootP = find(p); int rootQ = find(q); return rootP == rootQ; } private int find(int x) { while (parent[x] != x) { // Path compression parent[x] = parent[parent[x]]; x = parent[x]; } return x; } public int count() { return count; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int [] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long [] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public static int[] shuffle(int[] a, Random gen) { for(int i = 0, n = a.length;i < n;i++) { int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
t = int(input()) CAN_INVERSE = { "1": "1", "2": "5", "5": "2", "8": "8", "0": "0" } def is_inversable(num: str): num = list(num) res = "" for char in num[::-1]: if char not in CAN_INVERSE: return None res += CAN_INVERSE[char] return res KEYS = ["0", "1", "2", "5", "8"] POSSIBLE_NUMS = {} for i in range(5): for j in range(5): if i == 4 and j == 4: next_val = "00" elif j == 4: next_val = f"{KEYS[i+1]}0" else: next_val = f"{KEYS[i]}{KEYS[j+1]}" POSSIBLE_NUMS[f"{KEYS[i]}{KEYS[j]}"] = { "inv": f"{CAN_INVERSE[KEYS[j]]}{CAN_INVERSE[KEYS[i]]}", "next": next_val } result = [] for i in range(t): h, m = [int(x) for x in input().strip().split(' ')] hour, minute = input().strip().split(":") # print(POSSIBLE_NUMS) if hour in POSSIBLE_NUMS and int(POSSIBLE_NUMS[hour]["inv"]) < m and minute in POSSIBLE_NUMS and int(POSSIBLE_NUMS[minute]["inv"]) < h: result.append(f"{hour}:{minute}") else: possible_hours = sorted([x for x in POSSIBLE_NUMS.keys() if int(x) < h and int(POSSIBLE_NUMS[x]["inv"]) < m]) possible_minutes = sorted([x for x in POSSIBLE_NUMS.keys() if int(x) < m and int(POSSIBLE_NUMS[x]["inv"]) < h]) # print(possible_hours) if hour not in possible_hours: # do minutes == "00" and hours to next available if hour > possible_hours[-1]: new_hour = "00" else: new_hour = None for x in possible_hours: if x < hour: continue else: new_hour = x break if new_hour is None: new_hour = "00" new_minute = "00" elif hour in possible_hours and minute not in possible_minutes: # do minutes and possible hours if minutes == "00" update_hour = False if minute > possible_minutes[-1]: new_minute = "00" update_hour = True else: for x in possible_minutes: if x < minute: continue else: new_minute = x break if update_hour: hour = str(int(hour) + 1) if len(hour) == 1: hour = "0" + hour if hour > possible_hours[-1]: new_hour = "00" else: new_hour = None for x in possible_hours: if x < hour: continue else: new_hour = x break if new_hour is None: new_hour = "00" else: new_hour = hour result.append(f"{new_hour}:{new_minute}") # print("-----") for line in result: print(line)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
t = int(input()) for _ in range(t): hour, minute = map(int, input().split()) ta, tb = map(int, input().split(':')) def clip(a, b): b += 1 if b == minute: a += 1 b = 0 if a == hour: a = 0 return a, b def clock(a, b): a, b = str(a), str(b) if len(a) < 2: a = '0' + a if len(b) < 2: b = '0' + b return a, b def judge(a, b): a, b = clock(a, b) for letter in '34679': if letter in a or letter in b: return False dic = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'} aa = dic[b[1]]+dic[b[0]] bb = dic[a[1]]+dic[a[0]] if int(aa) < hour and int(bb) < minute: return True return False while not judge(ta, tb): ta, tb = clip(ta, tb) print(':'.join(clock(ta, tb)))
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.io.*; public class Equal { static class pair implements Comparable<pair> { int x; int y; public pair(int u, int v) { this.x = u; this.y = v; } @Override public int compareTo(pair o) { return o.x-x; } } static int[][]mem=new int[1001][1001]; // static int dp(int n,int k){ // if(n>=mem.length) // return 0; // if(k<0||k>=mem.length) // return 0; // if(mem[n][k]!=-1) // return mem[n][k]; // } static String timeInc(String time,int h,int m){ String []s =time.split(":"); int i=0; int hh=0; int mm=0; while (i<s[0].length()&&s[0].charAt(i)=='0'){ i++; } if(i<s[0].length()) hh=Integer.parseInt(s[0].substring(i)); i=0; while (i<s[1].length()&&s[1].charAt(i)=='0'){ i++; } if(i<s[1].length()) mm=Integer.parseInt(s[1].substring(i)); mm++; if(mm%m==0){ mm=0; hh++; if(hh%h==0) hh=0; } String hs=""+hh; while(hs.length()<2) hs="0"+hs; String ms=""+mm; while (ms.length()<2) ms="0"+ms; return hs+":"+ms; } static boolean validMirror(String s,int h,int m){ HashSet<Character>hs=new HashSet<>(); hs.add('3'); hs.add('4'); hs.add('6'); hs.add('7'); hs.add('9'); for (int i = 0; i <s.length() ; i++) { if(hs.contains(s.charAt(i))){ return false; } } String mirrored=""; for (int i = s.length()-1; i >=0 ; i--) { if(s.charAt(i)=='5'){ mirrored+="2"; continue; } if(s.charAt(i)=='2'){ mirrored+="5"; continue; } mirrored+=s.charAt(i); } int i=0; int hh=0; int mm=0; String []s2 =mirrored.split(":"); while (i<s2[0].length()&&s2[0].charAt(i)=='0'){ i++; } if(i<s2[0].length()) hh=Integer.parseInt(s2[0].substring(i)); i=0; while (i<s2[1].length()&&s2[1].charAt(i)=='0'){ i++; } if(i<s2[1].length()) mm=Integer.parseInt(s2[1].substring(i)); if(hh>=h||mm>=m) return false; return true; } public static void main(String[] args) throws IOException { //BufferedReader br = new BufferedReader(new FileReader("name.in")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; PrintWriter out = new PrintWriter(System.out); int T=Integer.parseInt(br.readLine()); while (T-->0){ st=new StringTokenizer(br.readLine()); int h=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); String s=br.readLine(); while(!validMirror(s,h,m)){ s=timeInc(s,h,m); } out.println(s); } out.flush(); out.close(); } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
mp={1:1,2:5,5:2,8:8,0:0} def getreflect(mh,lh,mm,lm,h,m): boo=True global mp if lh not in mp.keys(): return False if mh not in mp.keys(): return False if lm not in mp.keys(): return False if mm not in mp.keys(): return False if mp[lh]*10+mp[mh]>=m or mp[lm]*10+mp[mm]>=h: return False return boo t=int(input()) while t: t-=1 n,k=input().split() time=input() h,m=int(n),int(k) mh,lh,mm,lm=int(time[0]),int(time[1]),int(time[3]),int(time[4]) while True: if mm*10+lm>=m: mm=0 lm=0 lh+=1 if lh>=10: lh=0 mh+=1 if mh*10+lh>=h: lh=0 mh=0 if getreflect(mh,lh,mm,lm,h,m): ans=str(mh)+str(lh)+":"+str(mm)+str(lm) break lm+=1 if lm>=10: lm=0 mm+=1 print(ans)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <iostream> #include <algorithm> #include <utility> #include <vector> #include <unordered_map> using namespace std; int h, m; unordered_map<int, int> mp; bool is_valid(int hour, int minute) { int a, b, c, d; unordered_map<int, int>::iterator it_a, it_b, it_c, it_d; a = hour / 10; b = hour % 10; c = minute / 10; d = minute % 10; if ((it_a = mp.find(a)) == mp.end() || (it_b = mp.find(b)) == mp.end() || (it_c = mp.find(c)) == mp.end() || (it_d = mp.find(d)) == mp.end()) return false; if (it_d->second * 10 + it_c->second >= h || it_b->second * 10 + it_a->second >= m) return false; printf("%d%d:%d%d\n", a, b, c, d); return true; } void solution() { int hour, minute; scanf("%d %d", &h, &m); scanf("%d:%d", &hour, &minute); while (!is_valid(hour, minute)) { minute++; if (minute >= m) { minute = 0; hour++; } if (hour >= h) hour = 0; } } int main(void) { int t; scanf("%d", &t); mp.insert({0, 0}); mp.insert({1, 1}); mp.insert({2, 5}); mp.insert({5, 2}); mp.insert({8, 8}); while (t--) { solution(); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
R = dict() R['0'] = '0' R['1'] = '1' R['2'] = '5' R['5'] = '2' R['8'] = '8' for _ in range(int(input())): H, M = map(int, input().split(' ')) h, m = map(int, input().split(':')) def reflect(t): h = str((t // M) % H).zfill(2) m = str((t % M) % M).zfill(2) try: nh = ''.join(map(lambda x: R[x], m[::-1])) nm = ''.join(map(lambda x: R[x], h[::-1])) return f'{nh}:{nm}' except: return f'{H:02}:{M:02}' def valid(time): h, m = map(int, time.split(':')) return h < H and m < M t = h * M + m while not valid(reflect(t)): t += 1 h = str((t // M) % H).zfill(2) m = str((t % M) % M).zfill(2) print(f'{h}:{m}')
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
def isSafe(s, h, m): if int(s[:2]) >= h or int(s[3:]) >= m:return False s = list(s[::-1]) for i in range(5): if s[i] == '2':s[i] = '5' elif s[i] == '5':s[i] = '2' s = ''.join(s) if int(s[:2]) >= h or int(s[3:]) >= m:return False for d in ['3', '4', '6', '7', '9']: if d in s: return False return True t = int(input()) for _ in range(t): h, m = map(int, input().split()) s = input().strip() val1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] val2 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] val3 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] val4 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] while val1 and s[0] > val1[0]: val1.pop(0) while val2 and s[1] > val2[0]: val2.pop(0) while val3 and s[3] > val3[0]: val3.pop(0) while val4 and s[4] > val4[0]: val4.pop(0) ans = None for v1 in val1: if ans:break for v2 in val2: if ans:break for v3 in val3: if ans:break for v4 in val4: if isSafe(v1+v2+':'+v3+v4, h, m): ans = v1+v2+':'+v3+v4 break val4 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] val3 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] val2 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] print(ans if ans else '00:00')
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> #include <string> using namespace std; using ll=long long; int h,m; int r[10]={0,1,5,-1,-1,2,-1,-1,8,-1}; bool check(int a,int b){ if(r[a%10]==-1 || r[a/10]==-1 || r[b%10]==-1 || r[b/10]==-1) return false; return r[a%10]*10+r[a/10]<m && r[b%10]*10+r[b/10]<h; } void solve(){ int a,b; char x; cin>>h>>m; cin>>a>>x>>b; while(1){ if(check(a,b)==true) break; b=(b+1)%m; if(b==0) a=(a+1)%h; } cout<<a/10<<a%10<<":"<<b/10<<b%10<<endl; } int main(){ int t; cin>>t; while(t--){solve();} }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
/* AUTHOR: ADVAY AGGARWAL INSTITUTION: IIIT DHARWAD */ #include<bits/stdc++.h> using namespace std; #define mod 1000000007 //1e9+7 ans%mod #define ll long long int #define test_cases(x) int x; cin>>x; while(x--) #define vi vector<int> #define setbits(x) __builtin_popcountll(x) #define endl "\n" void starter() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE //for getting input from input.txt freopen("input.txt", "r", stdin); //for writing output to output.txt freopen("output.txt", "w", stdout); #endif } map<char, int>ma; bool is_valid(string s, int h, int m) { if (ma[s[0]] == -1 || ma[s[1]] == -1 || ma[s[3]] == -1 || ma[s[4]] == -1) return false; int x = ma[s[3]] + (10 * ma[s[4]]); int y = ma[s[0]] + (10 * ma[s[1]]); if (x < h && y < m) return true; return false; } int main() { starter(); ma['0'] = 0; ma['1'] = 1; ma['2'] = 5; ma['5'] = 2; ma['8'] = 8; ma['3'] = -1; ma['4'] = -1; ma['6'] = -1; ma['7'] = -1; ma['9'] = -1; test_cases(t) { int h, m; cin >> h >> m; string s; cin >> s; if (is_valid(s, h, m)) cout << s << endl; else { int hh = (s[1] - '0') + (10 * (s[0] - '0')); int mm = (s[4] - '0') + (10 * (s[3] - '0')); //cout << hh << " " << mm << endl; while (hh < h && mm < m ) { string s = to_string(hh) + ":" + to_string(mm); if (hh < 10 && mm >= 10) { s = "0" + to_string(hh) + ":" + to_string(mm); } else if (hh > 9 && mm < 10) { s = to_string(hh) + ":" + "0" + to_string(mm); } else if (hh < 10 && mm < 10) { s = "0" + to_string(hh) + ":" + "0" + to_string(mm); } //cout << s << endl; if (is_valid(s, h, m)) { cout << s << endl; break; } else { if (mm == m - 1) { if (hh < h - 1)hh++; else hh = 0; mm = 0; } else if (mm < m - 1) mm++; } // if (hh == h - 1) // { // hh = 0; // mm = 0; // } } } } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import sys import itertools import collections def rs(x=''): if len(x) == 0: return sys.stdin.readline().strip() return input(x).strip() def ri(x=''): return int(rs(x)) def rm(x=''): return map(str, rs(x).split()) def rl(x=''): return rs(x).split() def rmi(x=''): return map(int, rl(x)) def rli(x=''): return [int(val) for val in rl(x)] def println(val): sys.stdout.write(str(val) + '\n') def mirror(val): mirrored = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1] a, b = val // 10, val % 10 if mirrored[a] == -1 or mirrored[b] == -1: return -1 return mirrored[b] * 10 + mirrored[a] def solve(testCase): h, m = rmi() time = rs() hour, minute = time[:2], time[3:] hour = int(hour) * m + int(minute) while True: h2, m2 = mirror(hour // m % h), mirror(hour % m) h2, m2 = m2, h2 if h2 >= 0 and m2 >= 0 and h2 < h and m2 < m: break hour += 1 h = hour // m % h m = hour % m ans = [] if h < 10: ans += ['0'] ans += [str(h), ':'] if m < 10: ans += ['0'] ans += [str(m)] # print('!', ''.join(ans)) print(''.join(ans)) for _ in range(ri() if 1 else 1): solve(_ + 1)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.*; import java.util.*; import java.util.Collections; public class div2_705_B implements Runnable { int t,h,m; public void run() { InputReader sc = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0) { h = sc.nextInt();m = sc.nextInt(); String s = sc.next(); String str1 = s.substring(0,2); int nh = Integer.parseInt(str1); String str2 = s.substring(3,5); int nm = Integer.parseInt(str2); while(nh != 0 || nm != 0) { if(check(nh,nm)) { break; } if(nm == m-1) { nh = (nh+1)%h; } nm = (nm+1)%m; } System.out.println(nh/10+""+nh%10+":"+nm/10+""+nm%10); } } static class sortintarray { public static void sort(int[] arr) { int n = arr.length, mid, h, s, l, i, j, k; int[] res = new int[n]; n--; for (s = 1; s <= n; s <<= 1) { for (l = 0; l < n; l += (s << 1)) { h = Math.min(l + (s << 1) - 1, n); mid = Math.min(l + s - 1, n); i = l; j = mid + 1; k = l; while (i <= mid && j <= h) res[k++] = (arr[i] <= arr[j] ? arr[i++] : arr[j++]); while (i <= mid) res[k++] = arr[i++]; while (j <= h) res[k++] = arr[j++]; for (k = l; k <= h; k++) arr[k] = res[k]; } } } } static class sortchararray { public static void sort(char[] arr) { int n = arr.length, mid, h, s, l, i, j, k; char[] res = new char[n]; n--; for (s = 1; s <= n; s <<= 1) { for (l = 0; l < n; l += (s << 1)) { h = Math.min(l + (s << 1) - 1, n); mid = Math.min(l + s - 1, n); i = l; j = mid + 1; k = l; while (i <= mid && j <= h) res[k++] = (arr[i] <= arr[j] ? arr[i++] : arr[j++]); while (i <= mid) res[k++] = arr[i++]; while (j <= h) res[k++] = arr[j++]; for (k = l; k <= h; k++) arr[k] = res[k]; } } } } boolean check(int nh,int nm) { int a[] = new int[]{0,1,5,-1,-1,2,-1,-1,8,-1}; if (a[nh / 10] == -1 || a[nh % 10] == -1 || a[nm / 10] == -1 || a[nm % 10] == -1) { return false; } int ih = a[nm % 10] * 10 + a[nm / 10], im = a[nh % 10] * 10 + a[nh / 10]; return ih < h && im < m; } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} long factorial(long n){ if (n == 0) return 1; else return(n * factorial(n-1)); } boolean isPrime(int n) { if (n <= 1){ return false; } for (int i = 2; i < n; i++){ if (n % i == 0){ return false; } } return true; } long ceil(long a,long b) { if(a%b==0) { return a/b; } else { return (a/b)+1; } } int ceil(int a,int b) { if(a%b==0) { return a/b; } else { return (a/b)+1; } } public static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> { public U x; public V y; public Pair(U x, V y) { this.x = x; this.y = y; } public int hashCode() { return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode()); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<U, V> p = (Pair<U, V>) o; return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y)); } public int compareTo(Pair<U, V> b) { int cmpU = x.compareTo(b.x); return cmpU != 0 ? cmpU : y.compareTo(b.y); } public String toString() { return String.format("(%s, %s)", x.toString(), y.toString()); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new div2_705_B(),"Main",1<<27).start(); } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
class Clock: def __init__(self, h, m, hh, mm): self.h = h self.m = m self.hh = hh self.mm = mm def xx_str(self, xx): return str(xx).zfill(2) def __str__(self): return self.xx_str(self.hh) + ':' + self.xx_str(self.mm) def x_rev(self, x): revs = { '0': '0', '1': '1', '2': '5', '3': None, '4': None, '5': '2', '6': None, '7': None, '8': '8', '9': None, } return revs[x] def xx_rev(self, xx): first = self.x_rev(xx[1]) second = self.x_rev(xx[0]) if first is None or second is None: return None return first + second def check_rev(self): hh_rev = self.xx_rev(self.xx_str(self.mm)) mm_rev = self.xx_rev(self.xx_str(self.hh)) # print(self.xx_str(hh_rev) + ':' + self.xx_str(mm_rev)) if hh_rev is None or mm_rev is None: return False return int(hh_rev) < self.h and int(mm_rev) < self.m def inc(self): self.mm += 1 self.hh += self.mm // self.m self.mm %= self.m self.hh %= self.h def inc_untill_rev_correct(self): while not self.check_rev(): self.inc() for _ in range(int(input())): h, m = map(int, input().split()) hh, mm = map(int, input().split(':')) clock = Clock(h, m, hh, mm) clock.inc_untill_rev_correct() print(clock)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; import java.math.*; import java.io.*; // Arrays.sort(); //char[] a=fs.next().toCharArray(); public class B_Planet_Lapituletti { public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int T = fs.nextInt(); outer: while (T-- > 0) { int hm = fs.nextInt(), mm = fs.nextInt(); String arr[] = fs.next().split(":"); int nh = Integer.valueOf("" + arr[0]); int nm = Integer.valueOf("" + arr[1]); while (nh < hm) { while (!check(nm, hm)) { nm++; if (nm == mm) { nm = 0; nh++; break; } } if (check(nh, mm) && nh < hm) { if (nh < 10) { System.out.print("0" + nh + ":"); } else { System.out.print(nh + ":"); } if (nm < 10) { System.out.println("0" + nm); } else { System.out.println(nm); } continue outer; } else { nh++; nm = 0; } } System.out.println("00:00"); } out.close(); } public static boolean check(int n, int max) { int p1 = n % 10; int p2 = n / 10; int arr[] = { 0, 1, 5, -1, -1, 2, -1, -1, 8, -1 }; if (arr[p1] == -1 || arr[p2] == -1) { return false; } if ((arr[p1] * 10 + arr[p2] < max)) { return true; } return false; } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); StringBuilder nextsb() { StringBuilder sb = new StringBuilder(next()); return sb; } String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } return st.nextToken(); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; /** * @author Mubtasim Shahriar */ public class Cr705A { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); int t = sc.nextInt(); // int t = 1; while (t-- != 0) { solver.solve(sc, out); } out.close(); } static class Solver { HashMap<Character,Character> map = new HashMap<>(); public void solve(InputReader sc, PrintWriter out) { int h = sc.nextInt(); int m= sc.nextInt(); map.put('2','5'); map.put('5','2'); map.put('1','1'); map.put('8','8'); map.put('0','0'); char[] arr = sc.next().toCharArray(); if(okRef(arr) && ok(arr,h,m)) { out.println(new String(arr)); return; } char[] next = next(arr,h,m); do { while(!okRef(next)) next = next(next,h,m); if(ok(next,h,m)) { out.println(new String(next)); return; } next = next(next,h,m); } while(!same(next,arr)); } private boolean same(char[] next, char[] arr) { if(next.length!=arr.length) throw new RuntimeException(); int n = next.length; if(n!=5) throw new RuntimeException(); for(int i = 0; i < n; i++) { if(i==2) continue; if(next[i]!=arr[i]) return false; } return true; } private char[] next(char[] arr,int oh,int om) { int[] hm = getAll(arr); int h = hm[0]; int m = hm[1]; int carry = 0; int nextm = m+1; if(nextm==om) { nextm = 0; carry=1; } int nexth = h+carry; if(nexth==oh) nexth = 0; String hs = '0'+Integer.toString(nexth); String ms = '0'+Integer.toString(nextm); char[] ret = new char[5]; int hss = 0; if(hs.length()>2) hss++; for(int i = 0; i < 2; i++) { ret[i] = hs.charAt(hss++); } int mss = 0; if(ms.length()>2) mss++; for(int i = 3; i < 5; i++) { ret[i] = ms.charAt(mss++); } ret[2] = ':'; return ret; } private boolean okRef(char[] arr) { for(int i = 0; i < arr.length; i++) { if(i==2) continue; char now = arr[i]; if(!map.containsKey(now)) return false; } return true; } private boolean ok(char[] arr, int h, int m) { char[] revarr = rev(arr); int[] hm = getAll(revarr); if(hm[0]<h && hm[1]<m) return true; return false; } private int[] getAll(char[] arr) { StringBuilder hs = new StringBuilder(); StringBuilder ms = new StringBuilder(); int n = arr.length; for(int i = 0; i<2; i++) hs.append(arr[i]); for(int i = 3; i<n; i++) ms.append(arr[i]); int hr = Integer.parseInt(hs.toString()); int mt = Integer.parseInt(ms.toString()); return new int[] {hr,mt}; } private char[] rev(char[] arr) { int n = arr.length; int l = 0; int r = n-1; char[] ret=new char[arr.length]; while(l<n) { ret[l++] = arr[r--]; } for(int i = 0; i < n; i++) { if(i!=2) ret[i] = map.get(ret[i]); } return ret; } } static void sort(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); } static void sort(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); } static void sortDec(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); int l = 0; int r = n - 1; while (l < r) { arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; l++; r--; } } static void sortDec(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int idx = rand.nextInt(n); if (idx == i) continue; arr[i] ^= arr[idx]; arr[idx] ^= arr[i]; arr[i] ^= arr[idx]; } Arrays.sort(arr); int l = 0; int r = n - 1; while (l < r) { arr[l] ^= arr[r]; arr[r] ^= arr[l]; arr[l] ^= arr[r]; l++; r--; } } static class InputReader { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int peek() { if (numChars == -1) { return -1; } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) { return -1; } } return buf[curChar]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return readLine(); } else { return readLine0(); } } public BigInteger readBigInteger() { try { return new BigInteger(nextString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) { read(); } return value == -1; } public String next() { return nextString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int[] nextSortedIntArray(int n) { int array[] = nextIntArray(n); Arrays.sort(array); return array; } public int[] nextSumIntArray(int n) { int[] array = new int[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; ++i) array[i] = nextLong(); return array; } public long[] nextSumLongArray(int n) { long[] array = new long[n]; array[0] = nextInt(); for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt(); return array; } public long[] nextSortedLongArray(int n) { long array[] = nextLongArray(n); Arrays.sort(array); return array; } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned int uint; const int maxn = 1e7 + 10; const int N = 3e4 + 10; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7;; int t; int h,m; char hh[3]; char mm[3]; int num[10]; char s[10]; bool check(int num) { if((num % 10 == 1 || num % 10 == 2 || num % 10 == 5 || num % 10 == 8 || num % 10 == 0) && (num / 10 == 1 || num / 10 == 2 || num / 10 == 5 || num / 10 == 8 || num / 10 == 0)) return true; else return false; } int main() { cin >> t; num[1] = 1; num[2] = 5; num[5] = 2; num[8] = 8; num[0] = 0; while(t--) { cin >> h >> m; cin >> s + 1; int numh = (s[1] - '0') * 10 + s[2] - '0'; int numm = (s[4] - '0') * 10 + s[5] - '0'; while(1) { int res = numh; int ress = numm; if(check(numh) && check(numm)) { res = numh; ress = numm; numh = num[ress % 10] * 10 + num[ress / 10]; numm = num[res % 10] * 10 + num[res / 10]; if(numh < h && numm < m) { numh = res; numm = ress; if(numh < 10) cout << 0 << numh << ":"; else cout << numh << ":"; if(numm < 10) cout << 0 << numm << endl; else cout << numm << endl; break; } } numh = res; numm = ress; if(numm == m - 1) { numm = 0; if(numh == h - 1) { numh = 0; } else { numh++; } } else { numm++; } } } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
nums = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'} def fmt_num(x): return str(x).rjust(2, '0') def is_valid(hh, mm, h, m): hh = fmt_num(hh) mm = fmt_num(mm) if not all(c in nums for c in hh+mm): return False hh, mm = int(nums[mm[1]]+nums[mm[0]]), int(nums[hh[1]]+nums[hh[0]]) return 0 <= hh < h and 0 <= mm < m def solve(h, m, time): hh, mm = map(int, time.split(':')) while not is_valid(hh, mm, h, m): mm = (mm + 1) % m if mm == 0: hh = (hh + 1) % h return fmt_num(hh) + ':' + fmt_num(mm) for _ in xrange(int(raw_input())): h, m = map(int, raw_input().split()) time = raw_input().strip() print solve(h, m, time)
PYTHON
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B_Planet_Lapituletti { int h,m; void run(FastScanner sc){ h = sc.nextInt(); m = sc.nextInt(); String s = sc.nextLine(); // System.out.println(h + " " + m + " " + s); int hour = Integer.parseInt(s.substring(0,2)); int minute = Integer.parseInt(s.substring(3)); // System.out.println(hour + " " + minute); while(true){ if(checkReverse(hour,minute)){ break; } minute++; if(minute==m){ minute = 0; hour++; if(hour==h) { hour = 0; checkReverse(hour,minute); break; } } } } boolean checkReverse(int hour, int minute){ int num1 = rev(minute%10); if(num1 == -1) return false; int num2 = rev((minute/10)%10); if(num2 == -1) return false; int num3 = rev(hour%10); if(num3 == -1) return false; int num4 = rev((hour/10)%10); if(num4 == -1) return false; int hour2 = num1*10 + num2; int minute2 = num3*10 + num4; if(hour2 < h && minute2 < m) { System.out.println((hour/10)%10+""+hour%10+":"+(minute/10)%10+""+minute%10); return true; } else { return false; } } int rev(int digit){ switch (digit){ case 0: return 0; case 1: return 1; case 2: return 5; case 5: return 2; case 8: return 8; default: return -1; } } public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); for(int i = 0; i < t; i++){ new B_Planet_Lapituletti().run(sc); } } @SuppressWarnings("unused") static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return br.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
valid=[0,1,2,5,8] valid1=[0,1,2,5,8,6] def opos(x): a=x%10 b=x//10 if a==2: a=5 elif a==5: a=2 if b==2: b=5 elif b==5: b=2 return (a)*10+(b) def opos1(x): a=x%10 b=x//10 if a==2: a=5 elif a==5: a=2 elif a==9: a=6 elif a==6: a=9 if b==2: b=5 elif b==5: b=2 elif b==9: b=6 elif b==6: b=9 return (a)*10+(b) for _ in range(int(input())): a,b=map(int,input().split()) h,m=map(int,input().split(":")) while 1: if h//10 in valid and h%10 in valid and m//10 in valid and m%10 in valid and opos(h)<b and opos(m)<a: break m+=1 h+=m//b m=m%b h=h%a print("0"*(2-len(str(h)))+str(h)+":"+"0"*(2-len(str(m)))+str(m))
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
rn=lambda:int(input()) rns=lambda:map(int,input().split()) rl=lambda:list(map(int,input().split())) rs=lambda:input() YN=lambda x:print('YES') if x else print('NO') mod=10**9+7 from bisect import bisect_left def isvalid(i,j,k,l,h,m): ans=(10*int(i)+int(j))<h and (10*int(k)+int(l))<m def reverse(char): if char in [1,0,8]: return char if char==2: return 5 return 2 rev=[reverse(c) for c in [l,k,j,i]] ans = ans and (10 * int(rev[0]) + int(rev[1])) < h and (10 * int(rev[2]) + int(rev[3])) < m return ans for _ in range(rn()): h,m=rns() s=rs() good=[0,1,2,5,8] times=[] for i in good: for j in good: for k in good: for l in good: if isvalid(i,j,k,l,h,m): time=str(i)+str(j)+':'+str(k)+str(l) ttime=(10*int(i)+int(j))*m + (10*int(k)+int(l)) times.append([ttime,time]) times.sort() atimes=[i[0] for i in times] find=(10*int(s[0])+int(s[1]))*m + (10*int(s[3])+int(s[4])) i=bisect_left(atimes,find)%len(atimes) ans=times[i][1] print(ans)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
t = int(input()) for q in range(t): h, m = map(int, input().split()) s = input() s1 = s[0:2] s2 = s[3:5] while True: s3 = "" s4 = "" b = True for i in range(len(s1)-1, -1, -1): if s1[i] == '0': s4 += '0' elif s1[i] == "1": s4 += '1' elif s1[i] == "2": s4 += '5' elif s1[i] == "5": s4 += '2' elif s1[i] == "8": s4 += '8' else: b = False break for i in range(len(s2)-1, -1, -1): if s2[i] == '0': s3 += '0' elif s2[i] == "1": s3 += '1' elif s2[i] == "2": s3 += '5' elif s2[i] == "5": s3 += '2' elif s2[i] == "8": s3 += '8' else: b = False break if b: hr = int(s3) mn = int(s4) if hr // h == 0 and mn // m == 0: print(s1 + ':' + s2) break s1 = int(s1) s2 = int(s2) s1 = (s1 + ((s2+1) // m == 1))%h s2 = (s2+1) % m if s1 < 10: s1 = "0" + str(s1) else: s1 = str(s1) if s2 < 10: s2 = "0" + str(s2) else: s2 = str(s2)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; import java.lang.*; public class Planet_Lapituletti { static int[] ref = {0,1,5,-1,-1,2,-1,-1,8,-1}; public static void main(String[] args) throws java.lang.Exception{ Scanner input = new Scanner(System.in); int t = Integer.parseInt(input.nextLine()); for(int i=0;i<t;i++){ String[] hm = input.nextLine().split(" "); String[] HM = input.nextLine().split(":"); int h = Integer.parseInt(hm[0]); int m = Integer.parseInt(hm[1]); int H = Integer.parseInt(HM[0]); int M = Integer.parseInt(HM[1]); while(H!=0||M!=0){ if(isvalid(h, m, H, M)){ break; } if(M==m-1){ H = (H+1)%h; } M = (M+1)%m; } System.out.println((H/10)+""+(H%10)+":"+(M/10)+""+(M%10)); } } public static boolean isvalid(int h, int m, int H, int M){ String nh = ""; String nm = ""; nh = Integer.toString(ref[M%10])+Integer.toString(ref[M/10]); nm = Integer.toString(ref[H%10])+Integer.toString(ref[H/10]); if(ref[H/10]!=-1&&ref[H%10]!=-1&&ref[M/10]!=-1&&ref[M%10]!=-1&&Integer.parseInt(nh)<h&&Integer.parseInt(nm)<m){ return true; } return false; } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
accepted_numbers = [1, 2, 5, 8, 0] reverse_numbers = {1: 1, 2: 5, 5: 2, 8: 8, 0: 0} # def time_accepted(hn, mn, h, m): # h1 = hn // 10 # h0 = hn % 10 # m1 = mn // 10 # m0 = mn % 10 # if not (h1 in accepted_numbers and h0 in accepted_numbers and m0 in accepted_numbers and m1 in accepted_numbers): # return False # hn = # def main_code(): # h, m = input().split(" ") # h, m = int(h), int(m) # hn, mn = input().split(":") # hn, mn = int(hn), int(mn) # while not m_accpeted(mn, m): # mn += 1 # if mn >= m: # hn += 1 # if hn == h: # print("00:00") # return # if not hr_accpeted(hn, h): # mn = 0 # while not hr_accpeted(hn): # hn += 1 # if hn >= h: # hn = 0 # print(f"{hn}:{mn}") def main_code(): h, m = input().split(" ") h, m = int(h), int(m) hn, mn = input().split(":") hn, mn = int(hn), int(mn) minimum = 1000000 time = [0, 0] for i in accepted_numbers: for j in accepted_numbers: for k in accepted_numbers: for l in accepted_numbers: if 10 * i + j >= h: continue if 10 * k + l >= m: continue if 10 * reverse_numbers[l] + reverse_numbers[k] >= h: continue if 10 * reverse_numbers[j] + reverse_numbers[i] >= m: continue value = 10 * k + l - mn + m * (10 * i + j - hn) if 0 <= value < minimum: minimum = value time = [10 * i + j, 10 * k + l] print(f"{time[0]:02d}:{time[1]:02d}") no_of_test_cases = int(input()) for i in range(no_of_test_cases): main_code()
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.Scanner; public class PlanetLapituletti { public static String mirror(String moment) { char[] mirror = {'0', '1', '5', '/', '/', '2', '/', '/', '8', '/'}; String[] splitMoment = moment.split(":"); String hours = splitMoment[0]; String minutes = splitMoment[1]; int onesH = Character.getNumericValue(hours.charAt(1)); int tensH = Character.getNumericValue(hours.charAt(0)); int onesM = Character.getNumericValue(minutes.charAt(1)); int tensM = Character.getNumericValue(minutes.charAt(0)); // if mirror image contains / then it is not valid return ("" + mirror[onesM] + mirror[tensM] + ":" + mirror[onesH] + mirror[tensH]); } public static String findNearestMirrorMoment(String format, String moment) { String[] splitFormat = format.split(" "); int fH = Integer.parseInt(splitFormat[0]); int fM = Integer.parseInt(splitFormat[1]); String[] splitMoment = moment.split(":"); int mH = Integer.parseInt(splitMoment[0]); int mM = Integer.parseInt(splitMoment[1]); while(true) { String currentMoment = String.format("%02d:%02d", mH, mM); String mirrorImage = mirror(currentMoment); int mirrorH = -1; int mirrorM = -1; if(!mirrorImage.contains("/")) { mirrorH = Integer.parseInt(mirrorImage.split(":")[0]); mirrorM = Integer.parseInt(mirrorImage.split(":")[1]); } // is mirror image moment valid ? boolean isValid = false; if(!mirrorImage.contains("/") && mirrorH < fH && mirrorM < fM) { isValid = true; } if(isValid) { return currentMoment; } if(mM == fM - 1) { // one hour has gone through --> reset minutes & increase hours mM = 0; mH++; if(mH == fH) { // one day has gone through --> reset hours & minutes mH = 0; mM = 0; } } else { mM++; } } } public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int T = scanner.nextInt(); String line = null; String[] formats = new String[T]; String[] moments = new String[T]; int j = 0; int v = 0; scanner.nextLine(); // read new line after T for(int i = 0; i < 2*T; i++) { line = scanner.nextLine(); if(i % 2 == 0) { formats[j] = line; j++; } else { moments[v] = line; v++; } } scanner.close(); for(int k = 0; k < moments.length; k++) { System.out.println(findNearestMirrorMoment(formats[k], moments[k])); } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<bits/stdc++.h> using namespace std; #define ll long long #define endl ("\n") void solve() { ll h,m; cin>>h>>m; string s; cin>>s; ll H = (s[0]-'0')*10 + s[1]-'0'; ll M = (s[3]-'0')*10 + s[4]-'0'; ll a[] = {0,1,5,-1,-1,2,-1,-1,8,-1}; for(ll i=H;i<h;i++) { for(ll j=0;j<m;j++) { ll p = i/10; ll q = i%10; ll r = j/10; ll t = j%10; if(a[p]==-1 || a[q]==-1 || a[r]==-1 || a[t]==-1) continue; p = a[p]; q = a[q]; r = a[r]; t = a[t]; ll h1 = t*10+r; ll m1 = q*10+p; if(h1<h && m1<m && ((i>H) || (i==H && j>=M))) { cout<<a[m1%10]<<a[m1/10]<<":"<<a[h1%10]<<a[h1/10]<<endl; return; } } } cout<<"00:00"<<endl; } int main() { ll t; cin>>t; while(t--)solve(); return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; #define INF 987654321 ll gcd(ll a, ll b) { for (; b; a %= b, swap(a, b)); return a; } int h[3], m[3]; int H, M; int chk[5] = { 3, 4, 6, 7, 9 }; bool Check(void) { bool hasAns = true; for (int i = 0; i < 5; i++) { if (h[0] == chk[i] || h[1] == chk[i] || m[0] == chk[i] || m[1] == chk[i]) { hasAns = false; break; } } int mm[2], hh[2]; mm[1] = h[0], mm[0] = h[1], hh[1] = m[0], hh[0] = m[1]; for (int i = 0; i < 2; i++) { if (mm[i] == 2 || mm[i] == 5) mm[i] = 7 - mm[i]; if (hh[i] == 2 || hh[i] == 5) hh[i] = 7 - hh[i]; } int Hour = hh[0] * 10 + hh[1]; int Minute = mm[0] * 10 + mm[1]; if (Hour >= H || Minute >= M) hasAns = false; return hasAns; } void Move(void) { m[1]++; if (m[1] > 9) { m[0]++; m[1] = 0; } int Minute = m[0] * 10 + m[1]; if (Minute >= M) { h[1]++; m[0] = m[1] = 0; } if (h[1] > 9) { h[0]++; h[1] = 0; } int Hour = h[0] * 10 + h[1]; if (Hour >= H) { h[0] = h[1] = m[0] = m[1] = 0; } } int main(void) { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); int t; cin >> t; while (t--) { cin >> H >> M; string st; cin >> st; h[0] = st[0] - '0', h[1] = st[1] - '0'; m[0] = st[3] - '0', m[1] = st[4] - '0'; while (true) { bool flag = Check(); if (flag) { cout << h[0] << h[1] << ":" << m[0] << m[1] << "\n"; break; } Move(); } } }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
I=lambda x:[*map(int,input().split(x))] for _ in' '*I(' ')[0]: hh,mm=I(' ') h,m=I(':') convert=[0,1,5,-1,-1,2,-1,-1,8,-1] while 1: ah=convert[h//10] bh=convert[h%10] am=convert[m//10] bm=convert[m%10] H=10*bm+am M=10*bh+ah if -1 in [ah,bh,am,bm] or H>=hh or M>=mm: m=(m+1)%mm if m==0:h=(h+1)%hh continue else:print('0'*(h<10)+str(h)+':'+'0'*(m<10)+str(m));break
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
for _ in range(int(input())): hh, mm = map(int, input().split()) timeTr = [] inp = input() time = [int(inp[0] + inp[1]), int(inp[3] + inp[4])] def tTr(): global time global timeTr t0 = time[0] t1 = time[1] timeTr = [time[0] // 10, time[0] % 10, time[1] // 10, time[1] % 10] while True: tTr() while 3 in timeTr or 4 in timeTr or 6 in timeTr or 7 in timeTr or 9 in timeTr: h = time[0] m = time[1] if m < mm - 1: m += 1 else: m = 0 if h < hh - 1: h += 1 else: h = 0 time = [h, m] tTr() timeCheck = [timeTr[0], timeTr[1], timeTr[2], timeTr[3]] for i in range(4): if timeCheck[i] == 2: timeCheck[i] = 5 elif timeCheck[i] == 5: timeCheck[i] = 2 chekH = timeCheck[3] * 10 + timeCheck[2] chekM =timeCheck[1] * 10 + timeCheck[0] if chekH <= hh - 1 and chekM <= mm - 1: h = str(timeTr[0]) + str(timeTr[1]) m = str(timeTr[2]) + str(timeTr[3]) print(f"{h}:{m}") break else: time[1] += 1
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
for i in range(int(input())): a=[int(j) for j in input().split()] h=a[0] m=a[1] s=input() l1=['0','1','2','5','8'] l2=['0','1','5','2','8'] H=s[:2] H0=H M=s[3:] while int(H)<h: if len(str(int(H)))==1: if H=='09': H='10' else: if (H[1] in l1) and int(l2[l1.index(H[1])]+'0')<m: break else: H='0'+str(int(H[1])+1) else: if (H[0] in l1) and (H[1] in l1) and int(l2[l1.index(H[1])]+l2[l1.index(H[0])])<m: break else: H=str(int(H)+1) if int(H)==h: H='00' if H0==H: while int(M) < m: if len(str(int(M))) == 1: if M == '09': M = '10' else: if M[1] in l1 and int(l2[l1.index(M[1])]+'0')<h: break else: M = '0' + str(int(M[1]) + 1) else: if (M[0] in l1) and (M[1] in l1) and int(l2[l1.index(M[1])]+l2[l1.index(M[0])])<h: break else: M = str(int(M) + 1) if int(M) == m: if len(str(int(H))) == 1: if H == '09': H = '10' else: H = '0' + str(int(H[1]) + 1) else: if int(H)==h-1: H='00' else: H = str(int(H) + 1) while int(H) < h: if len(str(int(H))) == 1: if H == '09': H = '10' else: if (H[1] in l1) and int(l2[l1.index(H[1])] + '0') < m: break else: H = '0' + str(int(H[1]) + 1) else: if (H[0] in l1) and (H[1] in l1) and int(l2[l1.index(H[1])] + l2[l1.index(H[0])]) < m: break else: H = str(int(H) + 1) if int(H) == h: H = '00' M = '00' print(H+':'+M) else: print(H + ':' + M) else: print(H+':'+'00')
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> #include <complex> #include <queue> #include <set> #include <unordered_set> #include <list> #include <chrono> #include <random> #include <iostream> #include <algorithm> #include <cmath> #include <string> #include <vector> #include <map> #include <unordered_map> #include <stack> #include <iomanip> #include <fstream> using namespace std; #define mem1(a) memset(a,-1,sizeof(a)) #define ln "\n" #define ll long long int int arr[10]; int h,m; bool check(int a , int b) { if (arr[a%10] == -1 || arr[a/10] == -1 || arr[b%10] == -1 || arr[b/10] == -1) { return 0; } int x = arr[b%10] * 10 + arr[b/10]; int y = arr[a%10] * 10 + arr[a/10]; if (x < h && y < m) { return 1; } else{ return 0; } } void solve(){ cin >> h >> m; string t; cin >> t; mem1(arr); arr[0] = 0; arr[1] = 1; arr[2] = 5; arr[5] = 2; arr[8] = 8; int a = (t[0] - '0')*10 + t[1] - '0'; int b = (t[3] - '0')*10 + t[4] - '0'; while(!check(a,b)) { b++; if (b==m) { a++; } b %=m; a %= h; } printf("%02d:",a); printf("%02d\n",b); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll t; cin >> t; for (ll i = 0; i < t; i++) { solve(); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; import java.lang.*; public class Codeforces { static Scanner sr = new Scanner(System.in); static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static int w[]={0,1,5,-1,-1,2,-1,-1,8,-1}; static boolean check(int p1,int p2,int q1,int q2,int a,int b) { if(w[p1]!=-1&&w[p2]!=-1&&w[q1]!=-1&&w[q2]!=-1) { if((w[q2]*10+w[q1]<a)&&(w[p2]*10+w[p1]<b)) return true; } return false; } public static void main(String[] args) throws java.lang.Exception { int T=sr.nextInt(); StringBuffer ans=new StringBuffer(); while(T-->0) { int h=sr.nextInt(); int m=sr.nextInt(); String a=sr.next(); int H1=a.charAt(0)-48; int H2=a.charAt(1)-48; int M1=a.charAt(3)-48; int M2=a.charAt(4)-48; while(1>0) { if(check(H1,H2,M1,M2,h,m)) break; else { int MM=M1*10+M2; int HH=H1*10+H2; ++MM; if(MM>=m) { ++HH; if(HH>=h) HH%=h; MM%=m; } H1=HH/10; H2=HH%10; M1=MM/10; M2=MM%10; } } ans.append(H1+""+H2+":"+M1+""+M2+"\n"); } System.out.println(ans); } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
# region fastio import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion REFLECTIONS={'0':'0','1':'1','2':'5','5':'2','8':'8'} def intArr(): return map(int,input().split()) def In(): return int(input()) def check(s): for i in s: if i not in REFLECTIONS: return 0 return 1 def validity(t1,h,m): if 0<=int(t1[0])<h and 0<=int(t1[1])<m: return 1 return 0 def reflect(t1): temp=[0,0] temp[0]=REFLECTIONS[t1[1][1]]+REFLECTIONS[t1[1][0]] temp[1]=REFLECTIONS[t1[0][1]]+REFLECTIONS[t1[0][0]] return temp.copy() def incTime(t1,h,m): hr,mi=t1[0],t1[1] mi=int(mi)+1 hr=int(hr) hr+=mi//m mi%=m hr%=h temp=[str(hr).zfill(2),str(mi).zfill(2)] return temp.copy() def func(h,m,l1): curr=l1.copy() while 1: temp1=''.join(curr) if check(temp1): reflected=reflect(curr) if validity(reflected.copy(),h,m): return ':'.join(curr) curr=incTime(curr,h,m) def main(): for _ in range(In()): h,m=intArr() l1=input().split(':') print(func(h,m,l1)) return if __name__ == '__main__': main()
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
T=int(input()) def convert(s): s=s[::-1] s1="" for z in s: if(z=="2"): s1=s1+"5" elif(z=="5"): s1=s1+"2" else: s1=s1+z return int(s1) for x in range(T): a=[int(y) for y in input().split()] h=a[0] m=a[1] s=input() h1=s[0:2] m1=s[3:5] l=['0','1','2','5','8'] while((h1[0] not in l)or(h1[1] not in l)or(m1[0] not in l)or(m1[1] not in l)or(convert(m1)>=h)or(convert(h1)>=m)): h1=int(h1) m1=int(m1) m1=m1+1 if(m1>=m): m1=m1-m h1=h1+1 if(h1>=h): h1=h1-h h1=str(h1) m1=str(m1) if(len(h1)!=2): h1='0'+h1 if(len(m1)!=2): m1='0'+m1 print(h1+":"+m1)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
# 0 1 2 5 8 ref = { '0': '0', '1': '1', '2': '5', '5': '2', '8': '8', ':': ':' } def reflect(time): return ''.join([ref[time[i]] for i in range(len(time)-1, -1, -1) ]) def check(time): if any(num not in ref for num in time): return False else: return True def next(num): if num in ['2', '3', '4']: return '5' if num in ['5', '6', '7']: return '8' if num in ['8', '9']: return '0' return str(int(num)+1) def check_HH(HH, MM): ## Check HH is not reflectable or its reflection is not withen range while (not check(HH) or int(reflect(HH)) >= m or int(HH) >= h): # Nearest HH and set MM to 00 if not check(HH[0]): HH = next(HH[0]) + '0' else: HH = HH[0] + next(HH[1]) if HH[1] == '0': HH = next(HH[0]) + HH[1] MM = '00' return (HH, MM) cases = int(input()) for case in range(0, cases): inputs = [int(x) for x in input().split(" ")] time = input() HH = time[0:2] MM = time[3:] h = inputs[0] m = inputs[1] (HH, MM) = check_HH(HH,MM) while (not check(MM) or int(reflect(MM)) >= h or int(MM) >=m): # Nearest MM and set MM to 00 if not check(MM[0]): MM = next(MM[0]) + '0' if MM[0] == '0': # Check HH again! HH = HH[0] + next(HH[1]) if HH[1] == '0': HH = next(HH[0]) + HH[1] (HH, MM) = check_HH(HH,MM) else: MM = MM[0] + next(MM[1]) if MM[1] == '0': MM = next(MM[0]) + MM[1] if MM[0] == '0': # Check HH again! HH = HH[0] + next(HH[1]) if HH[1] == '0': HH = next(HH[0]) + HH[1] (HH, MM) = check_HH(HH,MM) print(HH + ':' + MM)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include "bits/stdc++.h" #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") // #pragma GCC optimization ("O3") // #pragma GCC optimization ("unroll-loops") // #include <ext/pb_ds/assoc_container.hpp> // #include <ext/pb_ds/tree_policy.hpp> // using namespace __gnu_pbds; //#include <boost/multiprecision/cpp_int.hpp> //using namespace boost::multiprecision; using namespace std; #define all(c) (c).begin(),(c).end() #define endl "\n" #define ff first #define ss second #define allr(c) (c).rbegin(),(c).rend() #define ifr(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define pof pop_front #define pob pop_back #define pb emplace_back #define pf emplace_front #define fstm(m,n,r) m.reserve(n);m.max_load_factor(r) #define mp make_pair #define mt make_tuple #define inf LLONG_MAX #define os tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> //order_of_key (k) : Number of items strictly smaller than k . //find_by_order(k) : K-th element in a set (counting from zero). const double PI = acos(-1); typedef complex<double> cd; typedef long long ll; ll gcd(){return 0ll;} template<typename T,typename... Args> T gcd(T a,Args... args) { return __gcd(a,(__typeof(a))gcd(args...)); } typedef map<ll,ll> mll; typedef map<string,ll> msll; typedef unordered_map<ll,ll> umap; typedef vector<ll> vll; typedef pair<ll,ll> pll; typedef long double ld; #define mod 1000000007 const int N = 1e5 + 2; int h, m; int refDigit(char ch) { int x = ch-'0'; switch(x) { case 0: return 0; case 1: return 1; case 2: return 5; case 5: return 2; case 8: return 8; } return -1; } bool valid(string &tim) { int hh = (tim[0]-'0')*10 + (tim[1]-'0'); int mm = (tim[3]-'0')*10 + (tim[4]-'0'); // cout<<tim<<" "<<hh<<" "<<mm<<endl; return hh<h && mm<m; } bool check(string &tim) { string rev = tim; int x, j = 5; // cout<<tim<<endl; for(auto &it: tim) { j--; if(it == ':') continue; x = refDigit(it); // cout<<x<<" "; if(x == -1) return 0; rev[j] = x + '0'; } // cout<<rev<<endl; return valid(rev); } void inc(string &tim) { int hh = (tim[0]-'0')*10 + (tim[1]-'0'); int mm = (tim[3]-'0')*10 + (tim[4]-'0'); // cout<<tim<<endl; // cout<<hh<<" "<<mm<<endl; mm++; if(mm == m) { mm=0; hh++; if(hh == h) hh = 0; } // cout<<hh<<" "<<mm<<endl; tim[0] = (hh/10) + '0'; tim[1] = (hh%10) + '0'; tim[3] = (mm/10) + '0'; tim[4] = (mm%10) + '0'; // tim = to_string(hh) + ":" + to_string(mm); } int Solve() { string tim, in, de; cin>>h>>m>>tim; in = de = tim; if(check(tim)) { cout<<tim<<endl; return 0; } while(1) { inc(in); if(check(in)) { cout<<in<<endl; return 0; } } return 0; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); // #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // #endif int T;cin>>T;while(T--) { Solve(); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<iostream> #include<cstdio> using namespace std; int T; string s; int h,m; int x,y; int fl[10]={0,1,5,-1,-1,2,-1,-1,8,-1}; void print(int x,int y) { cout<<x/10<<x%10<<":"<<y/10<<y%10<<endl; } void add(int &x,int &y) { y++; if(y==m) y=0,x++; if(x==h) x=0; } int op(int x,int y) { int a=x/10,b=x%10; int c=y/10,d=y%10; if(fl[a]==-1 || fl[b]==-1 || fl[c]==-1 || fl[d]==-1) return 0; x=fl[d]*10+fl[c]; y=fl[b]*10+fl[a]; if(x>=h || y>=m) return 0; return 1; } int main() { cin>>T; while(T--) { cin>>h>>m>>s; x=(s[0]-'0')*10+(s[1]-'0'); y=(s[3]-'0')*10+(s[4]-'0'); while(op(x,y)==0) add(x,y); print(x,y); } }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
symmetric_digits = { '0': '0', '1': '1', '2': '5', '5': '2', '8': '8', } def invert_digits(tt): res = '' for d in reversed(f'{tt:02d}'): if d not in symmetric_digits: return float('inf') res += symmetric_digits[d] return int(res) def valid(hh, mm, h, m): return invert_digits(hh) < m and invert_digits(mm) < h for _ in range(int(input())): h, m = map(int, input().split()) sh, sm = map(int, input().split(':')) while True: if valid(sh, sm, h, m): print(f'{sh:02d}:{sm:02d}') break sm += 1 sh += sm // m sm %= m sh %= h
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
r = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'} d = {} o = '01258' for i in o: for j in o: for k in o: for l in o: d[int(i + j, 10), int(k + l, 10)] = (int(r[l] + r[k], 10), int(r[j] + r[i], 10)) def solve(): h, m = map(int, raw_input().split()) s = map(int, raw_input().split(':'), (10, 10)) for i in xrange(h * m): if (s[0], s[1]) in d: e = d[s[0], s[1]] if 0 <= e[0] < h and 0 <= e[1] < m: print "%02d:%02d" % (s[0], s[1]) return s[1] += 1 if s[1] >= m: s[1] = 0 s[0] += 1 if s[0] >= h: s[0] = 0 T = int(raw_input()) for t in xrange(T): solve()
PYTHON
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; import java.lang.*; import java.io.*; import java.awt.*; // U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................ //JUst keep faith in ur strengths .................................................. // ASCII = 48 + i ;// 2^28 = 268,435,456 > 2* 10^8 // log 10 base 2 = 3.3219 // odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1 x >=4 // FOR ANY ODD NO N : N,N-1,N-2 //ALL ARE PAIRWISE COPRIME //THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS // two consecutive odds are always coprime to each other // two consecutive even have always gcd = 2 ; // Rectangle r = new Rectangle(int x , int y,int widht,int height) //Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height)) //BY DEFAULT Priority Queue is MIN in nature in java //to use as max , just push with negative sign and change sign after removal // We can make a sieve of max size 1e7 .(no time or space issue) // In 1e7 starting nos we have about 66*1e4 prime nos // In 1e6 starting nos we have about 78,498 prime nos public class Main { // static int[] arr = new int[100002] ; // static int[] dp = new int[100002] ; static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out); } String next(){ while(st==null || !st.hasMoreElements()){ try{ st= new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str = ""; try{ str=br.readLine(); } catch(IOException e){ e.printStackTrace(); } return str; } } //////////////////////////////////////////////////////////////////////////////////// public static int countDigit(long n) { return (int)Math.floor(Math.log10(n) + 1); } ///////////////////////////////////////////////////////////////////////////////////////// public static int sumOfDigits(long n) { if( n< 0)return -1 ; int sum = 0; while( n > 0) { sum = sum + (int)( n %10) ; n /= 10 ; } return sum ; } ////////////////////////////////////////////////////////////////////////////////////////////////// public static long arraySum(int[] arr , int start , int end) { long ans = 0 ; for(int i = start ; i <= end ; i++)ans += arr[i] ; return ans ; } ///////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// public static void swapArray(int[] arr , int start , int end) { while(start < end) { int temp = arr[start] ; arr[start] = arr[end]; arr[end] = temp; start++ ;end-- ; } } ////////////////////////////////////////////////////////////////////////////////// static long factorial(long a) { if(a== 0L || a==1L)return 1L ; return a*factorial(a-1L) ; } /////////////////////////////////////////////////////////////////////////////// public static int[][] rotate(int[][] input){ int n =input.length; int m = input[0].length ; int[][] output = new int [m][n]; for (int i=0; i<n; i++) for (int j=0;j<m; j++) output [j][n-1-i] = input[i][j]; return output; } /////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////// //////////////////////////////////////////////// public static boolean isPowerOfTwo(long n) { if(n==0) return false; if(((n ) & (n-1)) == 0 ) return true ; else return false ; } ///////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// public static String reverse(String input) { StringBuilder str = new StringBuilder("") ; for(int i =input.length()-1 ; i >= 0 ; i-- ) { str.append(input.charAt(i)); } return str.toString() ; } /////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// public static boolean isPossibleTriangle(int a ,int b , int c) { if( a + b > c && c+b > a && a +c > b)return true ; else return false ; } //////////////////////////////////////////////////////////////////////////////////////////// static long xnor(long num1, long num2) { if (num1 < num2) { long temp = num1; num1 = num2; num2 = temp; } num1 = togglebit(num1); return num1 ^ num2; } static long togglebit(long n) { if (n == 0) return 1; long i = n; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return i ^ n; } /////////////////////////////////////////////////////////////////////////////////////////////// public static int xorOfFirstN(int n) { if( n % 4 ==0)return n ; else if( n % 4 == 1)return 1 ; else if( n % 4 == 2)return n+1 ; else return 0 ; } ////////////////////////////////////////////////////////////////////////////////////////////// public static int gcd(int a, int b ) { if(b==0)return a ; else return gcd(b,a%b) ; } public static long gcd(long a, long b ) { if(b==0)return a ; else return gcd(b,a%b) ; } //////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c , int d ) { int temp = lcm(a,b , c) ; int ans = lcm(temp ,d ) ; return ans ; } /////////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a, int b ,int c ) { int temp = lcm(a,b) ; int ans = lcm(temp ,c) ; return ans ; } //////////////////////////////////////////////////////////////////////////////////////// public static int lcm(int a , int b ) { int gc = gcd(a,b); return (a/gc)*b ; } public static long lcm(long a , long b ) { long gc = gcd(a,b); return (a/gc)*b; } /////////////////////////////////////////////////////////////////////////////////////////// static boolean isPrime(long n) { if(n==1) { return false ; } boolean ans = true ; for(long i = 2L; i*i <= n ;i++) { if(n% i ==0) { ans = false ;break ; } } return ans ; } static boolean isPrime(int n) { if(n==1) { return false ; } boolean ans = true ; for(int i = 2; i*i <= n ;i++) { if(n% i ==0) { ans = false ;break ; } } return ans ; } /////////////////////////////////////////////////////////////////////////// static int sieve = 1000000 ; static boolean[] prime = new boolean[sieve + 1] ; public static void sieveOfEratosthenes() { // FALSE == prime // TRUE == COMPOSITE // FALSE== 1 // time complexity = 0(NlogLogN)== o(N) // gives prime nos bw 1 to N for(int i = 4; i<= sieve ; i++) { prime[i] = true ; i++ ; } for(int p = 3; p*p <= sieve; p++) { if(prime[p] == false) { for(int i = p*p; i <= sieve; i += p) prime[i] = true; } p++ ; } } /////////////////////////////////////////////////////////////////////////////////// public static void sortD(int[] arr , int s , int e) { sort(arr ,s , e) ; int i =s ; int j = e ; while( i < j) { int temp = arr[i] ; arr[i] =arr[j] ; arr[j] = temp ; i++ ; j-- ; } return ; } ///////////////////////////////////////////////////////////////////////////////////////// public static long countSubarraysSumToK(long[] arr ,long sum ) { HashMap<Long,Long> map = new HashMap<>() ; int n = arr.length ; long prefixsum = 0 ; long count = 0L ; for(int i = 0; i < n ; i++) { prefixsum = prefixsum + arr[i] ; if(sum == prefixsum)count = count+1 ; if(map.containsKey(prefixsum -sum)) { count = count + map.get(prefixsum -sum) ; } if(map.containsKey(prefixsum )) { map.put(prefixsum , map.get(prefixsum) +1 ); } else{ map.put(prefixsum , 1L ); } } return count ; } /////////////////////////////////////////////////////////////////////////////////////////////// // KMP ALGORITHM : TIME COMPL:O(N+M) // FINDS THE OCCURENCES OF PATTERN AS A SUBSTRING IN STRING //RETURN THE ARRAYLIST OF INDEXES // IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING public static ArrayList<Integer> kmpAlgorithm(String str , String pat) { ArrayList<Integer> list =new ArrayList<>(); int n = str.length() ; int m = pat.length() ; String q = pat + "#" + str ; int[] lps =new int[n+m+1] ; longestPefixSuffix(lps, q,(n+m+1)) ; for(int i =m+1 ; i < (n+m+1) ; i++ ) { if(lps[i] == m) { list.add(i-2*m) ; } } return list ; } public static void longestPefixSuffix(int[] lps ,String str , int n) { lps[0] = 0 ; for(int i = 1 ; i<= n-1; i++) { int l = lps[i-1] ; while( l > 0 && str.charAt(i) != str.charAt(l)) { l = lps[l-1] ; } if(str.charAt(i) == str.charAt(l)) { l++ ; } lps[i] = l ; } } /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n // TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1 // or n and the no will be coprime in nature //time : O(n*(log(logn))) public static void eulerTotientFunction(int[] arr ,int n ) { for(int i = 1; i <= n ;i++)arr[i] =i ; for(int i= 2 ; i<= n ;i++) { if(arr[i] == i) { arr[i] =i-1 ; for(int j =2*i ; j<= n ; j+= i ) { arr[j] = (arr[j]*(i-1))/i ; } } } return ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long nCr(int n,int k) { long ans=1L; k=k>n-k?n-k:k; int j=1; for(;j<=k;j++,n--) { if(n%j==0) { ans*=n/j; }else if(ans%j==0) { ans=ans/j*n; }else { ans=(ans*n)/j; } } return ans; } /////////////////////////////////////////////////////////////////////////////////////////// public static ArrayList<Integer> allFactors(int n) { ArrayList<Integer> list = new ArrayList<>() ; for(int i = 1; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } public static ArrayList<Long> allFactors(long n) { ArrayList<Long> list = new ArrayList<>() ; for(long i = 1L; i*i <= n ;i++) { if( n % i == 0) { if(i*i == n) { list.add(i) ; } else{ list.add(i) ; list.add(n/i) ; } } } return list ; } //////////////////////////////////////////////////////////////////////////////////////////////////// static final int MAXN = 1000001; static int spf[] = new int[MAXN]; static void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) spf[i] = i; for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { if (spf[i] == i) { for (int j=i*i; j<MAXN; j+=i) if (spf[j]==j) spf[j] = i; } } } static ArrayList<Integer> getPrimeFactorization(int x) { ArrayList<Integer> ret = new ArrayList<Integer>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } ////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() public static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; //Copy data to temp arrays for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } ///////////////////////////////////////////////////////////////////////////////////////// public static long knapsack(int[] weight,long value[],int maxWeight){ int n= value.length ; //dp[i] stores the profit with KnapSack capacity "i" long []dp = new long[maxWeight+1]; //initially profit with 0 to W KnapSack capacity is 0 Arrays.fill(dp, 0); // iterate through all items for(int i=0; i < n; i++) //traverse dp array from right to left for(int j = maxWeight; j >= weight[i]; j--) dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]); /*above line finds out maximum of dp[j](excluding ith element value) and val[i] + dp[j-wt[i]] (including ith element value and the profit with "KnapSack capacity - ith element weight") */ return dp[maxWeight]; } /////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// // to return max sum of any subarray in given array public static long kadanesAlgorithm(long[] arr) { if(arr.length == 0)return 0 ; long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } ///////////////////////////////////////////////////////////////////////////////////////////// public static long kadanesAlgorithm(int[] arr) { if(arr.length == 0)return 0 ; long[] dp = new long[arr.length] ; dp[0] = arr[0] ; long max = dp[0] ; for(int i = 1; i < arr.length ; i++) { if(dp[i-1] > 0) { dp[i] = dp[i-1] + arr[i] ; } else{ dp[i] = arr[i] ; } if(dp[i] > max)max = dp[i] ; } return max ; } /////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING // JUST CALL generatePermutation( str, start, end) start :inclusive ,end : exclusive //Function for swapping the characters at position I with character at position j public static String swapString(String a, int i, int j) { char[] b =a.toCharArray(); char ch; ch = b[i]; b[i] = b[j]; b[j] = ch; return String.valueOf(b); } //Function for generating different permutations of the string public static void generatePermutation(String str, int start, int end) { //Prints the permutations if (start == end-1) System.out.println(str); else { for (int i = start; i < end; i++) { //Swapping the string by fixing a character str = swapString(str,start,i); //Recursively calling function generatePermutation() for rest of the characters generatePermutation(str,start+1,end); //Backtracking and swapping the characters again. str = swapString(str,start,i); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public static long factMod(long n, long mod) { if (n <= 1) return 1; long ans = 1; for (int i = 1; i <= n; i++) { ans = (ans * i) % mod; } return ans; } ///////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////// public static long power(int a ,int b) { //time comp : o(logn) long x = (long)(a) ; long n = (long)(b) ; if(n==0)return 1 ; if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1) { ans = ans *x ; } n = n/2L ; x = x*x ; } return ans ; } public static long power(long a ,long b) { //time comp : o(logn) long x = (a) ; long n = (b) ; if(n==0)return 1L ; if(n==1)return x; long ans =1L ; while(n>0) { if(n % 2 ==1) { ans = ans *x ; } n = n/2L ; x = x*x ; } return ans ; } //////////////////////////////////////////////////////////////////////////////////////////////////// public static long powerMod(long x, long n, long mod) { //time comp : o(logn) if(n==0)return 1L ; if(n==1)return x; long ans = 1; while (n > 0) { if (n % 2 == 1) ans = (ans * x) % mod; x = (x * x) % mod; n /= 2; } return ans; } ////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// /* lowerBound - finds largest element equal or less than value paased upperBound - finds smallest element equal or more than value passed if not present return -1; */ public static long lowerBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static int lowerBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]<=k) { ans=arr[mid]; start=mid+1; } else { end=mid-1; } } return ans; } public static long upperBound(long[] arr,long k) { long ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } public static int upperBound(int[] arr,int k) { int ans=-1; int start=0; int end=arr.length-1; while(start<=end) { int mid=(start+end)/2; if(arr[mid]>=k) { ans=arr[mid]; end=mid-1; } else { start=mid+1; } } return ans; } ////////////////////////////////////////////////////////////////////////////////////////// public static void printArray(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printArrayln(int[] arr , int si ,int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printLArray(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } } public static void printLArrayln(long[] arr , int si , int ei) { for(int i = si ; i <= ei ; i++) { out.print(arr[i] +" ") ; } out.println() ; } public static void printtwodArray(int[][] ans) { for(int i = 0; i< ans.length ; i++) { for(int j = 0 ; j < ans[0].length ; j++)out.print(ans[i][j] +" "); out.println() ; } out.println() ; } static long modPow(long a, long x, long p) { //calculates a^x mod p in logarithmic time. a = a % p ; if(a == 0)return 0L ; long res = 1L; while(x > 0) { if( x % 2 != 0) { res = (res * a) % p; } a = (a * a) % p; x =x/2; } return res; } static long modInverse(long a, long p) { //calculates the modular multiplicative of a mod p. //(assuming p is prime). return modPow(a, p-2, p); } static long[] factorial = new long[1000001] ; static void modfac(long mod) { factorial[0]=1L ; factorial[1]=1L ; for(int i = 2; i<= 1000000 ;i++) { factorial[i] = factorial[i-1] *(long)(i) ; factorial[i] = factorial[i] % mod ; } } static long modBinomial(long n, long r, long p) { // calculates C(n,r) mod p (assuming p is prime). if(n < r) return 0L ; long num = factorial[(int)(n)] ; long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) % p ; long ans = num*(modInverse(den,p)) ; ans = ans % p ; return ans ; } static void update(int val , long[] bit ,int n) { for( ; val <= n ; val += (val &(-val)) ) { bit[val]++ ; } } static long query(int val , long[] bit , int n) { long ans = 0L; for( ; val >=1 ; val-=(val&(-val)) )ans += bit[val]; return ans ; } static int countSetBits(long n) { int count = 0; while (n > 0) { n = (n) & (n - 1L); count++; } return count; } static int abs(int x) { if(x < 0)x = -1*x ; return x ; } static long abs(long x) { if(x < 0)x = -1L*x ; return x ; } //////////////////////////////////////////////////////////////////////////////////////////////// static void p(int val) { out.print(val) ; } static void p() { out.print(" ") ; } static void pln(int val) { out.println(val) ; } static void pln() { out.println() ; } static void p(long val) { out.print(val) ; } static void pln(long val) { out.println(val) ; } static void yes() { out.println("YES") ; } static void no() { out.println("NO") ; } //////////////////////////////////////////////////////////////////////////////////////////// // calculate total no of nos greater than or equal to key in sorted array arr static int bs(int[] arr, int s ,int e ,int key) { if( s> e)return 0 ; int mid = (s+e)/2 ; if(arr[mid] <key) { return bs(arr ,mid+1,e , key) ; } else{ return bs(arr ,s ,mid-1, key) + e-mid+1; } } // static ArrayList<Integer>[] adj ; // static int mod= 1000000007 ; static HashMap<Character,Integer> map = new HashMap<>() ; static boolean check(int h ,int m , int hour ,int min) { String x = Integer.toString(h) ; String y = Integer.toString(m) ; while(x.length() < 2 )x="0"+x ; while(y.length() < 2 )y="0"+y ; int a = map.get(x.charAt(0)) ;int b = map.get(x.charAt(1)) ; int c = map.get(y.charAt(0)) ;int d = map.get(y.charAt(1)) ; if(a==-1 || b== -1 || c==-1 || d==-1)return false ; int e = (10*d)+c ; int f = (10*b)+a ; if(e>= hour)return false ; if(f>= min)return false ; return true ; } static String help(int x) { if(x== 0)return "00" ; if(x >=10 ) { return Integer.toString(x) ; } return "0"+Integer.toString(x) ; } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// public static void solve() { FastReader scn = new FastReader() ; //DEBUGGING - // 1 - I/O - CHECK PRINTING OF NEXT LINE , READ INPUT , EXTRA LINE PRINT. //2-OVERFLOW ERROR. //3 -STATIC VARIABLE INITIALIZATION (INT MAINLIY) //4-DIVISION ERROR(FLOOR/CEIL) or DIVIDE BY ZERO //5-MOD -(MOD BY 1 OR 0 ) //Scanner scn = new Scanner(System.in); //int[] store = {2 ,3, 5 , 7 ,11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 } ; // product of first 11 prime nos is greater than 10 ^ 12; //sieve() ; //ArrayList<Integer> arr[] = new ArrayList[n] ; ArrayList<Integer> list = new ArrayList<>() ; ArrayList<Long> lista = new ArrayList<>() ; ArrayList<Long> listb = new ArrayList<>() ; // ArrayList<Integer> lista = new ArrayList<>() ; // ArrayList<Integer> listb = new ArrayList<>() ; //ArrayList<String> lists = new ArrayList<>() ; //HashMap<Integer,Integer> map = new HashMap<>() ; //HashMap<Long,Long> map = new HashMap<>() ; HashMap<Integer,Integer> mapx = new HashMap<>() ; HashMap<Integer,Integer> mapy = new HashMap<>() ; //HashMap<String,Integer> maps = new HashMap<>() ; //HashMap<Integer,Boolean> mapb = new HashMap<>() ; //HashMap<Point,Integer> point = new HashMap<>() ; Set<Integer> set = new HashSet<>() ; Set<Integer> setx = new HashSet<>() ; Set<Integer> sety = new HashSet<>() ; StringBuilder sb =new StringBuilder("") ; //Collections.sort(list); //if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ; //else map.put(arr[i],1) ; // if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ; // else map.put(temp,1) ; //int bit =Integer.bitCount(n); // gives total no of set bits in n; // Arrays.sort(arr, new Comparator<Pair>() { // @Override // public int compare(Pair a, Pair b) { // if (a.first != b.first) { // return a.first - b.first; // for increasing order of first // } // return a.second - b.second ; //if first is same then sort on second basis // } // }); map.put('0',0) ;map.put('1',1) ;map.put('2',5) ;map.put('3',-1) ;map.put('4',-1) ;map.put('5',2) ; map.put('6',-1) ;map.put('7',-1) ;map.put('8',8) ;map.put('9',-1) ; int testcase = 1; testcase = scn.nextInt() ; for(int testcases =1 ; testcases <= testcase ;testcases++) { //if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ; //if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ; //adj = new ArrayList[n] ; // for(int i = 0; i< n; i++) // { // adj[i] = new ArrayList<Integer>(); // } // long n = scn.nextLong() ; //String s = scn.next() ; int hour= scn.nextInt() ;int min= scn.nextInt() ; String s = scn.next() ; int h = (s.charAt(0) -'0')*10 + (s.charAt(1)-'0') ; int m = (s.charAt(3) -'0')*10 + (s.charAt(4)-'0') ; if(check(h,m,hour,min))out.println(s) ; else{ int f= 0 ; for(int x= m+1; x< min ; x++) { if(check(h,x,hour,min)) { out.println(help(h)+":" +help(x)) ;f=1 ; break ; } } if(f== 0) { for(int y = h +1 ; y < hour ; y++) { for(int x=0 ; x < min ;x++) { if(check(y,x,hour,min)) { out.println(help(y)+":"+ help(x)) ;f=1 ;break ; } } if(f==1)break ; } } if(f == 0)out.println("00:00") ; } // s vala //out.println(ans) ; //out.println(ans+" "+in) ; //out.println("Case #" + testcases + ": " + ans ) ; //out.println("@") ; set.clear() ; sb.delete(0 , sb.length()) ; list.clear() ;lista.clear() ;listb.clear() ; //map.clear() ; mapx.clear() ; mapy.clear() ; setx.clear() ;sety.clear() ; } // test case end loop out.flush() ; } // solve fn ends public static void main (String[] args) throws java.lang.Exception { solve() ; } } class Pair { int first ; int second ; public Pair(int x, int y) { this.first = x ;this.second = y ; } @Override public boolean equals(Object obj) { if(obj == this)return true ; if(obj == null)return false ; if(this.getClass() != obj.getClass()) { return false ; } Pair other = (Pair)(obj) ; if(this.first != other.first)return false ; if(this.second != other.second)return false ; return true ; } @Override public int hashCode() { return this.first^this.second ; } @Override public String toString() { String ans = "" ; ans += this.first ; ans += " "; ans += this.second ; return ans ; } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
valid={0:0,1:1,2:5,5:2,8:8} for _ in range(int(input())): h,m=map(int,input().split()) hour,min=input().split(":") while 1: if int(min)>=m: min="0" hour=str(int(hour)+1) if int(hour)>=h:hour="0" min="0"*(len(min)==1)+min hour = "0" * (len(hour) == 1) + hour for i in range(2): if int(hour[i]) not in valid or int(min[i]) not in valid: min=str(int(min)+1) break else: if int(str(valid[int(min[1])])+str(valid[int(min[0])]))>=h: min = str(int(min) + 1);continue if int(str(valid[int(hour[1])])+str(valid[int(hour[0])]))>=m: min = str(int(min) + 1);continue print(hour+":"+min) break
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.Scanner; public class TaskB { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int j = 0; j < t; j++) { int h = in.nextInt(); int m = in.nextInt(); in.nextLine(); String time = in.nextLine(); while (true) { int hh = Integer.parseInt(time.split(":")[0]); int mm = Integer.parseInt(time.split(":")[1]); char[] c = time.toCharArray(); for (int i = 0; i < c.length / 2; i++) { char tmp = c[i]; c[i] = c[c.length - i - 1]; c[c.length - i - 1] = tmp; } for (int i = 0; i < c.length; i++) { if (c[i] == '2') { c[i] = '5'; } else if (c[i] == '5') { c[i] = '2'; } } String rev_time = new String(c); int hh1 = Integer.parseInt(rev_time.split(":")[0]); int mm1 = Integer.parseInt(rev_time.split(":")[1]); if (!(rev_time.contains("3") || rev_time.contains("4") || rev_time.contains("6") || rev_time.contains("7") || rev_time.contains("9")) && hh1 < h && mm1 < m) { System.out.println(time); break; } mm++; if (mm == m) { mm = 0; hh++; } if (hh == h) { hh = 0; } time = ((hh / 10 == 0) ? "0" + hh : String.valueOf(hh)) + ":" + ((mm / 10 == 0) ? "0" + mm : String.valueOf(mm)); } } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; import java.util.StringTokenizer; public class Main { public Main() throws FileNotFoundException { // // File file = Paths.get("input.txt").toFile(); // if (file.exists()) { // System.setIn(new FileInputStream(file)); // } long t = System.currentTimeMillis(); FastReader reader = new FastReader(); int tt = reader.nextInt(); for (int ttt = 0; ttt < tt; ttt++) { int h = reader.nextInt(); int m = reader.nextInt(); String str = reader.next(); System.out.println(getNextValid(str, h, m)); // 12:21 // 00:00 // 52:28 // 00:00 // 00:00 } } private String getNextValid(String str, int h, int m) { String hs = str.split(":")[0]; String ms = str.split(":")[1]; int ch = Integer.valueOf(hs); int cm = Integer.valueOf(ms); for (int ih = ch; ih < h; ih++) { int start=cm; if(ih!=ch) { start=0; } for (int im = start; im < m; im++) { String newHourStr = ih + ""; if (newHourStr.length() == 1) { newHourStr = "0" + newHourStr; } String newMinuteStr = im + ""; if (newMinuteStr.length() == 1) { newMinuteStr = "0" + newMinuteStr; } String mirrorMinuteStr = mirror(newHourStr); String mirrorHourStr = mirror(newMinuteStr); // .ch.System.out.println(mirrorHourStr + ":" + mirrorMinuteStr); if (mirrorHourStr == null || mirrorMinuteStr == null) { continue; } else { int newHour = Integer.valueOf(mirrorHourStr); int newMinute = Integer.valueOf(mirrorMinuteStr); if (newHour >= 0 && newHour < h && newMinute >= 0 && newMinute < m) { return newHourStr + ":" + newMinuteStr; } } } } return "00:00"; } private String mirror(String str) { int first = (int) (str.charAt(0) - '0'); int second = (int) (str.charAt(1) - '0'); int newFirst = newNum(second); int newSecond = newNum(first); if (newFirst != -1 && newSecond != -1) { return newFirst + "" + newSecond; } return null; } private int newNum(int num) { // 1-1,2-5,5-2,8-8,0-0 if (num == 1) { return 1; } if (num == 2) { return 5; } if (num == 5) { return 2; } if (num == 8) { return 8; } if (num == 0) { return 0; } return -1; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws FileNotFoundException { new Main(); } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
a=int(input()) reflect=[0,1,5,-1,-1,2,-1,-1,8,-1] for i in range(a): h,m=map(int,input().split()) s=input() l1=[h%10,h//10] l2=[m%10,m//10] x=s.index(':') s1=int(s[0:2]) s2=int(s[3:]) glag=0 value=(s1*m)+(s2) ori=h*m cnt=0 while(glag==0): time=(cnt+value)%ori i=time//m j=time%m cnt+=1 t1=str(i) t2=str(j) if(len(t1)==1): t1='0'+t1 if(len(t2)==1): t2='0'+t2 flag=0 for i in range(len(t1)): if(reflect[int(t1[i])]==-1): flag=1 break; for i in range(len(t2)): if(reflect[int(t2[i])]==-1): flag=1 break; if(flag==0 and glag==0): tig=((reflect[int(t2[1])])*10)+reflect[int(t2[0])] total=tig*m rig=(reflect[int(t1[1])]*10)+reflect[int(t1[0])] total+=rig if(total>=ori or rig>=m): continue; glag=1 print(t1,end="") print(':',end="") print(t2)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
d = {0:0,1:1,2:5,5:2,8:8} def check(curr): ones,tens = curr%10,curr//10 if ones in d and tens in d: return d[ones]*10 + d[tens] return 10**5 def solve(): for _ in range(int(input())): h,m =[int(x) for x in input().split()] x,y = map(int , input().split(":")) while True: if check(x)<m and check(y)<h: break y += 1 if y==m: y=0 x = (x+1)%h print(str(x).rjust(2,"0") + ":" + str(y).rjust(2,"0")) solve()
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
t=int(input()) for z in range(t): h,m=map(int,input().split()) s=input() hrs=s[:2] mi=s[3:] while(1): arr=[] if int(mi)==m: mi=0 if int(hrs)<h-1: hrs=int(hrs)+1 else: hrs=0 if len(str(hrs))==1: hrs = "0" + str(hrs) if len(str(mi))==1: mi = "0" + str(mi) if "3" not in str(hrs)+str(mi) and "4" not in str(hrs)+str(mi) and "6" not in str(hrs)+str(mi) and "7" not in str(hrs)+str(mi) and "9" not in str(hrs)+str(mi): moo=list(str(hrs)+str(mi)) for i in range(3,-1,-1): if moo[i]=="2": arr.append("5") elif moo[i]=="5": arr.append("2") else: arr.append(moo[i]) if int("".join(arr[:2]))<h and int("".join(arr[2:]))<m: break mi = int(mi) + 1 print("".join(moo[:2])+":"+"".join(moo[2:]))
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
# DEFINING SOME GOOD STUFF from math import * import threading import sys from collections import defaultdict from pprint import pprint sys.setrecursionlimit(300000) # threading.stack_size(10**8) ''' -> if you are increasing recursionlimit then remember submitting using python3 rather pypy3 -> sometimes increasing stack size don't work locally but it will work on CF ''' mod = 10 ** 9 inf = 10 ** 15 yes = 'YES' no = 'NO' # ------------------------------FASTIO---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # _______________________________________________________________# def npr(n, r): return factorial(n) // factorial(n - r) if n >= r else 0 def ncr(n, r): return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0 def lower_bound(li, num): answer = -1 start = 0 end = len(li) - 1 while (start <= end): middle = (end + start) // 2 if li[middle] >= num: answer = middle end = middle - 1 else: start = middle + 1 return answer # min index where x is not less than num def upper_bound(li, num): answer = -1 start = 0 end = len(li) - 1 while (start <= end): middle = (end + start) // 2 if li[middle] <= num: answer = middle start = middle + 1 else: end = middle - 1 return answer # max index where x is not greater than num def abs(x): return x if x >= 0 else -x def binary_search(li, val): # print(lb, ub, li) ans = -1 lb = 0 ub = len(li) - 1 while (lb <= ub): mid = (lb + ub) // 2 # print('mid is',mid, li[mid]) if li[mid] > val: ub = mid - 1 elif val > li[mid]: lb = mid + 1 else: ans = mid # return index break return ans def kadane(x): # maximum sum contiguous subarray sum_so_far = 0 current_sum = 0 for i in x: current_sum += i if current_sum < 0: current_sum = 0 else: sum_so_far = max(sum_so_far, current_sum) return sum_so_far def pref(li): pref_sum = [0] for i in li: pref_sum.append(pref_sum[-1] + i) return pref_sum def SieveOfEratosthenes(n): prime = [True for i in range(n + 1)] p = 2 li = [] while (p * p <= n): if (prime[p] == True): for i in range(p * p, n + 1, p): prime[i] = False p += 1 for p in range(2, len(prime)): if prime[p]: li.append(p) return li def primefactors(n): factors = [] while (n % 2 == 0): factors.append(2) n //= 2 for i in range(3, int(sqrt(n)) + 1, 2): # only odd factors left while n % i == 0: factors.append(i) n //= i if n > 2: # incase of prime factors.append(n) return factors def prod(li): ans = 1 for i in li: ans *= i return ans def dist(a, b): d = abs(a[1] - b[1]) + abs(a[2] - b[2]) return d def power_of_n(x, n): cnt = 0 while (x % n == 0): cnt += 1 x //= n return cnt def check(time, temphh, tempmm): changed = [0, 1, 5, inf, inf, 2, inf, inf, 8, inf] if time[0] > temphh-1 or time[1] > tempmm - 1: return 0 rev_min = changed[time[0]//10] + changed[(time[0]%10)]*10 rev_hour = changed[time[1]//10] + changed[(time[1]%10)]*10 if rev_hour > temphh - 1 or rev_min > tempmm - 1: return 0 return 1 # _______________________________________________________________# # def main(): # for _ in range(1): for _ in range(int(input()) if True else 1): # n = int(input()) temphh, tempmm = map(int, input().split()) time = list(map(int, input().split(':'))) # b = list(map(int, input().split())) # c = list(map(int, input().split())) # s = list(input()) # s = input() f = check(time, temphh, tempmm) while not f: time[1] += 1 if time[1] > tempmm-1: time[0] += 1 if time[0] > temphh-1 and time[1] > tempmm - 1: time[0] = 0 time[1] = 0 break time[1] = 0 f = check(time, temphh, tempmm) # print(time) print(str(time[0]).rjust(2,'0')+':'+str(time[1]).rjust(2,'0')) # t = threading.Thread(target=main) # t.start() # t.join()
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Set; public class Q2 { private interface Solution { void run(int t); } private static final boolean IS_MULTITASK = true; private static final boolean IS_ISOLATED = true; private static final Scanner in = new Scanner(System.in); public static void main(String[] args) { Solution s = getAndInitSolution(); if (IS_MULTITASK) { multiTask(s); } else { singleTask(s); } } private static void multiTask(Solution s) { int t = in.nextInt(); in.nextLine(); for (int i = 0; i < t; i++) { s.run(t); } } private static void singleTask(Solution s) { s.run(-1); } private static Solution getAndInitSolution() { if (IS_ISOLATED) { return t -> new IsolateSolution().run(t); } else { PreComputedSolution preComputedSolution = new PreComputedSolution(); preComputedSolution.init(); return preComputedSolution; } } private static class IsolateSolution implements Solution { int H, M; int inputH, inputM; Map<Integer, Integer> valid = new HashMap<>(); @Override public void run(int t) { init(); prepare(); solve(); } private void init() { valid.put(8, 8); valid.put(5, 2); valid.put(2, 5); valid.put(1, 1); valid.put(0, 0); H = in.nextInt(); M = in.nextInt(); in.nextLine(); String[] vals = in.nextLine().split(":"); inputH = Integer.valueOf(vals[0]); inputM = Integer.valueOf(vals[1]); } private void prepare() { } private void solve() { int h = inputH; int m = inputM; while (!reflectionValid(h, m)) { m++; if (m >= M) { h++; m = 0; } if (h >= H) { h = 0; } } if (h < 10) { System.out.print("0"); } System.out.print(h + ":"); if (m < 10) { System.out.print("0"); } System.out.println(m); } private boolean reflectionValid(int h, int m) { if (!valid.containsKey(h / 10) || !valid.containsKey(h % 10)) return false; if (!valid.containsKey(m / 10) || !valid.containsKey(m % 10)) return false; int hp = valid.get(m % 10) * 10 + valid.get(m / 10); int mp = valid.get(h % 10) * 10 + valid.get(h / 10); return hp < H && mp < M; } } private static class PreComputedSolution implements Solution { public void init() { //TODO: System.out.println("Init world!"); } @Override public void run(int t) { //TODO: System.out.println("Hello world!"); } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
// BABITHA'S CODE.// #include<bits/stdc++.h> using namespace std; #define int long long #define int_max 9223372036854775807 #define float double #define pii pair<int, int> #define fl(i, a, b) for (int i = a; i < b; i++) #define dy(a, n) int *a = new int[n] #define mii map<int, int> #define vec(a) vector<a> #define MAXN 1004 #define endl "\n" #define mod 1000000007 #define yes cout << "Yes\n" #define no cout << "No\n" static const int int_min = -9223372036854775807; int spf[MAXN]; void sieve() { spf[1] = 1; for (int i = 2; i < MAXN; i++) spf[i] = i; for (int i = 4; i < MAXN; i += 2) spf[i] = 2; for (int i = 3; i * i < MAXN; i++) { if (spf[i] == i) { for (int j = i * i; j < MAXN; j += i) if (spf[j] == j) spf[j] = i; } } } vector<int> getFactorization(int x) { vector<int> ret; while (x != 1) { ret.push_back(spf[x]); x = x / spf[x]; } return ret; } int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } int __gcd(int a, int b) { if (b > a) { swap(a, b); } return gcd(a, b); } int lcm(int a, int b) { int lcm1 = (a / __gcd(a, b)) * b; return lcm1; } int power(int x, int y) { int res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if (y & 1) { res = res * x; //res %= mod; } // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 //x %= mod; } return res; } int powermod(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p int modInverse(int n, int p) { return powermod(n, p - 2, p); } // Returns nCr % p using Fermat's little // theorem. int nCrModPFermat(int n, int r, int p) { // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r int fac[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = (fac[i - 1] * i) % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } int32_t main() { #ifndef ONLINE_JUDGE // For getting input from input.txt file freopen("input.txt", "r", stdin); // Printing the Output to output.txt file freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; cin >> t; while (t--) { int h, m; cin >> h >> m; string s; cin >> s; int i = 0; int hh = 0; hh = (s[0] - '0'); hh *= 10; hh += (s[1] - '0'); int mm = 0; mm = (s[3] - '0'); mm *= 10; mm += (s[4] - '0'); //cout << hh << " " << mm << endl; bool status = false; while (!status) { int k1 = (mm + i) / m; int k2 = (mm + i) % m; int cuhh = hh + k1; cuhh %= h; int cumi = k2; int p[4]; p[1] = cuhh % 10; p[0] = (cuhh / 10) % 10; p[3] = cumi % 10; p[2] = (cumi / 10) % 10; //cout << p[0] << p[1] << ":" << p[2] << p[3] << endl; bool check = true; fl(j, 0, 4) { if(p[j]!=1 && p[j]!=2 && p[j]!=5 &&p[j]!=0 &&p[j]!=8){ check = false; break; } } if(!check){ i++; continue; } int p1[4]; fl(j,0,4){ if(p[j]==2){ p1[j] = 5; } else if(p[j]==5){ p1[j] = 2; } else{ p1[j] = p[j]; } } int temph = p1[3] * 10 + p1[2]; int tempm = p1[1] * 10 + p1[0]; if(temph<h && tempm<m){ status = true; cout << p[0] << p[1] << ":" << p[2] << p[3] << endl; } //cout << p[0] << p[1] << ":" << p[2] << p[3] << endl; //cout << i << endl; i++; } } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <iostream> #include <vector> #include <unordered_map> using namespace std; #define ll long long int #define VEC vector<ll> #define PAIR pair<ll, ll> #define VECP vector<PAIR> #define mp(a, b) make_pair(a, b) #define pb(a) push_back(a) #define rep(st, n) for (ll i = st; i < n; i++) #define repr(st, n) for (ll i = st; i >= n; i--) #define REP(st, n) for (ll j = st; j < n; j++) #define REPR(st, n) for (ll j = st; j >= n; j--) #define REP3(st, n) for (ll k = st; k < n; k++) #define REPR3(st, n) for (ll k = st; k >= n; k--) #define repa(a) for(auto itr1: a) #define REPA(a) for(auto itr2: a) struct hash_pair { template <class T1, class T2> size_t operator()(const pair<T1, T2>& p) const { auto hash1 = hash<T1>{}(p.first); auto hash2 = hash<T2>{}(p.second); return hash1 ^ hash2; } }; #define PAIR_MAP(a) unordered_map<PAIR, a, hash_pair> bool check_reflection(ll h, ll m, ll h1, ll m1) { unordered_map<ll, bool> right = {{0, true}, {1, true}, {2, true}, {3, false}, {4, false}, {5, true}, {6, false}, {7, false}, {8, true}, {9, false}}; unordered_map<ll, ll> reflect = {{0, 0}, {1, 1}, {2, 5}, {5, 2}, {8, 8}}; if (!right[m1 % 10]) return false; else if (!right[m1 / 10]) return false; else if (!right[h1 % 10]) return false; else if (!right[h1 / 10]) return false; ll temp = reflect[m1 % 10]; m1 = 10 * temp + reflect[m1 / 10]; temp = reflect[h1 % 10]; h1 = 10 * temp + reflect[h1 / 10]; if (m1 >= h || h1 >= m) return false; return true; } void inc_time(ll h, ll m, ll * h1, ll * m1) { if (*m1 + 1 < m) *m1 += 1; else { *m1 = 0; if (*h1 + 1 < h) *h1 += 1; else *h1 = 0; } } void solve() { ll t; cin >> t; while (t--) { ll h, m, h1, m1; cin >> h >> m; string str_time; cin >> str_time; m1 = str_time[3] - '0'; m1 = m1 * 10 + str_time[4] - '0'; h1 = str_time[0] - '0'; h1 = h1 * 10 + str_time[1] - '0'; while (!check_reflection(h, m, h1, m1)) inc_time(h, m, &h1, &m1); str_time[0] = '0' + h1 / 10; str_time[1] = '0' + h1 % 10; str_time[3] = '0' + m1 / 10; str_time[4] = '0' + m1 % 10; cout << str_time << "\n"; } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); #endif solve(); return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<bits/stdc++.h> using namespace std; #include<cstring> #include<vector> typedef long long int ll; typedef long double ld; typedef double db; ll solve(ll i,ll h) { ll a[10]={0,1,5,-1,-1,2,-1,-1,8,-1}; ll b=i/10,c=i%10; if( a[b]!=-1 && a[c]!=-1 ) { ll ch= 10*( a[c] )+a[b]; if(ch<h){return i; } else { return -1;} } else {return -1;} } int main() { ll tt;cin>>tt; for(ll ii=0;ii<tt;ii++) { ll h,m,cm=0,ch=0,am=0,ah=0;cin>>h>>m; string s;cin>>s; ll hrs= (int(s[0] )-48)*10 + int(s[1])-48; ll mnt= (int(s[3] )-48)*10 +int(s[4])-48; for( ll i=mnt;i<m;i++ ) { ll d= solve(i ,h); if(d!=-1 ){cm=1;am=d;break; } } if(cm==0){am=0;hrs++; } for( ll i=hrs;i<h;i++ ) { ll t= solve(i ,m); if(t!=-1 ){ch=1;ah=t;break; } } if(hrs!=ah ){ am=0;} if(ah==0){ cout<<ah<<ah; } else if(ah>0 && ah<10){ cout<<0<<ah; } else{ cout<<ah; } cout<<":"; if(am==0){ cout<<am<<am; } else if(am>0 && am<10){ cout<<0<<am; } else{ cout<<am; } cout<<endl; } }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 bool check(int a){ if(a==0 || a==1 || a==2 || a==5 || a==8) return true; return false; } int mirror(int a){ if(a==0) return 0; if(a==1) return 1; if(a==2) return 5; if(a==5) return 2; if(a==8) return 8; return 0; } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t=1; cin>>t; while(t--){ int h,m; cin>>h>>m; string s; cin>>s; int x=10*(s[0]-'0')+s[1]-'0'; int y=10*(s[3]-'0')+s[4]-'0'; int flag=0; for(int j=y;j<m;j++){ int a=x/10; int b=x%10; int c=j/10; int d=j%10; if(check(a) and check(b) and check(c) and check(d)){ int p[4]={0}; p[0]=mirror(d); p[1]=mirror(c); p[2]=mirror(b); p[3]=mirror(a); int k=10*p[0]+p[1]; int l=10*p[2]+p[3]; if(k<h and l<m){ cout<<a<<b<<":"<<c<<d<<endl; flag=1; break; } } } for(int i=x+1;i<h;i++){ for(int j=0;j<m;j++){ if(flag==0){ int a=i/10; int b=i%10; int c=j/10; int d=j%10; if(check(a) and check(b) and check(c) and check(d)){ int p[4]={0}; p[0]=mirror(d); p[1]=mirror(c); p[2]=mirror(b); p[3]=mirror(a); int k=10*p[0]+p[1]; int l=10*p[2]+p[3]; if(k<h and l<m){ cout<<a<<b<<":"<<c<<d<<endl; flag=1; break; } } } } } if(flag==0) cout<<"00:00"<<endl; } }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<bits/stdc++.h> #define int long long #define double long double #define sz(x) (int)(x).size() #define all(x) (x).begin(),(x).end() #define pb push_back #define x first #define y second using namespace std; using pi = pair<int,int>; const int inf = 0x3f3f3f3f3f3f3f3f; const int minf = 0xc0c0c0c0c0c0c0c0; inline int valid(int x) { if (x==0 || x==1 || x==2 || x==5 || x==8) return 1; return 0; } inline int f(int x) { if (x==2) return 5; if (x==5) return 2; return x; } signed main() { ios::sync_with_stdio(0); cin.tie(0); int TC; cin>>TC; for (int tc=1; tc<=TC; tc++) { int h,m; cin>>h>>m; char dummy; int H,M; cin>>H>>dummy>>M; while (1) { if (valid(H/10) && valid(H%10) && valid(M/10) && valid(M%10)) { int TH = H, TM = M; swap(TH, TM); TH = f(TH%10)*10 + f(TH/10); TM = f(TM%10)*10 + f(TM/10); if (TH < h && TM < m) { if (H<10) cout<<0<<H; else cout<<H; cout<<':'; if (M<10) cout<<0<<M; else cout<<M; cout<<'\n'; break; } } ++M; if (M==m) { ++H; M=0; } if (H==h) H=0; } } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; public class Main { public static void main(String []args){ Scanner scn=new Scanner(System.in); int t=scn.nextInt(); while(t-->0){ int h=scn.nextInt(); int m=scn.nextInt(); String str=scn.next(); int []arr={0,1,5,-1,-1,2,-1,-1,8,-1}; String []time=str.split(":"); int hr=Integer.parseInt(time[0]); int min=Integer.parseInt(time[1]); while(!valid(hr,min,h,m,arr)){ min++; if(min==m){ hr++; } min=min%m; hr=hr%h; } if(hr>9 && min>9){ System.out.println(hr+":"+min); } else if(hr<=9 && min>9){ System.out.println("0"+hr+":"+min); }else if(hr>9 && min<=9){ System.out.println(hr+":0"+min); }else{ System.out.println("0"+hr+":0"+min); } } scn.close(); } public static boolean valid(int hr,int min,int h,int m,int []arr){ int hr1=hr%10; int hr2=hr/10; int min1=min%10; int min2=min/10; if(arr[hr1]==-1 || arr[hr2]==-1 || arr[min1]==-1 || arr[min2]==-1)return false; int revHr=arr[min1]*10+arr[min2]; int revMin=arr[hr1]*10+arr[hr2]; if(revHr>=h || revMin>=m)return false; return true; } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; import java.io.*; public class cc_march2020_long { public static void main(String[] args) { Scanner scn=new Scanner(System.in); int t=scn.nextInt(); HashMap<Integer,Integer> reflect=new HashMap(); reflect.put(0,0); reflect.put(1, 1); reflect.put(2, 5); reflect.put(5, 2); reflect.put(8, 8); while(t-- >0) { int hr=scn.nextInt(); int min=scn.nextInt(); scn.nextLine(); String str=scn.nextLine(); StringTokenizer st=new StringTokenizer(str,":"); int hh=Integer.parseInt(st.nextToken()); int mm=Integer.parseInt(st.nextToken()); boolean ans=false; int i=hh,j=mm; for( i=hh;i<hr;i++) { for( j= (i==hh ? mm : 0);j<min;j++) { if(validate(i,j,hr,min,reflect)) { ans=true; break; } } if(ans) break; } if(ans) { System.out.println((i/10 ==0 ? ("0"+i): (i+""))+":"+(j/10 ==0 ?("0"+j): (j+""))); }else { System.out.println("00:00"); } } } public static boolean validate(int hh,int mm,int hr,int min,HashMap<Integer,Integer>reflect) { if(!reflect.containsKey(hh/10) || !reflect.containsKey(hh%10) || !reflect.containsKey(mm/10) || !reflect.containsKey(mm%10)) return false; int newhh= ((reflect.get(mm%10))*10)+(reflect.get(mm/10)); int newmm= ((reflect.get(hh%10))*10)+(reflect.get(hh/10)); // System.out.println(newhh+" "+newmm); if(newhh>=hr || newmm>=min) { return false; } return true; } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<bits/stdc++.h> using namespace std; typedef long long ll; int rev(int x){ vector<int> v; for(int i=0;i<2;i++){ int d=x%10; x/=10; if(d!=0&&d!=1&&d!=2&&d!=5&&d!=8){ return -1; } if(d==2||d==5) d^=2^5; v.push_back(d); } return v[0]*10+v[1]; } int main(){ ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); int T; cin >> T; while(T--){ int h,m,x,y; string s; cin >> h >> m >> s; x=(s[0]-'0')*10+(s[1]-'0'); y=(s[3]-'0')*10+(s[4]-'0'); while(true){ int a=rev(y),b=rev(x); if(a!=-1&&b!=-1&&a<h&&b<m){ cout << (x/10==0?'0'+to_string(x):to_string(x)) << ":" << (y/10==0?'0'+to_string(y):to_string(y)) << '\n'; break; } y++; if(y==m){ y=0; x++; if(x==h) x=0; } } } }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
//package com.example.activitytest; /* Command + D 复制当前行到下一行 Command + Delete 删除当前行 Command + R 替换 Command + Option + L 格式化代码 Control + R 编译 */ import java.util.*; import java.io.InputStream; import java.io.*; import java.lang.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Long start = System.currentTimeMillis(); Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); for(int i=0;i<=9;i++)mp.put(i,-1); mp.put(0,0);mp.put(1,1);mp.put(2,5);mp.put(5,2);mp.put(8,8); int T = in.nextInt(); while (T-- > 0) { int h = in.nextInt(), m = in.nextInt(); String s = in.readString(); int nh = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0'); int nm = (s.charAt(3) - '0') * 10 + (s.charAt(4) - '0'); int flag = 0; while (true) { if (check(nh, nm,mp,h,m) == 1) { flag = 1; System.out.printf("%02d:%02d", nh, nm); break; } nm++; if (nm == m) { nm = 0; nh++; } if (nh == h) nh = 0; } nm = 0; nh = 0; if (flag == 0) System.out.printf("%02d:%02d", nm, nh); System.out.println(); } //System.out.println("Time=" + (System.currentTimeMillis() - start) + "ms"); } private static int check(int nh, int nm, Map<Integer, Integer> mp, int h, int m) { int a1=nh/10,a2=nh%10,a3=nm/10,a4=nm%10; int b4=mp.get(a1),b3=mp.get(a2),b2=mp.get(a3),b1=mp.get(a4); if(b1==-1||b2==-1||b3==-1||b4==-1)return 0; if(b1*10+b2<h&&b3*10+b4<m)return 1; return 0; } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt();; while (2*t-->0){ int h = sc.nextInt(); int m = sc.nextInt(); String s = sc.next(); String[] splitted = s.split(":"); int hour = Integer.parseInt(splitted[0]); int minute = Integer.parseInt(splitted[1]); for(int i=hour;i<=h;i++){ boolean found = false; for(int j=(i==hour?minute: 0);j<m;j++) { if (isValid(i % h) && isValid(j%m)) { if(isReverseCorrect(i, j , h, m)){ hour = i%h; minute = j%m; found = true; break; } } } if(found) break; } System.out.println(format(hour, minute)); } } private static boolean isReverseCorrect(int hour, int minute, int h, int m) { String hourValue = String.valueOf(hour%h); String minuteValue = String.valueOf(minute%m); if(hourValue.length()==1) hourValue = "0"+hourValue; if(minuteValue.length()==1) minuteValue = ("0"+minuteValue); int hourValueRev = Integer.parseInt(new StringBuilder().append(makereverse(hourValue)).reverse().toString()); int minuteValueRev = Integer.parseInt(new StringBuilder().append(makereverse(minuteValue)).reverse().toString()); return (minuteValueRev<h && hourValueRev <m); } private static String makereverse(String hourValue) { StringBuilder sb = new StringBuilder(); for(int i=0;i<hourValue.length();i++){ if(hourValue.charAt(i)=='5') sb.append(2); else if(hourValue.charAt(i)=='2') sb.append(5); else sb.append(hourValue.charAt(i)); } return sb.toString(); } private static String format(int hour, int minute) { String hourVal = String.valueOf(hour); String minVal = String.valueOf(minute); if(hourVal.length()==1) hourVal = "0"+hourVal; if(minVal.length()==1) minVal = "0"+minVal; return (hourVal + ":"+minVal); } private static boolean isValid(int value) { HashSet<Integer> valid = new HashSet<>(); valid.add(0);valid.add(1);valid.add(2);valid.add(5);valid.add(8); int unit = value%10; int decimal = value/10; return (valid.contains(unit) && valid.contains(decimal)); } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; import java.io.*; public class _705 { static int hTotal; static int mTotal; public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while (t-- > 0) { hTotal = sc.nextInt(); mTotal = sc.nextInt(); String s = sc.next(); int curH = Integer.parseInt(s.substring(0, 2)); int curM = Integer.parseInt(s.substring(3, 5)); while (true) { if (check(curH, curM)) break; else { curM++; if (curM == mTotal) { curM = 0; curH++; if (curH == hTotal) { curH = 0; } } } } String starter1 = ""; String starter2 = ""; if (curH < 10) starter1 = "0"; if (curM < 10) starter2 = "0"; out.println(starter1 + curH + ":" + starter2 + curM); } out.close(); } static boolean check(int h, int m) { ArrayList<Integer> digH = new ArrayList<>(); ArrayList<Integer> digM = new ArrayList<>(); String sH = Integer.toString(h); String sM = Integer.toString(m); while (sH.length() < 2) sH = "0" + sH; while (sM.length() < 2) sM = "0" + sM; boolean ok = true; for (int i = 0; i < 2; i++) { int one = sM.charAt(i) - '0'; int two = sH.charAt(i) - '0'; digM.add(one); digH.add(two); ok = ok && (one <= 2 || one == 5 ||one == 8); ok = ok && (two <= 2 || two == 5 || two == 8); } if (!ok) return false; int hTens = (digM.get(1) == 2 || digM.get(1) == 5) ? 7 - digM.get(1) : digM.get(1); int hOnes = (digM.get(0) == 2 || digM.get(0) == 5) ? 7 - digM.get(0) : digM.get(0); int mTens = (digH.get(1) == 2 || digH.get(1) == 5) ? 7 - digH.get(1) : digH.get(1); int mOnes = (digH.get(0) == 2 || digH.get(0) == 5) ? 7 - digH.get(0) : digH.get(0); ok = ok && (10 * hTens + hOnes < hTotal); ok = ok && (10 * mTens + mOnes < mTotal); return ok; } static void sort(int[] a) { ArrayList<Integer> q = new ArrayList<>(); for (int i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } static void sort(long[] a) { ArrayList<Long> q = new ArrayList<>(); for (long i : a) q.add(i); Collections.sort(q); for (int i = 0; i < a.length; i++) a[i] = q.get(i); } //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <algorithm> #include <cassert> #include <climits> #include <cmath> #include <complex> #include <iomanip> #include <iostream> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <tuple> #include <vector> #define LSOne(S) ((S) & -(S)) const long long P = 1e9 + 7; const double EPS = 1e-9; using namespace std; char getReflect(char c) { switch (c) { case '0': case '1': case '8': return c; case '2': return '5'; case '5': return '2'; default: return ' '; } } bool isReflectedTimeValid(string hstr, string mstr, int h, int m) { // cout << "hstr : " << hstr << " mstr: " << mstr << endl; string htemp = ""; int mul = 1; int hres = 0; for (char c : mstr) { char r = getReflect(c); if (r == ' ') return false; htemp = to_string(r) + htemp; hres += (r - '0') * mul; mul *= 10; } string mtemp = ""; mul = 1; int mres = 0; for (char c : hstr) { char r = getReflect(c); if (r == ' ') return false; mtemp = to_string(r) + mtemp; mres += (r - '0') * mul; mul *= 10; } // cout << "isvalid: hres: " << hres << " mres: " << mres << endl; return hres < h && mres < m; } pair<string, string> extract(string s) { return {s.substr(0, 2), s.substr(3, 2)}; } string toString(int h, int m) { string hstr = ""; while (h > 0) { hstr = to_string(h % 10) + hstr; h /= 10; } string mstr = ""; while (m > 0) { mstr = to_string(m % 10) + mstr; m /= 10; } while (hstr.length() < 2) { hstr = '0' + hstr; } while (mstr.length() < 2) { mstr = '0' + mstr; } return hstr + ":" + mstr; } string increment(string s, int h, int m) { auto [hstr, mstr] = extract(s); int hres = 0; int mul = 10; for (char c : hstr) { hres += (c - '0') * mul; mul /= 10; } int mres = 0; mul = 10; for (char c : mstr) { mres += (c - '0') * mul; mul /= 10; } if (mres + 1 < m) { mres++; } else { mres = 0; if (hres + 1 < h) { hres++; } else { hres = 0; } } return toString(hres, mres); } /* YOU CAN DO THIS!! ;) 1. Note the limits! 2. Give logical, short variable names 3. If you are stuck for a long time, skip to next problem */ int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while (t--) { int maxx = 60 * 60; int h, m; cin >> h >> m; string s; cin >> s; auto [hstr, mstr] = extract(s); // cout << hstr << " " << mstr << endl; while (maxx > 0 && !isReflectedTimeValid(hstr, mstr, h, m)) { s = increment(s, h, m); // cout << "incremented : " << s << endl; // cout << s << endl; auto [a, b] = extract(s); hstr = a; mstr = b; maxx--; } cout << s << '\n'; } }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import sys import re import random import math import copy from heapq import heappush, heappop, heapify from functools import cmp_to_key from bisect import bisect_left, bisect_right from collections import defaultdict, deque, Counter # sys.setrecursionlimit(1000000) # input aliases # input = sys.stdin.readline getS = lambda: input().strip() getN = lambda: int(input()) getList = lambda: list(map(int, input().split())) getZList = lambda: [int(x) - 1 for x in input().split()] INF = float("inf") MOD = 10**9 + 7 divide = lambda x: pow(x, MOD-2, MOD) def nck(n, k, kaijyo): return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD def npk(n, k, kaijyo): if k == 0 or k == n: return n % MOD return (kaijyo[n] * divide(kaijyo[n-k])) % MOD def fact_and_inv(SIZE): inv = [0] * SIZE # inv[j] = j^{-1} mod MOD fac = [0] * SIZE # fac[j] = j! mod MOD finv = [0] * SIZE # finv[j] = (j!)^{-1} mod MOD inv[1] = 1 fac[0] = fac[1] = 1 finv[0] = finv[1] = 1 for i in range(2, SIZE): inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD fac[i] = fac[i - 1] * i % MOD finv[i] = finv[i - 1] * inv[i] % MOD return fac, finv def renritsu(A, Y): # example 2x + y = 3, x + 3y = 4 # A = [[2,1], [1,3]]) # Y = [[3],[4]] または [3,4] A = np.matrix(A) Y = np.matrix(Y) Y = np.reshape(Y, (-1, 1)) X = np.linalg.solve(A, Y) # [1.0, 1.0] return X.flatten().tolist()[0] class TwoDimGrid: # 2次元座標 -> 1次元 def __init__(self, h, w, wall="#"): self.h = h self.w = w self.size = (h+2) * (w+2) self.wall = wall self.get_grid() # self.init_cost() def get_grid(self): grid = [self.wall * (self.w + 2)] for i in range(self.h): grid.append(self.wall + getS() + self.wall) grid.append(self.wall * (self.w + 2)) self.grid = grid def init_cost(self): self.cost = [INF] * self.size def pos(self, x, y): # 壁も含めて0-indexed 元々の座標だけ考えると1-indexed return y * (self.w + 2) + x def getgrid(self, x, y): return self.grid[y][x] def get(self, x, y): return self.cost[self.pos(x, y)] def set(self, x, y, v): self.cost[self.pos(x, y)] = v return def show(self): for i in range(self.h+2): print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)]) def showsome(self, tgt): for t in tgt: print(t) return def showsomejoin(self, tgt): for t in tgt: print("".join(t)) return def search(self): grid = self.grid move = [(0, 1), (0, -1), (1, 0), (-1, 0)] move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] # for i in range(1, self.h+1): # for j in range(1, self.w+1): # cx, cy = j, i # for dx, dy in move: # nx, ny = dx + cx, dy + cy class BIT(): # A1 ... AnのBIT(1-indexed) def __init__(self, n): self.n = n self.BIT = [0] * (n + 2) # A1 ~ Aiまでの和 O(logN) def query(self, idx): res_sum = 0 while idx > 0: res_sum += self.BIT[idx] idx -= idx & (-idx) return res_sum # Ai += x O(logN) def update(self, idx, x): # print(idx) while idx <= self.n: # print(idx) self.BIT[idx] += x idx += idx & (-idx) return def show(self): print(self.BIT) def judge(t, h, m): a = [] for tt in t: if tt in [3,4,6,7,9]: return False if tt in [0, 1, 8]: a.append(tt) if tt == 2: a.append(5) if tt == 5: a.append(2) hh = a[3] * 10 + a[2] mm = a[1] * 10 + a[0] if hh < h and mm < m: return True else: return False def solve(): # a = input().split(":") # print(a) # return h, m = map(int, input().split()) a, b = map(int, input().split(":")) while True: la = list(str(a)) if len(la) == 1: la = ["0"] + la lb = list(str(b)) if len(lb) == 1: lb = ["0"] + lb inp = la + lb inp = list(map(int, inp)) res = judge(inp, h, m) if res: break if b < m-1: b += 1 else: a += 1 b = 0 if a == h: a = 0 la = list(str(a)) if len(la) == 1: la = ["0"] + la lb = list(str(b)) if len(lb) == 1: lb = ["0"] + lb print("".join(la) + ":" + "".join(lb)) def main(): n = getN() for _ in range(n): solve() return if __name__ == "__main__": main() # solve()
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
change = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8} bad = (3, 4, 6, 7, 9) for _ in range(int(input())): h, m = map(int, input().split()) s = input() ch = int(s[:2]) cm = int(s[3:]) while True: if not ((ch%10) in bad or (cm%10) in bad or (ch//10) in bad or (cm//10) in bad): chm = change[ch%10] * 10 + change[ch//10] chh = change[cm%10] * 10 + change[cm//10] if chh < h and chm < m: if ch < 10: print('0', end='') print(ch, end=':') if cm < 10: print('0', end='') print(cm) break cm += 1 if cm == m: cm = 0 ch += 1 if ch == h: print("00:00") break
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
def incrementtime(h,m,s): t=s.split(":") ho=int(t[0]) mi=int(t[1]) if(mi+1<m): mi+=1 return (t[0]+":"+(str(mi)).zfill(2)) elif (mi+1==m): temp="00" if(ho+1<h): ho+=1 return((str(ho)).zfill(2)+":"+temp) elif(ho+1==h): return(temp+":"+temp) def reflect(s): t=s.split(":") m=[ t[0][0],t[0][1],t[1][0],t[1][1] ] n=[] for i in m: if(i=="0"): n.append("0") elif(i=="1"): n.append("1") elif(i=="2"): n.append("5") elif(i=="5"): n.append("2") elif(i=="8"): n.append("8") return (n[3]+n[2]+":"+n[1]+n[0]) def checkvalidreflection(h,minutes,s): l=["0","1","2","5","8"] t=s.split(":") m=[ t[0][0],t[0][1],t[1][0],t[1][1] ] for i in m: if (i not in l): return False reflected=reflect(s) tr=list(reflected.split(":")) h1=(int(tr[0])) m1=(int(tr[1])) if(h1< h and m1<minutes ): return True else: return False def getnearest(h,m,s): time=s while(not checkvalidreflection(h,m,time)): time=incrementtime(h,m,time) return time t=int(input()) for i in range(t): p=input() q=p.split(" ") h=int(q[0]) m=int(q[1]) s=input() ans=getnearest(h,m,s) print(ans)
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<ll, ll> pll; typedef pair<ld, ld> pld; typedef pair<string, string> pss; typedef vector<ll> vll; typedef vector<ld> vld; typedef vector<pll> vpll; typedef vector<pld> vpld; typedef vector<vll> vvll; typedef queue<ll> qll; typedef queue<ld> qld; typedef queue<vll> qvll; typedef queue<vld> qvld; typedef queue<pll> qpll; typedef queue<pld> qpld; #define unomi unordered_map<int, int> #define omi map<int, int> #define endl "\n" #define mp make_pair #define pb push_back #define all(v) v.begin(), v.end() #define fi first #define se second #define lb lower_bound #define ub upper_bound #define pi 3.14159265358979323846 #define MAX 1e18 #define ms(s, n) memset(s, n, sizeof(s)) #define prec(n) fixed << setprecision(n) #define fori(p, n) for (ll i = p; i < (ll)n; i++) #define forj(p, n) for (ll j = p; j < (ll)n; j++) #define fork(p, n) for (ll k = p; k < (ll)n; k++) #define foriv(p, n, v) for (ll i = p; i < (ll)n; i += v) #define forjv(p, n, v) for (ll j = p; j < (ll)n; j += v) #define forkv(p, n, v) for (ll k = p; k < (ll)n; k += v) #define rfori(a, b) for(ll i = a; i>= b; i--) #define rall(x) x.rbegin(), x.rend() #define mod 1000000007 inline ll modnum(ll a) { return (a + mod) % mod; } inline ll modadd(ll a, ll b) { return ((a % mod) + (b % mod)) % mod; } //a+b inline ll modsub(ll a, ll b) { return ((a % mod) - (b % mod)) % mod; } //a-b inline ll modmul(ll a, ll b) { return ((a % mod) * (b % mod)) % mod; } //a*b inline ll modexp(ll a, ll b) { return ((a % mod) ^ b) % mod; } //a^b #define bolt \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0); #define setbits(a) __builtin_popcountll(a) #define start \ ll t; \ cin >> t; \ while (t--) template <typename T> istream &operator>>(istream &input, vector<T> &data) { for (T &x : data) input >> x; return input; } template <typename T> ostream &operator<<(ostream &output, const vector<T> &data) { for (const T &x : data) output << x << " "; return output; } template <typename T> ostream &operator<<(ostream &output, const set<T> &data) { for (auto it : data) output << it << " "; return output; } template <typename T> ostream &operator<<(ostream &output, const unordered_set<T> &data) { for (auto it : data) output << it << " "; return output; } template <typename T, typename S> ostream &operator<<(ostream &output, const map<T, S> &data) { for (auto it : data) output << it.first << " " << it.second << endl; return output; } template <typename T, typename S> ostream &operator<<(ostream &output, const unordered_map<T, S> &data) { for (auto it : data) output << it.first << " " << it.second << endl; return output; } template <typename T, typename S> ostream &operator<<(ostream &output, const pair<T, S> &data) { output << data.first << " " << data.second << endl; return output; } void IO() { #ifndef ONLINE_JUDGE freopen("input1.txt", "r", stdin); freopen("output1.txt", "w", stdout); #endif } inline ll fact(ll n) { if (n <= 1) return 1; return n * fact(n - 1); } inline ll nCr(ll n, ll r) { ll res = 1; if (r > n - r) r = n - r; for (ll i = 0; i < r; i++) { res *= n - i; res /= i + 1; } return res; } inline ll nPr(ll n, ll r) { return fact(n) / fact(n - r); } void swap(ll& a, ll& b) { ll tmp; if (a < b) { tmp = a; a = b; b = tmp; } } inline ll gcd(ll a, ll b) { if (b == 0) return a; if (a < b) swap(a, b); return gcd(b, a % b); } inline ll lcm(ll a, ll b) { return (a / gcd(a, b) * b); } inline ll ceil(ll num, ll den) { return ((num + den - 1) / den); } inline bool sortbysec(const pair<ll, ll> &a, const pair<ll, ll> &b) { return (a.second < b.second); } inline ll pw(ll x, ll y) { ll res = 1; x = x % mod; while (y > 0) { if (y & 1) res = (1ll * res * x) % mod; y = y >> 1; x = (1ll * x * x) % mod; } return res; } // nCr & nPr with mod // nCr = fact(n) / (fact(r) x fact(n - r)) // nCr % p = (fac[n] * modInverse(fac[r]) % p * modInverse(fac[n - r]) % p) % p; const int N = 1e5; int fac[N], ifac[N], inv[N]; void precalc_factorial() { fac[0] = ifac[0] = fac[1] = ifac[1] = inv[0] = inv[1] = 1; for (int i = 2; i < N; i++) { fac[i] = 1LL * fac[i - 1] * i % mod; inv[i] = mod - 1LL * inv[mod % i] * (mod / i) % mod; ifac[i] = 1LL * ifac[i - 1] * inv[i] % mod; } } inline int ncr(int n, int r) { if (r < 0 | r > n) return 0; return 1LL * fac[n] * ifac[r] % mod * ifac[n - r] % mod; } inline int npr(int n, int r) { if (r < 0 | r > n) return 0; return 1LL * fac[n] * ifac[n - r] % mod; } struct node { ll val; node *left; node *right; node(ll x) : val(x), left(NULL), right(NULL) {} // vector<TreeNode *> children; // TreeNode(ll x) : val(x) {} }; void next_greater(vll &v, vll &res) { if (v.empty()) return; stack<pll> stk; for (int i = 0; i < v.size(); i++) { while (!stk.empty() && stk.top().first <= v[i]) { res[stk.top().second] = v[i]; stk.pop(); } stk.push({v[i], i}); } } set<ll> primes; void sieve(ll n) { vll arr(n + 1, 1); for (ll p = 2; p * p <= n; p++) { if (arr[p]) { for (ll i = p * p; i <= n; i += p) arr[i] = 0; } } if (!primes.empty()) primes.clear(); for (ll p = 2; p <= n; p++) if (arr[p]) primes.insert(p); } inline bool is_prime(ll n) { for (ll i = 2; i <= sqrt(n); i++) { if (n % i == 0) return false; } return true; } //void tin(vll& a){ ll n = a.size(); fori(0, n) cin>>a[i];} //void pot(vll& a){ ll n = a.size(); fori(0, n) cout<<a[i]<<" "; cout<<endl;} //void spot(string& s){ ll n = s.size(); fori(0, n)cout<<s[i]; cout<<endl;} /*void solve() { }*/ ll solve(vll& a1, vll& a2){ ll ans = 0, cnt =0; ll n = a1.size(), m = a2.size(); if(n == 0) return 0; vll suffix(m+1, 0); map<ll, ll> mp; fori(0, n) mp[a1[i]]++; for(int i = m-1; i >=0; i--){ suffix[i] = suffix[i+1]; suffix[i] += mp[a2[i]]; } fori(0, m){ auto it = upper_bound(all(a1), a2[i]); it--; ll stack_size = it - a1.begin()+1; ll curr_special = stack_size; if(stack_size >= 1){ auto it = lower_bound(all(a2), a2[i] - stack_size+1); curr_special = it - a2.begin(); curr_special = i - curr_special + 1; } ans = max(ans, curr_special + suffix[i+1]); //cout<<i<<" "<<a2[i]<<" "<<stack_size << " "<<curr_special<<" "<<ans<<endl; } return ans; } int is_valid(ll test_hr, ll test_min, ll hr, ll min){ ll tmp; ll tmp_min = test_min, tmp_hr = test_hr; if(test_hr >= hr || test_min >= min) return 0; while(tmp_min > 0){ tmp = tmp_min%10; tmp_min /= 10; if(tmp == 3 || tmp == 4 || tmp == 6 || tmp == 7 || tmp == 9) return 0; } while(tmp_hr > 0){ tmp = tmp_hr%10; tmp_hr /= 10; if(tmp == 3 || tmp == 4 || tmp == 6 || tmp == 7 || tmp == 9) return 0; } tmp_min = test_min; tmp_hr = test_hr; ll res_min = 0, res_hr = 0; while(tmp_min > 0){ tmp = tmp_min%10; tmp_min = tmp_min/10; if(tmp < 2 || tmp == 8) res_hr += tmp; else if(tmp == 2) res_hr += 5; else if(tmp == 5) res_hr += 2; if(tmp_min) res_hr *= 10; } while(tmp_hr > 0){ tmp = tmp_hr%10; tmp_hr = tmp_hr/10; if(tmp < 2 || tmp == 8) res_min += tmp; else if(tmp == 2) res_min += 5; else if(tmp == 5) res_min += 2; if(tmp_hr) res_min *= 10; } if(test_hr < 10) res_min *= 10; if(test_min < 10) res_hr *= 10; //cout<<res_hr<<" "<<res_min<<endl; if(res_hr >= hr || res_min >= min) return 0; return 1; } int main() { bolt; IO(); //precalc_factorial(); //sieve(100); start{ string str, tmp; ll hr, min, curr_hr, curr_min; cin>>hr>>min; //cout<<hr<<" "<<min<<endl; cin>>str; //cout<<str<<endl; stringstream stream(str); // Tokenizing w.r.t. space ' ' getline(stream, tmp, ':'); //cout<<tmp<<endl; curr_hr = stoi(tmp); getline(stream, tmp, ':'); //cout<<tmp<<endl; curr_min = stoi(tmp); //cout<<curr_hr<<" "<<curr_min<<endl; ll res_hr = 1, res_min = 1, i = curr_min, j = curr_hr; if(!is_valid(j ,i, hr, min)) { i++; j += i/min; i = i%min; j = j%hr; while(!is_valid(j , i, hr, min)){ i++; j += i/min; i = i%min; j = j%hr; } } /* cout<<j <<" "<<i<<endl;*/ res_hr = j;res_min = i; if(res_hr < 10) cout<<0; cout<<res_hr<<":"; if(res_min < 10) cout<<0; cout<<res_min<<endl; } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
N=100 a=5,N,N,2,N,N,8,N,0,1 R=lambda x=' ':map(int,input().split(x)) t,=R() exec(t*"h,m=R();x,y=R(':');y+=x*m;u=v=w=q=N\nwhile h<=w+q*10or v*10+u>=m:r=f'{y//m%h:02}:{y%m:02}';y+=1;u,v,_,w,q=(a[ord(x)%10]for x in r)\nprint(r)\n")
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int t=Integer.parseInt(bu.readLine()); int r[]=new int[10]; r[1]=1; r[2]=5; r[3]=-1; r[4]=-1; r[5]=2; r[6]=-1; r[7]=-1; r[8]=8; r[9]=-1; while(t-->0) { String s[]=bu.readLine().split(" "); int h=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]); boolean val[][]=new boolean[h][m]; int d[][]=new int[h][m]; s=bu.readLine().split(":"); int ch=Integer.parseInt(s[0]),cm=Integer.parseInt(s[1]); int i,j; for(i=0;i<h;i++) for(j=0;j<m;j++) { d[i][j]=Integer.MAX_VALUE; int ntl=j%10,ntr=j/10,nhl=i%10,nhr=i/10; ntl=r[ntl]; ntr=r[ntr]; nhl=r[nhl]; nhr=r[nhr]; if(ntl!=-1 && ntr!=-1 && nhl!=-1 && nhr!=-1) { int hr=ntl*10+ntr,min=nhl*10+nhr; if(hr<h && min<m) val[i][j]=true; } } int cx=ch,cy=cm; boolean vis[][]=new boolean[h][m]; i=0; while(!vis[cx][cy]) { vis[cx][cy]=true; if(val[cx][cy]) d[cx][cy]=i; i++; cy++; if(cy==m) { cy=0; cx++; } if(cx==h) cx=0; } int p[]={-1,-1},ans=Integer.MAX_VALUE; for(i=0;i<h;i++) for(j=0;j<m;j++) if(d[i][j]<ans) { ans=d[i][j]; p[0]=i; p[1]=j; } sb.append(p[0]/10); sb.append(p[0]%10); sb.append(':'); sb.append(p[1]/10); sb.append(p[1]%10); sb.append("\n"); } System.out.print(sb); } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<bits/stdc++.h> using namespace std; #define gc getchar_unlocked #define ll long long #define PI 3.1415926535897932384626 #define pb push_back //#define mp make_pair #define F first #define S second #define fast ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); typedef pair<int, int> pi; typedef pair<ll, ll> pl; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pi> vpi; typedef vector<pl> vpl; typedef vector<vi> vvi; typedef vector<vl> vvl; const int M=1000000007; int mir[10]; void solution() { int i, j, k, n, m; cin>>n>>m; mir[0]=0; mir[1]=1; mir[2]=5; mir[3]=-1; mir[4]=-1; mir[5]=2; mir[6]=-1; mir[7]=-1; mir[8]=8; mir[9]=-1; string s; cin>>s; int min=(s[3]-48)*10+(s[4]-48); int hr=(s[0]-48)*10+(s[1]-48); while(hr<n) { while(min<m) { if(mir[min%10]<0 || mir[min/10]<0 || mir[hr%10]<0 || mir[hr/10]<0) { min++; continue; } int temphr=mir[min%10]*10+mir[min/10]; int tempmn=mir[hr%10]*10+mir[hr/10]; if(temphr<n && tempmn<m) { if(hr<10) cout<<0; cout<<hr<<":"; if(min<10) cout<<0; cout<<min<<'\n'; return; } min++; } min=0; hr++; } cout<<"00:00"<<'\n'; } int main() { int t=1; cin>>t; while(t--) { solution(); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> using namespace std; #define fi first #define se second #define ii pair<int,int> #define vi vector<int> #define vii vector<ii> #define fora(i,a,b) for(int i=a;i<=b;++i) #define forb(i,a,b) for(int i=a;i>=b;--i) #define pb push_back #define all(a) a.begin(),a.end() bool conv(int x) { if (x == 0 || x== 1 || x == 2 || x == 5 || x == 8) return true; return false; } int op(int x) { if (x == 0 || x == 1 || x == 8) return x; else if (x == 2 || x == 5) return 7-x; return -1; } vi cv(int x) { vi ans; if (x < 10){ ans.pb(0); ans.pb(x); } else { fora(i,0,1) { ans.pb(x%10); x/=10; } reverse(all(ans)); } return ans; } int check(int x,int q) { vi ans = cv(x); int alt = 0; fora(i,0,1){ if (op(ans[i]) == -1) return 1; if (!i) alt += op(ans[i]); else alt += op(ans[i])*10; } if (alt >= q) return -1; return 0; } void solve() { int h,s; vi res; cin >> h >> s; int hh,ss; char sp; cin >> hh >> sp >> ss; int cnt1 = hh; int cnt2 = ss; int ho = 0; int mi = 0; while (check(cnt2,h)) ++cnt2; vi tmp =cv(cnt2); if (cnt2 >= s){ res.pb(0); res.pb(0); ++cnt1; } else { forb(i,1,0) res.pb(tmp[i]); } if (check(cnt1,s)) { res.clear(); res.pb(0); res.pb(0); ++cnt1; } while(check(cnt1,s)) ++cnt1; tmp = cv(cnt1); if (cnt1 >= h){ res.pb(0); res.pb(0); } else{ forb(i,1,0) res.pb(tmp[i]); } // cout << cnt1 << " " << cnt2 << "\n"; reverse(all(res)); fora(i,0,3){ cout << res[i]; if (i == 1) cout << ":"; } cout << "\n"; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while(t--){ solve(); } }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
//Flower_On_Stone #include <bits/stdc++.h> using namespace std; const int MIRROR[] = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1}; int test, h, m; string strClock; int hour, minute; int toInt(char ch) { return ch - '0'; } string toString(int x) { string resuft = ""; for (int i = 1; i <= 2; i++) { resuft.push_back(char(x % 10 + '0')); x /= 10; } reverse(resuft.begin(), resuft.end()); return resuft; } bool check(int hour, int minute) { if (min({MIRROR[hour % 10], MIRROR[hour / 10], MIRROR[minute % 10], MIRROR[minute / 10]}) == -1) { return false; } return (MIRROR[minute % 10] * 10 + MIRROR[minute / 10] < h && MIRROR[hour % 10] * 10 + MIRROR[hour / 10] < m); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); #ifdef Flower_On_Stone freopen("DEBUG.inp", "r", stdin); freopen("DEBUG.out", "w", stdout); #endif // Flower_On_Stone cin >> test; while (test--) { cin >> h >> m; cin >> strClock; hour = toInt(strClock[0]) * 10 + toInt(strClock[1]); minute = toInt(strClock[3]) * 10 + toInt(strClock[4]); while (!check(hour, minute)) { minute++; if (minute == m) { minute = 0; hour = (hour + 1) % h; } } cout << toString(hour) + ":" + toString(minute) << '\n'; } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> #define fi first #define se second #define rep(i,n) for(int i = 0; i < (n); ++i) #define rrep(i,n) for(int i = 1; i <= (n); ++i) #define drep(i,n) for(int i = (n)-1; i >= 0; --i) #define srep(i,s,t) for (int i = s; i < t; ++i) #define rng(a) a.begin(),a.end() #define rrng(a) a.rbegin(),a.rend() #define isin(x,l,r) ((l) <= (x) && (x) < (r)) #define pb push_back #define eb emplace_back #define sz(x) (int)(x).size() #define pcnt __builtin_popcountll #define uni(x) x.erase(unique(rng(x)),x.end()) #define snuke srand((unsigned)clock()+(unsigned)time(NULL)); #define show(x) cerr<<#x<<" = "<<x<<endl; #define PQ(T) priority_queue<T,v(T),greater<T> > #define bn(x) ((1<<x)-1) #define dup(x,y) (((x)+(y)-1)/(y)) #define newline puts("") #define v(T) vector<T> #define vv(T) v(v(T)) using namespace std; typedef long long int ll; typedef unsigned uint; typedef unsigned long long ull; typedef pair<int,int> P; typedef tuple<int,int,int> T; typedef vector<int> vi; typedef vector<vi> vvi; // typedef vector<ll> vl; typedef vector<P> vp; // typedef vector<T> vt; int getInt(){int x;scanf("%d",&x);return x;} template<typename T>istream& operator>>(istream&i,v(T)&v){rep(j,sz(v))i>>v[j];return i;} template<typename T>string join(const v(T)&v){stringstream s;rep(i,sz(v))s<<' '<<v[i];return s.str().substr(1);} template<typename T>ostream& operator<<(ostream&o,const v(T)&v){if(sz(v))o<<join(v);return o;} template<typename T1,typename T2>istream& operator>>(istream&i,pair<T1,T2>&v){return i>>v.fi>>v.se;} template<typename T1,typename T2>ostream& operator<<(ostream&o,const pair<T1,T2>&v){return o<<v.fi<<","<<v.se;} template<typename T>bool mins(T& x,const T&y){if(x>y){x=y;return true;}else return false;} template<typename T>bool maxs(T& x,const T&y){if(x<y){x=y;return true;}else return false;} template<typename T>ll suma(const v(T)&a){ll res(0);for(auto&&x:a)res+=x;return res;} const double eps = 1e-10; const ll LINF = 1001002003004005006ll; const int INF = 1001001001; #define dame { puts("-1"); return;} #define yn {puts("Yes");}else{puts("No");} const int MX = 200005; #define has(x,y) ((x).find(y) != (x).end()) #define int ll const int mod = 1000000007; int arr[10]; int h , m; bool check(int a , int b){ if(arr[a%10] == -1 || arr[a/10] == -1 || arr[b%10] == -1 || arr[b/10] == -1){ return 0; } int x = arr[b%10]*10+arr[b/10]; int y = arr[a%10]*10+arr[a/10]; if(x < h && y < m){ return 1; } else{ return 0; } } struct Solver { void solve() { // input memset(arr,-1,sizeof(arr)); arr[0] = 0; arr[1] = 1; arr[2] = 5; arr[5] = 2; arr[8] = 8; cin >> h >> m; string s; cin >> s; int rh = 0 , rm = 0; int n = s.size(); bool happen = false; for(int i = 0 ; i < n ; i++){ if(s[i] == ':'){ happen = true; continue; } if(!happen){ rh = rh*10+s[i]-'0'; } else{ rm = rm*10+s[i]-'0'; } } // cout<<rh<<" "<<rm<?<"\n"; while(!check(rh,rm)){ rm++; if(rm == m) rh++; rm%=m; rh%=h; } printf("%02d:",rh); printf("%02d\n",rm); } }; int32_t main() { ios_base::sync_with_stdio(NULL); cin.tie(NULL); cout.tie(NULL); cout<<fixed<<setprecision(10); int ts = 1; cin >> ts; rrep(ti,ts) { Solver solver; solver.solve(); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<bits/stdc++.h> using namespace std; #define pb push_back #define ll long long int int ara[] = {0, 1, 5, 0, 0, 2, 0, 0, 8}; bool valid(int n, int &x) { int a = n % 10; n /= 10; int b = n % 10; if ((a == 0 || a == 1 || a == 2 || a == 5 || a == 8) && (b == 0 || b == 1 || b == 2 || b == 5 || b == 8)) { x = ara[a] * 10 + ara[b]; return true; } return false; } int main() { #ifndef ONLINE_JUDGE clock_t tStart = clock(); freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int test_case; cin >> test_case; for (int Case = 1; Case <= test_case; Case++) { int h, m, hc, mc, x, y, rm, rh; char c; cin >> h >> m >> hc >> c >> mc; bool flg = 1; if (valid(hc, x) && x >= 0 && x < m) { for (int i = mc; i < m; i++) { if (valid(i, x) && x >= 0 && x < h) { printf("%02d:%02d\n", hc, i); flg = 0; break; } } } if (flg) { for (int i = hc + 1; i < h; i++) { if (valid(i, x) && x >= 0 && x < m) { printf("%02d:00\n", i); flg = 0; break; } } } if (flg) printf("00:00\n"); } #ifndef ONLINE_JUDGE fprintf(stderr, "\n>> Runtime: %.10fs\n", (double) (clock() - tStart) / CLOCKS_PER_SEC); #endif return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import math import operator def lcm(a,b): return (a / math.gcd(a,b))* b def nCr(n, r): return((math.factorial(n))/((math.factorial(r))*(math.factorial(n - r)))) def isKthBitSet(n, k): if (n & (1 << (k - 1))): return True else: return False def maximalRectangle( matrix): if not matrix or not matrix[0]: return 0 n = len(matrix[0]) height = [0] * (n + 1) ans = 0 for row in matrix: for i in range(n): height[i] = height[i] + 1 if row[i] == '0' else 0 stack = [-1] for i in range(n + 1): while height[i] < height[stack[-1]]: h = height[stack.pop()] w = i - 1 - stack[-1] ans = max(ans, h * w) stack.append(i) return ans def matched(str): count = 0 for i in str: if i == "(": count += 1 elif i == ")": count -= 1 if count < 0: return False return count == 0 def isValid(h,m,nh,nm): l=[0,1,5,-1,-1,2,-1,-1,8,-1] if(l[h//10]==-1 or l[h%10]==-1 or l[m//10]==-1 or l[m%10]==-1): return False resh= l[m%10]*10 + l[m//10] resm= l[h%10]*10 + l[h//10] return (resh<nh and resm<nm) def solve(): h,m=map(int,input().split()) #n=int(input()) #l=list(map(int,input().split())) #n2=int(input()) s=input() #l1=list(ap(int,input().split())) nh=int(s[0]+s[1]) nm=int(s[3]+s[4]) while(not(isValid(nh,nm,h,m))): #print(nh,nm) if(nm==m-1): nh+=1 nm+=1 nm=nm%m nh=nh%h nh=str(nh) nm=str(nm) if(len(nh)==1): nh='0'+nh if(len(nm)==1): nm='0'+nm print(nh+":"+nm) #print(s) t=int(input()) while(t>0): t-=1 solve()
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <iostream> #include <bits/stdc++.h> #define ll long long using namespace std; void test_case() { int h, m; cin >> h >> m; int r[10] = { 0, 1, 5, -1, -1, 2, -1, -1, 8, -1}; string s, s1, s2; cin >> s; int x = (s[0] - '0') * 10 + s[1] - '0', y = (s[3] - '0') * 10 + s[4] - '0'; while(1) { s1 = ""; s2 = ""; int x1 = x/10, x2 = x % 10, y1 = y/10, y2 = y % 10; s1 += x1 + '0'; s1 += x2 + '0'; s2 += y1 + '0'; s2 += y2 + '0'; if(min({r[x1], r[x2], r[y1], r[y2]}) > -1) { int newH = r[y2] * 10 + r[y1]; int newM = r[x2] * 10 + r[x1]; //cout << x1 << x2 << " " << y1 << y2 << "\n"; //cout << newH << " " << newM << "\n"; if(newH < h && newM < m) break; } y++; if(y == m) { y = 0; x++; } if(x == h) { x = 0; } } cout << s1 << ":" << s2 << "\n"; } int main() { int tc = 1; cin >> tc; while(tc--) { test_case(); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; import java.math.*; public class SortTheArray { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int runs = sc.nextInt(); while(runs-->0) { int h = sc.nextInt(); int m = sc.nextInt(); String[] in = sc.next().split(":"); int hour = Integer.parseInt(in[0]); int minute = Integer.parseInt(in[1]); while(true) { if(works(h,m,hour,minute)) break; minute++; if(minute==m) { minute=0; hour++; } if(hour==h) hour=0; } if(hour<10) System.out.print("0"+hour); else System.out.print(hour); System.out.print(":"); if(minute<10) System.out.print("0"+minute); else System.out.print(minute); System.out.println(); //System.out.println(hour+":"+minute); } } public static boolean works(int h,int m,int hour,int minute) { int a = swap(hour/10); if(a==-1) return false; int b = swap(hour % 10); if (b == -1) return false; int c = swap(minute / 10); if (c == -1) return false; int d = swap(minute % 10); if (d == -1) return false; if (10 * d + c >= h) return false; if (10 * b + a >= m) return false; return true; } public static int swap(int x) { if(x==0) return 0; if(x==1) return 1; if(x==2) return 5; if(x==5) return 2; if(x==8) return 8; return -1; } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
from sys import *; from math import *; from collections import *; from bisect import *; from itertools import * INF = maxsize def get_ints(): return map(int, stdin.readline().strip().split()) def get_array(): return list(map(int, stdin.readline().strip().split())) def input(): return stdin.readline().strip() mod = 1000000007 ump = {0: '0', 1: '1', 2: '5', 5: '2', 8 :'8'} # h,m=0,0 def isvalid(a,b): a=list(a) b=(list(b)) for i in range(len(a)): if a[i] not in ump.values(): return False else: a[i]=ump.get(int(a[i])) for i in range(len(b)): if b[i] not in ump.values(): return False else: b[i]=ump.get(int(b[i])) b.reverse() a.reverse() ax=int(''.join(a)) bx=int(''.join(b)) return bx<h and ax<m for _ in range(int(input())): h,m=get_ints() x=input() a=x[:2] b=x[3:] # print(a,b) # print(a,b) while True: if isvalid(a,b): break else: bint=(int(b)+1)%m aint=0 if bint==0: aint=(int(a)+1)%h else: aint=int(a) # print(aint, bint) a=list(str(aint)) b=list(str(bint)) if len(a)==1: a.append('0') a.reverse() a=''.join(a) if len(b)==1: b.append('0') b.reverse() b=''.join(b) # print(a,b) # print(a,b) print(f'{a}:{b}')
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.StringTokenizer; public class B { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out; public static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static float nextFloat() throws IOException { return Float.parseFloat(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } static HashMap map = new HashMap<Character, Character>(); public static void main(String[] args) throws IOException { map.put('0', '0'); map.put('1', '1'); map.put('2', '5'); map.put('5', '2'); map.put('8', '8'); int t = nextInt(); for (int i = 0; i < t; i++) { int h = nextInt(); int m = nextInt(); String s = next(); String sh = s.substring(0, 2); String sm = s.substring(3); if (isMirror(sh) && isMirror(sm) && Integer.parseInt(mirror(sm)) < h && Integer.parseInt(mirror(sh)) < m) { System.out.println(sh + ":" + sm); } else { boolean exist = false; int time = Integer.parseInt(sh) * m + Integer.parseInt(sm); for (int j = time + 1; j < h * m; j++) { sh = pad((j / m) + ""); sm = pad((j % m) + ""); if (isMirror(sh) && isMirror(sm) && Integer.parseInt(mirror(sm)) < h && Integer.parseInt(mirror(sh)) < m) { exist = true; System.out.println(sh + ":" + sm); break; } } if (!exist) { System.out.println("00:00"); } } } } static boolean isMirror(String s) { for (int i = 0; i < s.length(); i++) { if (map.get(s.charAt(i)) == null) { return false; } } return true; } static String mirror(String s) { StringBuilder res = new StringBuilder(); for (int i = s.length()-1; i >= 0 ; i--) { res.append(map.get(s.charAt(i))); } return res.toString(); } static String pad(String s) { if (s.length() <= 1) { return "0" + s; } else { return s; } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
def reflective(newh, newm, th, tm): r = '01258' #print(int(str(newm).zfill(2)[::-1]), newm) if not ((str(newh // 10) in r) and (str(newh % 10) in r)): return False if not ((str(newm // 10) in r) and (str(newm % 10) in r)): return False newm = str(newm).zfill(2)[::-1] newh = str(newh).zfill(2)[::-1] nm = '' nh = '' for ch in newm: if ch == '5': nm += '2' elif ch == '2': nm += '5' else: nm += ch for ch in newh: if ch == '5': nh += '2' elif ch == '2': nh += '5' else: nh += ch newm = nm newh = nh if not((int(newm) < th) and (int(newh) < tm)): return False return True t = int(input()) for _ in range(t): th, tm = [int(x) for x in input().split()] h, m = [int(x) for x in input().split(':')] flag = True for i in range(th): for j in range(tm): newm = (m + j) % tm; newh = (h + i + (m + j)//tm) % th; if (reflective(newh, newm, th, tm)): t = str(newh).zfill(2) + ":" + str(newm).zfill(2) print(t) flag = False break if not flag: break
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#region Header #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools import bisect import heapq def input(): return sys.stdin.readline()[:-1] # sys.setrecursionlimit(1000000) #endregion # _INPUT = """5 # 1 100 # 00:01 # 10 10 # 04:04 # 24 60 # 12:21 # 24 60 # 23:59 # 90 80 # 52:26 # """ # sys.stdin = io.StringIO(_INPUT) def is_mirrorable(H, M, h, m): D = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8} if not((h % 10 in D) and (h // 10 in D) and (m % 10 in D) and (m // 10 in D)): return False m1 = D[h % 10] * 10 + D[h // 10] h1 = D[m % 10] * 10 + D[m // 10] if 0 <= h1 < H and 0 <= m1 < M: return True else: return False def solve(H, M, S): h = int(S[:2]) m = int(S[3:]) while True: if is_mirrorable(H, M, h, m): return f'{h:02d}:{m:02d}' m += 1 if m == M: h += 1 m = 0 if h == H: h = 0 def main(): T0 = int(input()) for _ in range(T0): H, M = map(int, input().split()) S = input() ans = solve(H, M, S) print(ans) if __name__ == '__main__': main()
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
//Utilities import java.io.*; import java.util.*; public class Main { static int T; static int h, m; static int a, b; static int[] v = new int[10]; static String[] tmp = new String[2]; public static void main(String[] args) throws IOException { Arrays.fill(v, -1); v[0] = 0; v[1] = 1; v[2] = 5; v[5] = 2; v[8] = 8; T = in.iscan(); while (T-- > 0) { h = in.iscan(); m = in.iscan(); tmp = in.sscan().split(":"); a = Integer.parseInt(""+tmp[0]); b = Integer.parseInt(""+tmp[1]); while (!isValid(a, b)) { if (b != m-1) { b++; } else { b = 0; if (a != h-1) { a++; } else { a = 0; } } } String res1 = a >= 10 ? ""+a : "0" + a; String res2 = b >= 10 ? ""+b : "0" + b; System.out.println(res1 + ":" + res2); } out.close(); } static boolean isValid(int a, int b) { int[] d = new int[4]; d[0] = a / 10; d[1] = a % 10; d[2] = b / 10; d[3] = b % 10; int[] nd = new int[4]; for (int i = 0; i < 4; i++) { if (v[d[i]] == -1) { return false; } nd[3-i] = v[d[i]]; } int na = nd[0] * 10 + nd[1]; int nb = nd[2] * 10 + nd[3]; if (na < h && nb < m) { return true; } else { return false; } } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static int gcd (int a, int b) { return b == 0 ? a : gcd (b, a % b); } public static int lcm (int a, int b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static int fast_pow (int b, int x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { string s; char check[5]={'0','1','2','5','8'}; int h,m; cin >> h >> m; cin >> s; int sum1 = 0,sum2=0; int i; for( i=0;i<s.size();i++) { if(s[i]==':') break; sum1 = sum1*10 + (s[i]-'0'); } for(++i;i<s.size();i++) { sum2 = sum2*10 + (s[i]-'0'); } int ok1 = 0,ok2 = 0; string str1,str2,t1,t2; while(ok2==0 || ok1==0) { str2 = to_string(sum2); if(str2.size()==1){ str2+="0"; reverse(str2.begin(),str2.end()); str2[0] = '0'; } t2 = str2; for(int i=0;i<str2.size();i++) { if(str2[i]==check[0] || str2[i]==check[1] || str2[i]==check[2] || str2[i]==check[3] || str2[i]==check[4]) { if(i==1) { if(str2[0]=='2') str2[0] = '5'; else if(str2[0]=='5') str2[0] = '2'; if(str2[1]=='2') str2[1] = '5'; else if(str2[1]=='5') str2[1] = '2'; reverse(str2.begin(),str2.end()); int p = stoi(str2); if(p>=0 && p<=h-1){ ok2=1; } else { str2 = t2; } } } else break; } str1 = to_string(sum1); if(str1.size()==1){ str1+="0"; reverse(str1.begin(),str1.end()); str1[0] = '0'; } t1 = str1; for(int i=0;i<str1.size();i++) { if(str1[i]==check[0] || str1[i]==check[1] || str1[i]==check[2] || str1[i]==check[3] || str1[i]==check[4]) { if(i==1) { //cout<<str1; if(str1[0]=='2') str1[0] = '5'; else if(str1[0]=='5') str1[0] = '2'; if(str1[1]=='2') str1[1] = '5'; else if(str1[1]=='5') str1[1] = '2'; reverse(str1.begin(),str1.end()); int p = stoi(str1); if(p>=0 && p<=m-1){ ok1=1; } else { str1 = t1; } } } else break; } // cout<<sum2<<" "<<sum1<<" "<<ok2<<" "<<ok1<<endl; if(ok2==0 || ok1 ==0 ){ sum2 = (sum2 + 1)%m; ok2 = 0; if(sum2==0) { sum1 = (sum1 + 1) %h; ok1 = 0; } } } cout<<t1<<":"<<t2<<endl; } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> using namespace std; #define ll long long #define pb push_back #define mp make_pair #define mt make_tuple #define ff first #define ss second #define M1 1000000007 #define M2 998244353 #define fl(i,a,b) for(ll i=a;i<b;i++) #define bfl(i,a,b) for(ll i=b-1;i>=a;i--) #define f(i,n) for(int i=0;i<n;i++) #define bf(i,n) for(int i=n-1;i>=0;i--) #define f1(i,n) for(int i=1;i<=n;i++) #define bf1(i,n) for(int i=n;i>=1;i--) #define all(v) v.begin(),v.end() #define pll pair<long,long> #define pii pair<int,int> #define vi vector<int> #define vl vector<ll> #define p0(a) cout << a << " " #define p1(a) cout << a << endl #define p2(a, b) cout << a << " " << b << endl #define p3(a, b, c) cout << a << " " << b << " " << c << endl #define p4(a,b,c,d) cout << a << " " << b << " " << c << " " << d << endl #define debug(x) cerr << #x << " = " << x << endl; #define bn "\n" #define pbn cout<<"\n" ll modI(ll a,ll m); ll gcd(ll a,ll b); ll powM(ll x,ll y,ll m); ll swap(ll a,ll b); void swap(ll& a,ll& b) { ll tp=a; a=b; b=tp; } ll gcd(ll x,ll y) { if(x==0) return y; return gcd(y%x,x); } ll powM(ll x,ll y,ll m) { ll ans=1,r=1; x%=m; while(r>0&&r<=y) { if(r&y) { ans*=x; ans%=m; } r<<=1; x*=x; x%=m; } return ans; } ll modI(ll a, ll m) { ll m0=m,y=0,x=1; if(m==1) return 0; while(a>1) { ll q=a/m; ll t=m; m=a%m; a=t; t=y; y=x-q*y; x=t; } if(x<0) x+=m0; return x; } //----------------------------------------------------------------------------- int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(0); int tt=1; cin>>tt; f1(testcase_no,tt) { // cout<<"test case no. "<<testcase_no<<bn; int h,m; cin>>h>>m; char c[5]; f(i,5)cin>>c[i]; int h1=(c[0]-'0')*10+(c[1]-'0'); int m1=(c[3]-'0')*10+(c[4]-'0'); // cout<<h1<<bn; // cout<<m1<<bn; // int h11=(c[0]-'0') int ref[10]={0,1,5,-1,-1,2,-1,-1,8,-1}; int hh1[2]={h/10,h%10}; int mm1[2]={m/10,m%10}; int ans[4]={0}; int ok=0; for(int i=h1;i<h;i++) { int z1=0; if(i==h1)z1=m1; for(int j=z1;j<m;j++) { ok=1; int hh[2]={i/10,i%10}; int mm[2]={j/10,j%10}; f(ii,2) { if(ref[hh[ii]]==-1 )ok=0; if(ref[mm[ii]]==-1 )ok=0; } // int m2=(c[3]-'0')*10+(c[4]-'0'); int i2=ref[hh[1]]*10+ref[hh[0]] ,j2=ref[mm[1]]*10+ref[mm[0]] ; if(i2>=m || j2>=h)ok=0; if(ok) { ans[0]=hh[0]; ans[1]=hh[1]; ans[2]=mm[0]; ans[3]=mm[1]; break; // goto done;; } } if(ok)break; } if(ok==0) { cout<<"00:00"<<bn;continue;} // done; // cout<<"YES"<<bn; f(i,2)cout<<ans[i]; cout<<":"; for(int i=2;i<4;i++) cout<<ans[i]; pbn; } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
def do(): conv = dict() conv["0"] = "0" conv["1"] = "1" conv["2"] = "5" conv["3"] = "xxxxxx" conv["4"] = "xxxxxx" conv["5"] = "2" conv["6"] = "xxxxxx" conv["7"] = "xxxxxx" conv["8"] = "8" conv["9"] = "xxxxxx" def isitok(curtime): curtime %= maxtime h, m = curtime // maxm, curtime % maxm #print(h, m) hstr = "{:02}".format(h) mstr = "{:02}".format(m) newm = conv[hstr[1]] + conv[hstr[0]] newh = conv[mstr[1]] + conv[mstr[0]] #print(newh, newh) if newm.find("x") != -1 or newh.find("x") != -1: return False if int(newh) >= maxh or int(newm) >= maxm: return False return True maxh, maxm = map(int, input().split()) s = input().split(":") h, m = int(s[0]), int(s[1]) curtime = (maxm * h) + m maxtime = maxh * maxm #print(curtime, maxtime) while True: if isitok(curtime): h, m = curtime // maxm, curtime % maxm print("{:02}".format(h)+":"+"{:02}".format(m)) break curtime += 1 curtime %= maxtime q = int(input()) for _ in range(q): do() #print("--")
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> using namespace std; template <typename A, typename B> string to_string(pair<A, B> p); string to_string(const char& ch) { return "'" + string(1, ch) + "'"; } string to_string(const string& s) { return '"' + s + '"'; } string to_string(const char* s) { return to_string((string) s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ", "; } first = false; res += to_string(v[i]); } res += "}"; return res; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res; } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } #define output cout void debug_out() { output << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { output << " " << to_string(H); debug_out(T...); } #ifndef ONLINE_JUDGE #define dbg(...) output << "[" << #__VA_ARGS__ << "] :", debug_out(__VA_ARGS__) #else #define dbg(...) 42 #endif #define ll int64_t #define ull uint64_t #define lld long double #define FIO ios_base::sync_with_stdio(false);cin.tie(NULL); #define pb push_back #define eb emplace_back #define ff first #define ss second #define vt vector #define vll vt<ll> #define pll pair<ll,ll> #define vpll vt<pll> #define vvll vt<vll> #define all(v) v.begin(),v.end() #define rall(v) v.rbegin(), v.rend() #define FOR(i,n) for(ll i=0;i<n;i++) #define ffo(i,a,b) for(ll i=a;i<=b;i++) #define rfo(i,a,b) for(ll i=a;i>=b;i--) template <typename T> using mxpq = priority_queue<T>; template <typename T> using mnpq = priority_queue<T, vt<T>, greater<T>>; #define fps(x,y) fixed << setprecision(y) << x #define mmss(xa,v) memset(xa,v,sizeof(xa)) // use only if v = -1 or 0, else use fill template<typename T1, typename T2> istream& operator>>(istream& in, pair<T1, T2> &a) {in >> a.ff >> a.ss; return in;} template<typename T1, typename T2> ostream& operator<<(ostream& out, pair<T1, T2> a) {out << a.ff << " " << a.ss; return out;} template<typename T, typename T1> T amax(T &a, T1 b) {if (b > a) a = b; return a;} template<typename T, typename T1> T amin(T &a, T1 b) {if (b < a) a = b; return a;} template <class A, size_t S> istream& operator>>(istream& in, array<A, S>& a) { for (A& x : a) in >> x; return in; } template <class A, size_t S> ostream& operator<<(ostream& out, array<A, S>& a) { bool f = false; for (A& x : a) { if (f) out << " "; out << x; f = true; } return out; } template <typename T> istream& operator>>(istream& in, vt<T>& a) { for (T& x : a) in >> x; return in; } template <typename T> ostream& operator<<(ostream& out, vt<T>& a) { bool f = false; for (T& x : a) {if (f) out << " "; out << x; f = true; } return out; } int dx[4] = { -1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; // up, right, down, left const lld PI = 3.14159265359; const ll INF = 2e18; const ll N = 1e6 + 6; const ll MAX_SIZE = 2e6 + 6; const ll mod = 163577857; ll powerM(ll x, ll y, ll M = mod) { // default argument ll v = 1; x = x % M; while (y > 0) {if (y & 1)v = (v * x) % M; y = y >> 1; x = (x * x) % M;} return v; } ll power(ll x, ll y) { ll v = 1; while (y > 0) {if (y & 1)v = v * x; y = y >> 1; x = x * x;} return v; } int largest_bit(long long x) { // based on 0-indexing return x == 0 ? -1 : 63 - __builtin_clzll(x); } const ll maxN = 1e5 + 5; void preSolve() { } void solve() { ll h, m; cin >> h >> m; map<ll, ll> mp; mp[0] = 0; mp[1] = 1; mp[2] = 5; mp[5] = 2; mp[8] = 8; mp[3] = -1; mp[4] = -1; mp[6] = -1; mp[7] = -1; mp[9] = -1; string s; cin >> s; auto valid = [&](ll hh, ll mm) { string hrs = to_string(hh); if (hrs.length() == 1) hrs = '0' + hrs; string mins = to_string(mm); if (mins.length() == 1) mins = '0' + mins; string g = hrs + ':' + mins; // dbg(g); set<ll> skk; skk.insert(hrs[0] - '0'); skk.insert(hrs[1] - '0'); skk.insert(mins[0] - '0'); skk.insert(mins[1] - '0'); for (auto it : skk) { if (mp[it] == -1) { return false; } } string rev; FOR(i, 5) { rev.pb(g[4 - i]); if (rev.back() == '2') { rev[(ll)rev.size() - 1] = '5'; } else if (rev.back() == '5') { rev[(ll)rev.size() - 1] = '2'; } } // dbg(rev); ll hir = stoi(rev.substr(0, 2)); ll mir = stoi(rev.substr(3, 2)); if (hir < h && mir < m) { cout << g << endl; return true; } return false; }; ll ih = stoi(s.substr(0, 2)); ll im = stoi(s.substr(3, 2)); ll tmph = ih, tmpm = im; ll tim = h * m; while (tim--) { if (tmpm >= m) { tmpm = 0; tmph++; if (tmph >= h) { tmph = 0; } } if (valid(tmph, tmpm)) { return; } tmpm++; } } signed main() { #ifdef LOCAL freopen("in1.txt", "r", stdin); freopen("out1.txt", "w", stdout); #endif FIO; preSolve(); int testcases = 1; cin >> testcases; for (int caseno = 1; caseno <= testcases; ++caseno) { // cout << "Case #" << caseno << ": "; solve(); // cout << endl; } return 0; } /* On getting WA: 1. Check if implementation is correct and NOTHING overflows. 2. Start thinking about counter cases for your logic as well as implementation. 3. Try removing redundancy (any additon you might have done for ease of implementation or thought process) and putting asserts. 4. Make a generator, an unoptimized but correct soln and run it against wrong soln. Things you may rarely use: In C++, comparator should return false if its arguments are equal. #define _GLIBCXX_DEBUG // Use at the top of code cerr << "[Execution : " << (1.0 * clock()) / CLOCKS_PER_SEC << "s]\n"; int dx[] = {+1,-1,+0,+0,-1,-1,+1,+1}; // Eight Directions int dy[] = {+0,+0,+1,-1,+1,-1,-1,+1}; // Eight Directions int dx[]= {-2,-2,-1,1,-1,1,2,2}; // Knight moves int dy[]= {1,-1,-2,-2,2,2,-1,1}; // Knight moves For taking a complete line as input: string s; while(s == "") getline(cin, s); For calculating inverse modulo, raise to the power mod-2. For (a^b)%mod, where b is large, replace b by b%(mod-1). x | (x + 1) sets lowest unset bit of x x & (x - 1) unsets lowest set bit of x x - 1 unsets the lowest set bit and sets all bits on it's right arr.erase(unique(all(arr)), arr.end()); // erase duplicates #define merg(a,b,c) set_union(a.begin(),a.end(),b.begin(),b.end(),inserter(c,c.begin())) https://www.techiedelight.com/merge-two-sets-set_union-merge-cpp/ #pragma GCC optimize "trapv" // catches integer overflows #pragma GCC optimize ("O3") #pragma GCC target ("sse4") #pragma GCC optimize("Ofast") #pragma GCC optimize("Ofast,unroll-loops") #pragma GCC target("avx,avx2,fma") #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; functions: set.insert(val), *(set.find_by_order(order-1)), set.order_of_key(val) less_equal for multiset #include <ext/pb_ds/priority_queue.hpp> template<typename T> using pbds_pq = __gnu_pbds::priority_queue<T>; template<typename T> using pbds_min_pq = __gnu_pbds::priority_queue<T, greater<T>>; */
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include<cstdio> using namespace std; int tim[26]={0,0,1,2,5,8,10,11,12,15,18,20,21,22,25,28,50,51,52,55,58,80,81,82,85,88}; int flc[26]={0,0,10,50,20,80,1,11,51,21,81,5,15,55,25,85,2,12,52,22,82,8,18,58,28,88}; int amax,bmax; int finda(int v) { while(1) { if(tim[v]>=amax) v=1; if(flc[v]<bmax) return v; v=v%25+1; } } int findb(int v) { while(1) { if(tim[v]>=bmax) v=1; if(flc[v]<amax) return v; v=v%25+1; } } int main() { int t,a,b,v,va,vb; char x,y; scanf("%d",&t); while(t--) { scanf("%d%d",&amax,&bmax); getchar(); x=getchar(); y=getchar(); a=(x-'0')*10+y-'0'; getchar(); x=getchar(); y=getchar(); b=(x-'0')*10+y-'0'; v=1; while(tim[v]<a) { ++v; if(v==26) { v=1; break; } } va=finda(v); if(tim[va]==a) { v=1; while(tim[v]<b) { ++v; if(v==26) { v=1; break; } } vb=findb(v); if(tim[vb]<b) { va=finda(va+1); vb=1; } } else vb=1; x=tim[va]/10+'0'; y=tim[va]%10+'0'; printf("%c%c:",x,y); x=tim[vb]/10+'0'; y=tim[vb]%10+'0'; printf("%c%c\n",x,y); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<long long> vl; #define pll pair<ll, ll> #define vpl vector<pll> #define vb vector<bool> #define PB push_back #define MP make_pair #define ln "\n" #define forn(i,e) for(ll i=0; i<e; i++) #define forsn(i,s,e) for(ll i=s; i<e; i++) #define rforn(i,e) for(ll i=e; i>=0; i--) #define rforsn(i,s,e) for(ll i=s; i>=e; i--) #define vasort(v) sort(v.begin(), v.end()) #define vdsort(v) sort(v.begin(), v.end(),greater<ll>()) #define F first #define S second #define out1(x1) cout << x1 << ln #define out2(x1,x2) cout << x1 << " " << x2 << ln #define out3(x1,x2,x3) cout << x1 << " " << x2 << " " << x3 << ln #define out4(x1,x2,x3,x4) cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln #define out5(x1,x2,x3,x4,x5) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln #define out6(x1,x2,x3,x4,x5,x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln #define in1(x1) cin >> x1 #define in2(x1,x2) cin >> x1 >> x2 #define in3(x1,x2,x3) cin >> x1 >> x2 >> x3 #define in4(x1,x2,x3,x4) cin >> x1 >> x2 >> x3 >> x4 #define in5(x1,x2,x3,x4,x5) cin >> x1 >> x2 >> x3 >> x4 >> x5 #define in6(x1,x2,x3,x4,x5,x6) cin >> x1 >> x2 >> x3 >> x4 >> x5 >> x6 #define mz(a) memset(a,0,sizeof(a)) #define arrin(a,n) forn(i,n) cin >> a[i]; #define arrout(a,n) forn(i,n) {cout << a[i] << " ";} cout << ln; #define TYPEMAX(type) std::numeric_limits<type>::max() #define TYPEMIN(type) std::numeric_limits<type>::min() #define zoom ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #pragma GCC optimize("Ofast") #pragma GCC target("avx,avx2,fma") #pragma GCC optimization ("unroll-loops") vl v(10, -1); ll h,m; bool check(ll f1,ll f2,ll f3,ll f4){ if (v[f1]==-1 || v[f2]==-1 || v[f3]==-1 || v[f4]==-1) return false; ll h1=v[f4]; ll h2=v[f3]; ll h3=v[f2]; ll h4=v[f1]; if (h1*10+h2>=h || h3*10+h4>=m) return false; return true; } void solve() { in2(h,m); string s; in1(s); v[0]= 0; v[1]= 1; v[2]= 5; v[5]= 2; v[8]= 8; ll f1=s[0]-'0'; ll f2=s[1]-'0'; ll f3=s[3]-'0'; ll f4=s[4]-'0'; while(!check(f1,f2,f3,f4)){ f4++; if (f4==10 || f4>=m) f3++,f4=0; if (f3*10+f4>=m) f2++,f3=0,f4=0; if (f2==10 || f2>=h) f2=0,f1++,f3=0,f4=0; if (f1*10+f2>=h) f1=0,f2=0,f3=0,f4=0; } cout<<f1<<f2<<":"<<f3<<f4<<"\n"; } int main() { zoom; ll t; in1(t); while(t--) { solve(); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.*; import java.util.*; import java.lang.*; public class beng{ public static int f(int x) { if(x == 5)return 2; else if(x == 2)return 5; else return x; } public static int chk(int x, int y, int A, int B) { int arr[] = {0, 1, 2, -1, -1, 5, -1, -1, 8, -1}; int a = x % 10; int b = x / 10; int a1 = y % 10; int b1 = y / 10; if(arr[a] == -1 || arr[b] == -1 || arr[a1] == -1 || arr[b1] == -1) return 0; else if(f(a1) * 10 + f(b1) < A && f(a) * 10 + f(b) < B)return 1; else return 0; } public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t--> 0) { int A = s.nextInt(); int B = s.nextInt(); String str = s.next(); int x = Integer.parseInt(str.substring(0, 2)); int y = Integer.parseInt(str.substring(3)); while(true) { if(chk(x, y, A, B) == 1){ System.out.println((x < 10 ? "0" : "") + x + ":" + (y < 10 ? "0":"") + y); break; } y++; if(y >= B){ y = 0; x++; } if(x>=A) { x = 0; } } } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> using namespace std; int h, m, h1, h0, m1, m0, hh, mm; int a[10] = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1}; bool Chk(int x1, int x0, int y1, int y0) { if(y1 == -1 || y0 == -1) return false; if(y1 > x1) return false; if(y1 == x1) return y0 < x0; return true; } bool Check() { int hh1 = hh / 10, hh0 = hh % 10; int mm1 = mm / 10, mm0 = mm % 10; swap(hh1, mm0), swap(hh0, mm1); return Chk(h1, h0, a[hh1], a[hh0]) && Chk(m1, m0, a[mm1], a[mm0]); } int main() { int T; scanf("%d", &T); while(T--) { scanf("%d%d", &h, &m); scanf("%d:%d", &hh, &mm); h1 = h / 10, h0 = h % 10; m1 = m / 10, m0 = m % 10; while(true) { if(Check()) { printf("%02d:%02d\n", hh, mm); break; } ++mm; if(mm == m) mm = 0, ++hh; if(hh == h) hh = 0; } } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int test=sc.nextInt(); for(int i=0;i<test;i++) { int h=sc.nextInt(); int m=sc.nextInt(); String str=sc.next(); boolean valid=false; String hour=str.substring(0,2); int curr_hour=Integer.parseInt(hour); String minute=str.substring(3,5); int curr_minute=Integer.parseInt(minute); while(valid==false) { valid=true; int temp=curr_minute; int temp1=curr_minute; int reflected_minute=0; int reflected_hour=0; while(temp>0) { if(temp%10==3||temp%10==4||temp%10==6||temp%10==7||temp%10==9) { valid=false; break; } temp=temp/10; } if(valid==true) { int d=temp1%10; if(d==5) reflected_minute=20; else if(d==2) reflected_minute=50; else reflected_minute=d*10; temp1=temp1/10; if(temp1==2) reflected_minute+=5; else if(temp1==5) reflected_minute+=2; else reflected_minute+=temp1; } if(reflected_minute>=h) { valid=false; } temp=curr_hour; temp1=curr_hour; while(temp>0) { if(temp%10==3||temp%10==4||temp%10==6||temp%10==7||temp%10==9) { valid=false; break; } temp=temp/10; } if(valid==true) { int d=temp1%10; if(d==5) reflected_hour=20; else if(d==2) reflected_hour=50; else reflected_hour=d*10; temp1=temp1/10; if(temp1==2) reflected_hour+=5; else if(temp1==5) reflected_hour+=2; else reflected_hour+=temp1; } if(reflected_hour>=m) { valid=false; } if(valid==false) { if(curr_minute<m-1) { curr_minute++; } else if(curr_minute==m-1) { if(curr_hour<h-1) { curr_hour++; curr_minute=0; } else if(curr_hour==h-1) { curr_hour=0; curr_minute=0; valid=true; break; } } } } if(curr_hour<10) { System.out.print("0"+curr_hour+":"); } else { System.out.print(curr_hour+":"); } if(curr_minute<10) { System.out.print("0"+curr_minute); } else { System.out.print(curr_minute); } System.out.println(); } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
def mirro(n): if n==5: return 2 elif n==2: return 5 else: return n t=int(input()) ok=[0,1,2,5,8] for _ in range(t): h,m=map(int,input().split()) ttime=str(input()) hnow,mnow=int(ttime[0])*10+int(ttime[1]),int(ttime[3])*10+int(ttime[4]) while True: h0,h1=hnow//10,hnow%10 m0,m1=mnow//10,mnow%10 if h0 in ok and h1 in ok and m0 in ok and m1 in ok: mh0=mirro(m1) mh1=mirro(m0) mm0=mirro(h1) mm1=mirro(h0) mh=10*mh0+mh1 mm=10*mm0+mm1 if mh<h and mm<m: minu=m0*10+m1+100 hour=h0*10+h1+100 print("".join([str(hour)[1:],':',str(minu)[1:]])) break mnow+=1 if mnow==m: mnow=0 hnow+=1 if hnow==h: hnow=0
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; public class Main implements Runnable { int n, m, k; static boolean use_n_tests = true; void solve(FastScanner in, PrintWriter out, int testNumber) { int h = in.nextInt(); int m = in.nextInt(); char[] time = in.next().toCharArray(); int hu = time(time[0], time[1]); int mu = time(time[3], time[4]); while (true) { if (isOk(hu, mu)) { int one = hu / 10; int two = hu % 10; int thee = mu / 10; int four = mu % 10; int hu1 = convert(four) * 10 + convert(thee); int mu1 = convert(two) * 10 + convert(one); if (hu1 < h && mu1 < m) { out.printf("%02d:%02d\n", hu, mu); return; } } mu++; if (mu == m) { hu++; } mu %= m; hu %= h; } } boolean isOk(int h,int m) { if (correct(m / 10) && correct(m % 10) && correct(h / 10) && correct(h % 10)) return true; return false; } boolean correct(int d) { return d == 0 || d == 1 || d == 2 || d == 5 || d == 8; } int convert(int d) { if (d == 1 || d == 0 || d == 8) { return d; } if (d == 2) { return 5; } if (d == 5) { return 2; } return -1; } int time(char a, char b) { return (a - '0') * 10 + (b - '0'); } // ****************************** template code *********** List<Integer> getGidits(long n) { List<Integer> res = new ArrayList<>(); while (n != 0) { res.add((int) (n % 10L)); n /= 10; } return res; } List<Integer> generatePrimes(int n) { List<Integer> res = new ArrayList<>(); boolean[] sieve = new boolean[n + 1]; for (int i = 2; i <= n; i++) { if (!sieve[i]) { res.add(i); } if ((long) i * i <= n) { for (int j = i * i; j <= n; j += i) { sieve[j] = true; } } } return res; } int ask(int l, int r) { if (l >= r) { return -1; } System.out.printf("? %d %d\n", l + 1, r + 1); System.out.flush(); return in.nextInt() - 1; } static int stack_size = 1 << 27; class Mod { long mod; Mod(long mod) { this.mod = mod; } long add(long a, long b) { a = mod(a); b = mod(b); return (a + b) % mod; } long sub(long a, long b) { a = mod(a); b = mod(b); return (a - b + mod) % mod; } long mul(long a, long b) { a = mod(a); b = mod(b); return a * b % mod; } long div(long a, long b) { a = mod(a); b = mod(b); return (a * inv(b)) % mod; } public long inv(long r) { if (r == 1) return 1; return ((mod - mod / r) * inv(mod % r)) % mod; } private long mod(long a) { return a % mod; } } class Coeff { long mod; long[][] C; long[] fact; boolean cycleWay = false; Coeff(int n, long mod) { this.mod = mod; fact = new long[n + 1]; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = i; fact[i] %= mod; fact[i] *= fact[i - 1]; fact[i] %= mod; } } Coeff(int n, int m, long mod) { // n > m cycleWay = true; this.mod = mod; C = new long[n + 1][m + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, m); j++) { if (j == 0 || j == i) { C[i][j] = 1; } else { C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; C[i][j] %= mod; } } } } public long C(int n, int m) { if (cycleWay) { return C[n][m]; } return fC(n, m); } private long fC(int n, int m) { return (fact[n] * inv(fact[n - m] * fact[m] % mod)) % mod; } private long inv(long r) { if (r == 1) return 1; return ((mod - mod / r) * inv(mod % r)) % mod; } } class Pair { int first; long second; Pair(int f, long s) { first = f; second = s; } public int getFirst() { return first; } public long getSecond() { return second; } } class MultisetTree<T> { int size = 0; TreeMap<T, Integer> mp = new TreeMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } boolean contains(T x) { return mp.containsKey(x); } T greatest() { return mp.lastKey(); } T smallest() { return mp.firstKey(); } int size() { return size; } int diffSize() { return mp.size(); } } class Multiset<T> { int size = 0; Map<T, Integer> mp = new HashMap<>(); void add(T x) { mp.merge(x, 1, Integer::sum); size++; } boolean contains(T x) { return mp.containsKey(x); } void remove(T x) { if (mp.containsKey(x)) { mp.merge(x, -1, Integer::sum); if (mp.get(x) == 0) { mp.remove(x); } size--; } } int size() { return size; } int diffSize() { return mp.size(); } } static class Range { int l, r; int id; public int getL() { return l; } public int getR() { return r; } public Range(int l, int r, int id) { this.l = l; this.r = r; this.id = id; } } static class Array { static Range[] readRanges(int n, FastScanner in) { Range[] result = new Range[n]; for (int i = 0; i < n; i++) { result[i] = new Range(in.nextInt(), in.nextInt(), i); } return result; } static List<List<Integer>> intInit2D(int n) { List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < n; i++) { res.add(new ArrayList<>()); } return res; } static boolean isSorted(Integer[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static public long sum(int[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static public long sum(long[] a) { long sum = 0; for (long x : a) { sum += x; } return sum; } static public long sum(Integer[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static public int min(Integer[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int min(int[] a) { int mn = Integer.MAX_VALUE; for (int x : a) { mn = Math.min(mn, x); } return mn; } static public int max(Integer[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int max(int[] a) { int mx = Integer.MIN_VALUE; for (int x : a) { mx = Math.max(mx, x); } return mx; } static public int[] readint(int n, FastScanner in) { int[] out = new int[n]; for (int i = 0; i < out.length; i++) { out[i] = in.nextInt(); } return out; } } class Graph { List<List<Integer>> graph; Graph(int n) { create(n); } void create(int n) { List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } this.graph = graph; } void readBi(int m, FastScanner in) { for (int i = 0; i < m; i++) { int v = in.nextInt() - 1; int u = in.nextInt() - 1; graph.get(v).add(u); graph.get(u).add(v); } } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream io) { br = new BufferedReader(new InputStreamReader(io)); } public String line() { String result = ""; try { result = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return result; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public long[] nextArrayL(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Long[] nextArrayL2(int n) { Long[] res = new Long[n]; for (int i = 0; i < n; i++) { res[i] = in.nextLong(); } return res; } public Integer[] nextArray2(int n) { Integer[] res = new Integer[n]; for (int i = 0; i < n; i++) { res[i] = in.nextInt(); } return res; } public long nextLong() { return Long.parseLong(next()); } } void run_t_tests() { int t = in.nextInt(); int i = 0; while (t-- > 0) { solve(in, out, i++); } } void run_one() { solve(in, out, -1); } @Override public void run() { in = new FastScanner(System.in); out = new PrintWriter(System.out); if (use_n_tests) { run_t_tests(); } else { run_one(); } out.close(); } static FastScanner in; static PrintWriter out; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(null, new Main(), "", stack_size); thread.start(); thread.join(); } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.BufferedReader; import java.io.InputStreamReader; public class B { static class Pair { long a; long b; public Pair(long a, long b) { this.a = a; this.b = b; } } public static void main(String[] args) throws Exception { // write your code here BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int t = getInt(reader.readLine()); while (t-- > 0) { int[] inp = getArray(reader.readLine()); int h = inp[0]; int m = inp[1]; String s = reader.readLine(); int ch = Integer.parseInt(s.substring(0, 2)); int cm = Integer.parseInt(s.substring(3, 5)); while (ch != 0 || cm != 0) { StringBuilder hr = new StringBuilder(); StringBuilder mn = new StringBuilder(); StringBuilder mirror_h = new StringBuilder(); StringBuilder mirror_m = new StringBuilder(); if (ch < 10) { hr.append('0'); } hr.append(ch); if (cm < 10) { mn.append('0'); } mn.append(cm); String main = hr.toString() + mn.toString(); int c1 = 0; for (int i = main.length() - 1; i >= 0; i--) { char c = main.charAt(i); if (mirror_h.length() < 2) { if (c == '0') { c1++; mirror_h.append('0'); } else if (c == '1') { c1++; mirror_h.append('1'); } else if (c == '2') { c1++; mirror_h.append('5'); } else if (c == '5') { c1++; mirror_h.append('2'); } else if (c == '8') { c1++; mirror_h.append('8'); } } else { if (c == '0') { c1++; mirror_m.append('0'); } else if (c == '1') { c1++; mirror_m.append('1'); } else if (c == '2') { c1++; mirror_m.append('5'); } else if (c == '5') { c1++; mirror_m.append('2'); } else if (c == '8') { c1++; mirror_m.append('8'); } } } if (c1 < 4) { if (cm + 1 == m) { cm = 0; if (ch + 1 == h) { ch = 0; } else { ch++; } } else { cm++; } continue; } int mir_h = Integer.parseInt(mirror_h.toString()); int mir_m = Integer.parseInt(mirror_m.toString()); if (mir_h >= h || mir_m >= m) { if (cm + 1 == m) { cm = 0; if (ch + 1 == h) { ch = 0; } else { ch++; } } else { cm++; } continue; } else if (c1 == 4) { break; } } StringBuilder hr = new StringBuilder(); StringBuilder mn = new StringBuilder(); if (ch < 10) { hr.append('0'); } hr.append(ch); if (cm < 10) { mn.append('0'); } mn.append(cm); System.out.println(hr.toString() + ":" + mn.toString()); } } private static int[] getArray(String readLine) { String strings[] = readLine.split(" "); int n = strings.length; int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(strings[i]); } return a; } private static long[] getLongArray(String readLine) { String strings[] = readLine.split(" "); int n = strings.length; long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(strings[i]); } return a; } private static int getInt(String s) { try { return Integer.parseInt(s); } catch (Exception e) { return 0; } } private static long getLong(String s) { try { return Long.parseLong(s); } catch (Exception e) { return 0; } } private static double getDouble(String s) { try { return Double.parseDouble(s); } catch (Exception e) { return 0; } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#include <bits/stdc++.h> using namespace std; #define int long long #define ld long double #define pii pair<int,int> #define pf push_front #define pb push_back #define ub upper_bound #define lb lower_bound #define ppb pop_back #define ppf pop_front #define F(i,a,b) for(int i = a; i < b; ++i) #define R(i,a,b) for(int i = a; i >= b; --i) #define rep(i,a,b) for(int i = a; i <= b; ++i) #define fr first #define sc second #define sz(x) (int)((x).size()) #define all(x) (x).begin(),(x).end() const int INF = 1e9+7; vector<int> refD = {0,1,5,-1,-1,2,-1,-1,8,-1}; string padd(int x){ string res = to_string(x); if(res.length()==1){ res = "0"+res; } return res; } int mirror(int x){ string s = to_string(x); if(sz(s)==1) s = "0"+s; string res =""; if(refD[s[1]-'0']==-1) return INF; else res+=char(refD[s[1]-'0']+'0'); if(refD[s[0]-'0']==-1) return INF; else res+=char(refD[s[0]-'0']+'0'); return stoi(res); } void solve(){ int h,m; string s; cin >> h >> m >> s; int H = (s[0]-'0')*10+s[1]-'0'; int M = (s[3]-'0')*10+s[4]-'0'; while(1){ if(M==m){ M=0; H++; } if(H==h){ H=0; M=0; } if(mirror(H)<m && mirror(M)<h){ cout << padd(H) << ":" << padd(M) << "\n"; return; } M++; } } signed main() { ios_base::sync_with_stdio(false);cin.tie(NULL); int TC = 1;cin >> TC; rep(T,1,TC){ //cout << "Case #" << T << " : "; solve(); } return 0; }
CPP
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; public class _705_B { static int t; static int h, m; static int hh, mm; static long ans; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); t = Integer.parseInt(st.nextToken()); for (int tc = 0; tc < t; tc++) { st = new StringTokenizer(br.readLine()); h = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine(), ":"); hh = Integer.parseInt(st.nextToken()); mm = Integer.parseInt(st.nextToken()); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(0, 0); map.put(1, 1); map.put(2, 5); map.put(5, 2); map.put(8, 8); while (true) { int a = hh / 10; int b = hh % 10; int c = mm / 10; int d = mm % 10; if (map.containsKey(a) && map.containsKey(b) && map.containsKey(c) && map.containsKey(d)) { int rHH = map.get(d) * 10 + map.get(c); int rMM = map.get(b) * 10 + map.get(a); if (rHH < h && rMM < m) break; } mm++; if (mm >= m) { mm = 0; hh++; if (hh >= h) { hh = 0; } } } System.out.println(hh/10+""+hh%10 + ":" + mm/10+""+mm%10); } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
nums = {'0': '0', '1': '1', '2': '5', '5': '2', '8': '8'} def fmt_num(x): return str(x).rjust(2, '0') def is_valid(hh, mm, h, m): hh = fmt_num(hh) mm = fmt_num(mm) md = '' for d in (hh + mm)[::-1]: if d not in nums: return False md += nums[d] return 0 <= int(md[:2]) < h and 0 <= int(md[2:]) < m # if not all(c in nums for c in hh+mm): return False # hh, mm = int(nums[mm[1]]+nums[mm[0]]), int(nums[hh[1]]+nums[hh[0]]) # return 0 <= hh < h and 0 <= mm < m def solve(h, m, time): hh, mm = map(int, time.split(':')) while not is_valid(hh, mm, h, m): mm = (mm + 1) % m if mm == 0: hh = (hh + 1) % h return fmt_num(hh) + ':' + fmt_num(mm) for _ in xrange(int(raw_input())): h, m = map(int, raw_input().split()) time = raw_input().strip() print solve(h, m, time)
PYTHON
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int h = sc.nextInt(), m = sc.nextInt(); String s = sc.next(), ans = ""; int hour = (s.charAt(0) - 48) * 10 + s.charAt(1) - 48, minute = (s.charAt(3) - 48) * 10 + s.charAt(4) - 48; int hans = 0, mans = -1, flag = 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, 0); map.put(1, 1); map.put(2, 5); map.put(5, 2); map.put(8, 8); for (int i = hour; i < h; i++) { int temp; if (map.containsKey(i / 10) && map.containsKey(i % 10)) { temp = map.get(i / 10) + map.get(i % 10) * 10; if (temp < m) { hans = i; if (i != hour) mans = 0; flag = 1; break; } } } if (hans == 0 && flag == 0) mans = 0; if (mans != 0) { for (int i = minute; i < m; i++) { int temp; if (map.containsKey(i / 10) && map.containsKey(i % 10)) { temp = map.get(i / 10) + map.get(i % 10) * 10; if (temp < h) { mans = i; break; } } } if (mans == -1) { mans = 0; hans = 0; for (int i = hour + 1; i < h; i++) { int temp; if (map.containsKey(i / 10) && map.containsKey(i % 10)) { temp = map.get(i / 10) + map.get(i % 10) * 10; if (temp < m) { hans = i; break; } } } } } if (hans < 10) ans += "0"; ans += String.valueOf(hans); ans += ":"; if (mans < 10) ans += "0"; ans += String.valueOf(mans); System.out.println(ans); } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; public class B { static Scanner scan = new Scanner(System.in); public static void main(String[] args) { int t = scan.nextInt(); while(t != 0) { int mh = scan.nextInt(); int mm = scan.nextInt(); String[] arr = scan.next().split(":"); int h = Integer.parseInt(arr[0]); int m = Integer.parseInt(arr[1]); validTime(mh, mm, h, m); t--; } } private static void validTime(int mh, int mm, int nh, int nm) { while (nh != 0 || nm != 0) { if (isValid(mh, mm, nh, nm)) break; if (nm == mm - 1) nh = (nh + 1) % mh; nm = (nm + 1) % mm; } System.out.println((nh / 10) + "" + (nh % 10) + ":" + (nm / 10) + "" + (nm % 10)); } private static boolean isValid(int mh, int mm, int nh, int nm) { int[] mirror = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1}; if (mirror[nh / 10] == -1 || mirror[nh % 10] == -1 || mirror[nm / 10] == -1 || mirror[nm % 10] == -1) return false; int ih = mirror[nm % 10] * 10 + mirror[nm / 10]; int im = mirror[nh % 10] * 10 + mirror[nh / 10]; return ih < mh && im < mm; } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
a = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1] test = int(input()) def check(x, y, h, m): if a[x // 10] == -1 or a[x % 10] == -1 or a[y // 10] == -1 or a[y % 10] == -1 : return 0 if a[x % 10] * 10 + a[x // 10] >= m or a[y % 10] * 10 + a[y // 10] >= h : return 0 return 1 def pnt(x, y): res='' if x < 10 : res += '0' res += str(x) res += ':' if y < 10 : res += '0' res += str(y) print(res) return 0 for i in range(test): h, m = map(int, input().split(' ')) s = input() arr = s.split(':') x = int(arr[0]) y = int(arr[1]) while True: if check(x, y, h, m) == 1 : pnt(x, y) break else : y += 1 if y >= m : y -= m x += 1 if x >= h : x -= h
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
#------------------Important Modules------------------# from sys import stdin,stdout from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import * input=stdin.readline #prin=stdout.write from random import sample t=int(input()) #t=1 from collections import Counter,deque from math import sqrt,ceil,log2,gcd #dist=[0]*(n+1) class DisjSet: def __init__(self, n): # Constructor to create and # initialize sets of n items self.rank = [1] * n self.parent = [i for i in range(n)] # Finds set of given item x def find(self, x): # Finds the representative of the set # that x is an element of if (self.parent[x] != x): # if x is not the parent of itself # Then x is not the representative of # its set, self.parent[x] = self.find(self.parent[x]) # so we recursively call Find on its parent # and move i's node directly under the # representative of this set return self.parent[x] # Do union of two sets represented # by x and y. def union(self, x, y): # Find current sets of x and y xset = self.find(x) yset = self.find(y) # If they are already in same set if xset == yset: return # Put smaller ranked item under # bigger ranked item if ranks are # different if self.rank[xset] < self.rank[yset]: self.parent[xset] = yset elif self.rank[xset] > self.rank[yset]: self.parent[yset] = xset # If ranks are same, then move y under # x (doesn't matter which one goes where) # and increment rank of x's tree else: self.parent[yset] = xset self.rank[xset] = self.rank[xset] + 1 # Driver code def f(arr,i,j,d,dist): if i==j: return nn=max(arr[i:j]) for tl in range(i,j): if arr[tl]==nn: dist[tl]=d #print(tl,dist[tl]) f(arr,i,tl,d+1,dist) f(arr,tl+1,j,d+1,dist) #return dist def ps(n): cp=0 while n%2==0: n=n//2 cp+=1 for ps in range(3,ceil(sqrt(n))+1,2): while n%ps==0: n=n//ps cp+=1 if n!=1: return False return True #count=0 #dp=[[0 for i in range(m)] for j in range(n)] #[int(x) for x in input().strip().split()] def find_gcd(x, y): while(y): x, y = y, x % y return x # Driver Code def factorials(n,r): #This calculates ncr mod 10**9+7 slr=n;dpr=r qlr=1;qs=1 mod=10**9+7 for ip in range(n-r+1,n+1): qlr=(qlr*ip)%mod for ij in range(1,r+1): qs=(qs*ij)%mod #print(qlr,qs) ans=(qlr*modInverse(qs))%mod return ans def modInverse(b): qr=10**9+7 return pow(b, qr - 2,qr) tt=[xa**3 for xa in range(0,10**4+1)] qq=set(tt) def digits(k,rp): n=len(k) pq=k[::-1] jq='' for ij in pq: if ij=='1': jq+='1' elif ij=='2': jq+='5' elif ij=='4' or ij=='7' or ij=='3' or ij=='6' or ij=='9': jq+='-' elif ij=='5': jq+='2' elif ij=='8': jq+='8' elif ij=='0': jq+='0' if jq.find('-')!=-1: return -1 else: jl=int(jq) if jl>=rp: return -1 else: return jq def fr(a,b,h,m): kl=int(b) kl=(kl+1)%m b='0'*(2-len(str(kl)))+str(kl) if b=='0'*2: kj=(int(a)+1)%h a='0'*(2-len(str(kj)))+str(kj) return [a,b] for jj in range(t): #n=int(input()) h,m=[int(x) for x in input().strip().split()] #arr=[int(x) for x in input().strip().split()]; #brr=[int(x) for x in input().strip().split()];brr.sort() kq=input().strip() hrs=h;mins=m while True: if digits(kq[:2],m)!=-1 and digits(kq[3:],h)!=-1: print(kq) break #print(kq) klp=fr(kq[:2],kq[3:],h,m) kq=klp[0]+':'+klp[1]
PYTHON3
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; import java.io.*; public class B{ static class fastReader{ BufferedReader br; StringTokenizer st; public fastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } String Next(){ while(st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(Next()); } float nextFloat(){ return Float.parseFloat(Next()); } boolean nextBoolean(){ return Boolean.parseBoolean(Next()); } double nextDouble(){ return Double.parseDouble(Next()); } long nextLong(){ return Long.parseLong(Next()); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch(IOException e){ e.printStackTrace(); } return str; } String next(){ return Next(); } } static int int_max = Integer.MAX_VALUE; static int int_min = Integer.MIN_VALUE; private static final fastReader f = new fastReader(); private static final PrintWriter out = new PrintWriter(System.out); public static void print(Object o){out.print(o);} public static void println(Object o){out.println(o);} public static void println(){out.println();} public static<T extends Comparable<T>> T max(T a , T b){return a.compareTo(b) > 0 ? a : b;} public static<T extends Comparable<T>> T min(T a , T b){return a.compareTo(b) > 0 ? b : a;} public static void main(String[] args){ int t = f.nextInt(); while(t-- > 0){ solve(); } out.close(); } public static String good(int x){ String ans = "" + x; if(x < 10){ ans = "0"+ ans; } return ans; } public static int get(int x, HashMap<Integer, Integer> map){ String ans = ""; int val = x; while(val > 0){ int temp = val % 10; val /= 10; if(map.get(temp) == -1){ return int_max; } else{ ans += map.get(temp); } } if(ans.length() == 1) ans += "0"; if(ans.length() == 0) ans = "00"; return Integer.parseInt(ans); } public static void solve(){ int h = f.nextInt(); int m = f.nextInt(); String s = f.nextLine(); int hr = Integer.parseInt(s.substring(0, 2)); int min = Integer.parseInt(s.substring(3, 5)); HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, 0); map.put(1, 1); map.put(2, 5); map.put(3, -1); map.put(4, -1); map.put(5, 2); map.put(6, -1); map.put(7, -1); map.put(8, 8); map.put(9, -1); while(true){ if(min == m){ hr++; min = 0; } if(hr == h){ hr = 0; } // after reflection min becomes hour and hour becomes min if(get(min, map) < h && get(hr, map) < m){ println(good(hr) + ":" + good(min)); return; } min++; } } }
JAVA
1493_B. Planet Lapituletti
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from 0 to h-1 and minutes are numbered from 0 to m-1. <image> That's how the digits are displayed on the clock. Please note that digit 1 is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day). The image of the clocks in the mirror is reflected against a vertical axis. <image> The reflection is not a valid time. <image> The reflection is a valid time with h=24, m = 60. However, for example, if h=10, m=60, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment s and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid. It can be shown that with any h, m, s such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest. You are asked to solve the problem for several test cases. Input The first line contains a single integer T (1 ≤ T ≤ 100) — the number of test cases. The next 2 ⋅ T lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers h, m (1 ≤ h, m ≤ 100). The second line contains the start time s in the described format HH:MM. Output For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct. Example Input 5 24 60 12:21 24 60 23:59 90 80 52:26 1 100 00:01 10 10 04:04 Output 12:21 00:00 52:28 00:00 00:00 Note In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. <image>
2
8
import java.util.*; public class cp{ static int h=0,m=0,hh=0,mm=0; static boolean check(int nh,int nm,int[] pre) { if(pre[nh/10]==-1 || pre[nh%10]==-1 || pre[nm/10]==-1 || pre[nm%10]==-1) return false; int ih = pre[nm%10]*10+pre[nm/10]; int im = pre[nh%10]*10+pre[nh/10]; return ih < h && im < m; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int test = sc.nextInt(); while(test-- != 0) { h = sc.nextInt(); m = sc.nextInt(); String s = sc.next(); hh = Integer.parseInt(s.substring(0,2)); mm = Integer.parseInt(s.substring(3,5)); int nh = hh; int nm = mm; int[] pre = new int[10]; for(int i=0;i<10;i++) pre[i] = -1; pre[0] = 0; pre[1] = 1; pre[2] = 5; pre[5] = 2; pre[8] = 8; while(nh!=0 || nm!=0) { if(check(nh,nm,pre)) break; if(nm == m-1) nh = (nh+1)%h; nm = (nm+1)%m; } System.out.print(nh/10); System.out.print(nh%10); System.out.print(":"); System.out.print(nm/10); System.out.print(nm%10); System.out.println(); } } }
JAVA