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 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
allowed_digits = [0, 1, 2, 5, 8]
rev = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
T = int(input())
for _ in range(T):
h, m = map(int, input().split())
hh, mm = map(int, input().split(':'))
mins = hh * m + mm
day = h * m
dist = float('inf')
sol = ""
for h1 in allowed_digits:
for h2 in allowed_digits:
for m1 in allowed_digits:
for m2 in allowed_digits:
nm = m1 * 10 + m2
nh = h1 * 10 + h2
rm = rev[h2] * 10 + rev[h1]
rh = rev[m2] * 10 + rev[m1]
if nm < m and rm < m and nh < h and rh < h:
cmins = nh * m + nm
cdist = (cmins - mins) % day
if cdist < dist:
dist = cdist
sol = "%d%d:%d%d" % (h1, h2, m1, m2)
print(sol)
# region fastio
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
| 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 os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
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")
ALPHA = "abcdefghijklmnopqrstuvwxyz/"
M = 1000000007
EPS = 1e-6
def Ceil(a, b):
return a // b + int(a % b > 0)
def value():
return tuple(map(int, input().split()))
def array():
return [int(i) for i in input().split()]
def Int():
return int(input())
def Str():
return input()
def arrayS():
return [i for i in input().split()]
# -------------------------code---------------------------#
def change(s):
toret=""
for x in s:
if x=="2":
toret+="5"
elif x=="5":
toret+="2"
else:
toret+=x
return toret
def isvalid(s,h,m):
if "3" in s or "4" in s or "6" in s or "7" in s or "9" in s:
return False
else:
time,mnt=map(int,change(s[::-1]).split(":"))
if time<=h-1 and mnt<=m-1:
return True
for _ in range(int(input())):
h,m=map(int,input().split(" "))
hrs,mnt=map(int,input().split(":"))
totime=h*m+1
curtime=hrs*m+mnt
ans=str(hrs)+":"+str(mnt)
for x in range(totime+1):
curh=(curtime//m)%h
curm=curtime%m
scurh=str(curh)
scurm=str(curm)
if len(scurh)<2: scurh="0"+scurh
if len(scurm)<2: scurm="0"+scurm
if isvalid(scurh+":"+scurm,h,m)==True:
find=True
ans=str(scurh)+":"+str(scurm)
break
curtime+=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 | import java.io.*;
import java.util.*;
public class Main {
static int h;
static int m;
public static void main(String[] args) throws IOException {
// br = new BufferedReader(new FileReader(new File("input.txt")));
// out = new PrintWriter(new File("cutting.out"));
int jopa = nextInt();
for (int NASRSAL = 0; NASRSAL < jopa; NASRSAL++) {
h = nextInt();
m = nextInt();
char[] p = next().toCharArray();
int h_now = (p[0] - '0') * 10 + (p[1] - '0');
int m_now = (p[3] - '0') * 10 + (p[4] - '0');
for (int i = 0; i < 10000; i++) {
if (cor_h(h_now) && cor_min(m_now)) {
if (h_now < 10) out.print("0");
out.print(h_now);
out.print(":");
if (m_now < 10) out.print("0");
out.print(m_now);
out.println();
break;
} else {
m_now++;
if (m_now == m) {
m_now = 0;
h_now++;
if (h_now == h) h_now = 0;
}
}
}
}
out.close();
}
static boolean cor_min(int k) {
int a = (k % 10);
int b = k / 10;
if (!(a == 0 || a == 1 || a == 2 || a == 5 || a == 8) || !(b == 0 || b == 1 || b == 2 || b == 5 || b == 8))
return false;
int h_now = 0;
if (a == 2) h_now = 50;
else if (a == 5) h_now = 20;
else h_now = 10 * a;
if (b == 2) h_now += 5;
else if (b == 5) h_now += 2;
else h_now += b;
return h_now < h;
}
static boolean cor_h(int k) {
int a = (k % 10);
int b = k / 10;
if (!(a == 0 || a == 1 || a == 2 || a == 5 || a == 8) || !(b == 0 || b == 1 || b == 2 || b == 5 || b == 8))
return false;
int min_now = 0;
if (a == 2) min_now = 50;
else if (a == 5) min_now = 20;
else min_now = a * 10;
if (b == 2) min_now += 5;
else if (b == 5) min_now += 2;
else min_now += b;
return min_now < m;
}
public static StringTokenizer in = new StringTokenizer("");
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static PrintWriter out = new PrintWriter(System.out);
static String next() throws IOException {
while (!in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(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 | #include <bits/stdc++.h>
#include <unordered_set>
using namespace std;
///// Change default type here :D /////
typedef long long num;
//////////////////////////////
void PrintBool(bool a);
num a, b, c, d, e, f, g, h, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z;
// Does not contain i and j
string s1, s2, t1;
vector<num> nums;
num MirrorDigit(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;
}
}
num MirrorNumber(int number)
{
int first_digit = number % 10;
int second_digit = number / 10;
if (MirrorDigit(first_digit) == -1 || MirrorDigit(second_digit) == -1) return -1;
return MirrorDigit(first_digit) * 10 + MirrorDigit(second_digit);
}
void Solve()
{
cin >> h >> m;
cin >> a;
char c;
cin >> c;
cin >> b;
if (!(MirrorNumber(a) != -1 && MirrorNumber(a) < m)){
b = 0;
}
while (true){
if (MirrorNumber(b) != -1 && MirrorNumber(b) < h){
break;
}
b++;
if (b == m) {
b = 0;
a ++;
if (a == h) a = 0;
}
}
while (true){
if (MirrorNumber(a) != -1 && MirrorNumber(a) < m){
string str_b = to_string(b);
if (str_b.size() < 2) str_b = "0" + str_b;
string str_a = to_string(a);
if (str_a.size() < 2) str_a = "0" + str_a;
cout << str_a << ":" << str_b << endl;
return;
}
a++;
if (a == h) a = 0;
}
}
int main()
{
int query;
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// Comment out either of the two lines below
// depending on the problem type.
cin >> query; // Use when there are multiple test cases per test.
//query = 1; // Use when there are 1 test case per test.
while (query--)
{
Solve();
}
return 0;
}
void PrintBool(bool a)
{
string s = (a) ? "YES" : "NO";
cout << s << 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 |
//Bismillahir Rahmanir Raheem
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int>pii;
#define sf(x) scanf("%d",&x)
#define sfl(x) scanf("%lld",&x)
#define lli long long int
#define ll64 int64_t
#define pb push_back
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define frr(i,a) for(int i=0;i<a;i++)
#define frl(i,a) for(lli i=0;i<a;i++)
#define fr1(i,a) for(int i=1;i<=a;i++)
#define iter(x) x.begin(),x.end()
#define Memset(a,x,n) for(int i=0;i<n;i++)a[i]=x;
#define fi first
#define si second
typedef pair<lli,lli>pll;
lli h,m;
bool valid(lli a, lli b)
{
lli hh=0,mm=0;
lli ta=a,tb=b;
while(a)
{
int r=a%10,c;
c=r;
if(!(r==0 || r==1 || r==2 || r==5 || r==8))
{
return false;
}
if(r==2)
{
c=5;
}
else if(r==5)
{
c=2;
}
a/=10;
mm=mm*10+c;
}
if(ta/10==0)
{
mm*=10;
}
if(mm>=m)
{
return false;
}
while(b)
{
int r=b%10,c;
c=r;
if(!(r==0 || r==1 || r==2 || r==5 || r==8))
{
return false;
}
if(r==2)
{
c=5;
}
else if(r==5)
{
c=2;
}
b/=10;
hh=hh*10+c;
}
if(tb/10==0)
{
hh*=10;
}
if(hh>=h)
{
return false;
}
return true;
}
void solve()
{
cin>>h>>m;
vector<pll>v;
vector<lli>a;
for(int i=0;i<h;i++)
{
for(int j=0;j<m;j++)
{
if(valid(i,j))
{
//cout<<"i = "<<i<<" j = "<<j<<endl;
v.pb({i,j});
a.pb(i*m+j);
}
}
}
lli hh,mm;
string s;
cin>>s;
hh=(s[0]-'0')*10+(s[1]-'0');
mm=(s[3]-'0')*10+(s[4]-'0');
lli sum=hh*m+mm;
lli x=lower_bound(a.begin(),a.end(),sum)-a.begin();
if(x==a.size())
{
x=0;
}
printf("%02lld:%02lld\n",v[x].fi,v[x].si);
}
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 | import java.util.*;
import java.io.*;
public class EdB {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
public static void main(String[] omkar) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
int t = sc.nextInt();
for(int i = 0;i<t;i++){
// String input1 = bf.readLine().trim();
// String input2 = bf.readLine().trim();
// COMPARING INTEGER OBJECTS U DO DOT EQUALS NOT ==
int hs = sc.nextInt();
int ms = sc.nextInt();
String s = sc.next();
Time ts = new Time(hs, ms, Integer.parseInt(s.substring(0, 2)), Integer.parseInt(s.substring(3)));
while(!ts.isValid()){
ts.next();
}
out.print((ts.h/10)%10);
out.print(ts.h%10);
out.print(":");
out.print((ts.m/10)%10);
out.print(ts.m%10);
out.println();
// for(int j = 0;j<array.length;j++){
// out.print(array[j] + " ");
// }
// out.println();
}
out.close();
}
static class Time{
static int[] reflection = new int[]{0, 1, 5, -1, -1, 2, -1, -1, 8, -1};
static int hours;
static int minutes;
private int h;
private int m;
public Time(int hs, int ms, int h, int m){
hours = hs;
minutes = ms;
this.h = h;
this.m = m;
}
public void next(){
m++;
if (m == minutes){
m = 0;
h++;
if (h == hours){
h = 0;
}
}
}
public boolean isValid(){
int ones = m%10;
int twos = (m/10)%10;
int threes = h%10;
int fours = (h/10)%10;
boolean ans = true;
ans = ans && reflection[ones] != -1;
ans = ans && reflection[twos] != -1;
ans = ans && reflection[threes] != -1;
ans = ans && reflection[fours] != -1;
return ans && (reflection[ones]*10+reflection[twos] < hours && reflection[threes]*10+reflection[fours] < minutes);
}
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
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;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is | 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 collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat
import math
def inp(force_list=False):
re = map(int, raw_input().split())
if len(re) == 1 and not force_list:
return re[0]
return re
def inst():
return raw_input().strip()
def gcd(x, y):
while(y):
x, y = y, x % y
return x
mod = 1000000007
mp = {0:0, 1:1, 2:5, 3:-1, 4:-1, 5:2, 6:-1, 7:-1, 8:8, 9:-1}
def my_main():
kase = inp()
pans = []
for i in range(kase):
h, m = inp()
st = inst()
nh, nm = map(int, st.split(':'))
def pl(th, tm):
tm += 1
if tm == m:
tm = 0
th += 1
if th == h:
th = 0
return th, tm
def va(th, tm):
x, y = mp[th/10], mp[th%10]
if x==-1 or y == -1:
return 0
if x+y*10 >= m:
return 0
x, y = mp[tm/10], mp[tm%10]
if x==-1 or y == -1:
return 0
if x+y*10 >= h:
return 0
return 1
while True:
if va(nh, nm):
print "%02d:%02d" % (nh, nm)
break
nh, nm = pl(nh, nm)
# print '\n'.join(pans)
# print int('101010', 2), int('11011', 2)
my_main()
| 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 | # include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
using namespace std;
int rc(char c) {
switch(c) {
case '0': return 0;
case '1': return 1;
case '2': return 5;
case '5': return 2;
case '8': return 8;
}
return -1;
}
int helper(int tm, int lmt, int x) {
int d, result = 0;
d = (x == 0)? 0 : tm - x;
int td, temp, a, b;;
string s;
bool good;
for (int i = 0; i < tm; i++) {
td = 0;
if (i < x) {
td = tm - x + i;
} else if (i > x) {
td = i - x;
}
s = to_string(i);
good = true;
for (int j = 0; j < s.size(); j++) {
if (rc(s[j]) == -1) {
good = false;
break;
}
}
if (!good) continue;
if (s.size() == 1) s = "0" + s;
a = rc(s[1]);
b = rc(s[0]);
temp = (a * 10) + b;
if ((temp < lmt) and (td < d)) {
d = td;
result = i;
}
}
return result;
}
int main() {
int tc;
cin >> tc;
while(tc--) {
int h, m;
cin >> h >> m;
string s;
cin >> s;
int ch, cm;
ch = (int) (s[0] - '0') * 10;
ch += (int) (s[1] - '0');
cm = (int) (s[3] - '0') * 10;
cm += (int) (s[4] - '0');
int nm, nh;
nm = helper(m, h, cm);
if (nm < cm) {
ch++;
cm = 0;
nh = helper(h, m, ch);
nm = helper(m, h, 0);
} else {
nh = helper(h, m, ch);
if (nh != ch) {
nm = helper(m, h, 0);
}
}
if (nh < 10) cout << '0';
cout << nh << ':';
if (nm < 10) cout << '0';
cout << nm << '\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 |
# Author : raj1307 - Raj Singh
# Date : 06.03.2021
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def msi(): return map(str,input().strip().split(" "))
def li(): return list(mi())
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import log,sqrt,factorial,cos,tan,sin,radians
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *
#import threading
#from itertools import permutations
#Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy
abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[1]
def sort2(l):return sorted(l, key=getKey,reverse=True)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def ceil(x,y):
if x%y==0:
return x//y
else:
return x//y+1
def powerMod(x,y,p):
res = 1
x %= p
while y > 0:
if y&1:
res = (res*x)%p
y = y>>1
x = (x*x)%p
return res
def gcd(x, y):
while y:
x, y = y, x % y
return x
def isPrime(n) : # Check Prime Number or not
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def check(x):
if x in [0,1,2,5,8]:
return 1
return 0
def ans(x,y):
x1=''
x2=''
if len(str(x))==1:
x1='0'+str(x)
else:
x1=str(x)
if len(str(y))==1:
x2='0'+str(y)
else:
x2=str(y)
print(x1+':'+x2)
def main():
for _ in range(ii()):
h,m=mi()
s=si()
x=int(s[0]+s[1])
y=int(s[3]+s[4])
f=[0,1,2,5,8]
p=-1
q=-1
a=x
b=y
for j in range(y,m):
x1=a//10
x2=a%10
num1=0
if x2==2:
x2=5
elif x2==5:
x2=2
if x1==2:
x1=5
elif x1==5:
x1=2
num1=x2*10+x1
y1=b//10
y2=b%10
num2=0
if y2==2:
y2=5
elif y2==5:
y2=2
if y1==2:
y1=5
elif y1==5:
y1=2
num2=y2*10+y1
#print(a,b,num1,num2)
if check(y1) and check(y2) and check(x1) and check(x2):
pass
else:
b+=1
continue
if num1<m and num2<h:
p=a
q=b
break
b+=1
if p!=-1:
#print(str(p)+':'+str(q))
ans(p,q)
continue
a+=1
b=0
for i in range(x+1,h):
b=0
for j in range(0,m):
#print(a,b)
x1=a//10
x2=a%10
num1=0
if x2==2:
x2=5
elif x2==5:
x2=2
if x1==2:
x1=5
elif x1==5:
x1=2
num1=x2*10+x1
y1=b//10
y2=b%10
num2=0
if y2==2:
y2=5
elif y2==5:
y2=2
if y1==2:
y1=5
elif y1==5:
y1=2
num2=y2*10+y1
#print(num1,num2)
#print(num2,num1)
if check(y1) and check(y2) and check(x1) and check(x2):
pass
else:
b+=1
continue
#print(num2,num1)
if num1<m and num2<h:
p=a
q=b
break
b+=1
a+=1
if p!=-1:
break
if p!=-1:
#print(str(p)+':'+str(q))
ans(p,q)
continue
a=0
b=0
for i in range(h):
b=0
for j in range(m):
x1=a//10
x2=a%10
num1=0
if x2==2:
x2=5
elif x2==5:
x2=2
if x1==2:
x1=5
elif x1==5:
x1=2
num1=x2*10+x1
y1=b//10
y2=b%10
num2=0
if y2==2:
y2=5
elif y2==5:
y2=2
if y1==2:
y1=5
elif y1==5:
y1=2
num2=y2*10+y1
if check(y1) and check(y2) and check(x1) and check(x2):
pass
else:
b+=1
continue
if num1<m and num2<h:
p=a
q=b
break
b+=1
a+=1
if p!=-1:
break
if p!=-1:
#print(str(p)+':'+str(q))
ans(p,q)
continue
a=h
b=0
for j in range(m):
x1=a//10
x2=a%10
num1=0
if x2==2:
x2=5
elif x2==5:
x2=2
if x1==2:
x1=5
elif x1==5:
x1=2
num1=x2*10+x1
y1=b//10
y2=b%10
num2=0
if y2==2:
y2=5
elif y2==5:
y2=2
if y1==2:
y1=5
elif y1==5:
y1=2
num2=y2*10+y1
if check(y1) and check(y2) and check(x1) and check(x2):
pass
else:
b+=1
continue
if num1<m and num2<h:
p=a
q=b
break
b+=1
if p!=-1:
#print(str(p)+':'+str(q))
ans(p,q)
continue
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
#dmain()
# Comment Read()
| 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 solutioncode {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int testcases=s.nextInt();
while(testcases>0) {
int h=s.nextInt();
int m=s.nextInt();
String ss=s.next();
int hh=(ss.charAt(0)-'0')*10 + ss.charAt(1)-'0';
int mm=(ss.charAt(3)-'0')*10 + ss.charAt(4)-'0';
while(true) {
int m1=hh%10;
int m2=(hh-m1)/10;
int h1=mm%10;
int h2=(mm-h1)/10;
if((m1==0 || m1==1 || m1==2 || m1==5 || m1==8) && (m2==0 || m2==1 || m2==2 || m2==5 || m2==8) && (h1==0 || h1==1 || h1==2 || h1==5 || h1==8) && (h2==0 || h2==1 || h2==2 || h2==5 || h2==8)) {
if(m1==2)
m1=5;
else if(m1==5)
m1=2;
if(m2==2)
m2=5;
else if(m2==5)
m2=2;
if(h1==2)
h1=5;
else if(h1==5)
h1=2;
if(h2==2)
h2=5;
else if(h2==5)
h2=2;
if(h1*10 + h2 <h && m1*10 + m2<m) {
if(m1==2)
m1=5;
else if(m1==5)
m1=2;
if(m2==2)
m2=5;
else if(m2==5)
m2=2;
if(h1==2)
h1=5;
else if(h1==5)
h1=2;
if(h2==2)
h2=5;
else if(h2==5)
h2=2;
System.out.println(m2 +""+ m1 + ":" +h2 + h1);
break;
}
}
mm=(mm+1)%m;
if(mm==0)
hh=(hh+1)%h;
}
testcases--;
}
}
}
| 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 time,math as mt,bisect as bs,sys
from sys import stdin,stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
from collections import defaultdict
pi=3.14159265358979323846264338327950
def II(): # to take integer input
return int(stdin.readline())
def IP(): # to take tuple as input
return map(int,stdin.readline().split())
def L(): # to take list as input
return list(map(int,stdin.readline().split()))
def P(x): # to print integer,list,string etc..
return stdout.write(str(x)+"\n")
def PI(x,y): # to print tuple separatedly
return stdout.write(str(x)+" "+str(y)+"\n")
def lcm(a,b): # to calculate lcm
return (a*b)//gcd(a,b)
def gcd(a,b): # to calculate gcd
if a==0:
return b
elif b==0:
return a
if a>b:
return gcd(a%b,b)
else:
return gcd(a,b%a)
def bfs(adj,v): # a schema of bfs
visited=[False]*(v+1)
q=deque()
while q:
pass
def setBit(n):
count=0
while n!=0:
n=n&(n-1)
count+=1
return count
mx=10**7
spf=[mx]*(mx+1)
def readTree(n,e): # to read tree
adj=[set() for i in range(n+1)]
for i in range(e):
u1,u2=IP()
adj[u1].add(u2)
return adj
def sieve():
li=[True]*(10**3+5)
li[0],li[1]=False,False
for i in range(2,len(li),1):
if li[i]==True:
for j in range(i*i,len(li),i):
li[j]=False
prime,cur=[0]*200,0
for i in range(10**3+5):
if li[i]==True:
prime[cur]=i
cur+=1
return prime
def SPF():
mx=(10**6+1)
spf[1]=1
for i in range(2,mx):
if spf[i]==1e9:
spf[i]=i
for j in range(i*i,mx,i):
if i<spf[j]:
spf[j]=i
return
def prime(n,d):
prm=set()
while n!=1:
prm.add(spf[n])
n=n//spf[n]
for ele in prm:
d[ele]=d.get(ele,0)+1
return
#####################################################################################
mod=10**9+7
inf = 10000000000000000
def check(s):
stack=[]
for ele in s:
if ele==")" and not(stack):
return 0
elif ele==")":
stack.pop()
if ele=="(":
stack.append("(")
if stack:
return 0
return 1
def getans(h,m):
if len(h)==1:
h='0'+h
if len(m)==1:
m='0'+m
ans=h+":"+m
return ans,h,m
def check(h,m):
for ele in h:
if ele not in '01258':
return False
for ele in m:
if ele not in '01258':
return False
return True
def check2(hh,mm,h,m):
hh=hh[::-1]
mm=mm[::-1]
newh,newm="",""
for ele in mm:
if ele=='2':
newh+='5'
elif ele=='5':
newh+='2'
else:
newh+=ele
for ele in hh:
if ele=='2':
newm+='5'
elif ele=='5':
newm+='2'
else:
newm+=ele
newh,newm=int(newh),int(newm)
# print(hh,mm,newh,newm)
if newh>=0 and newh<h and newm>=0 and newm<m:
return True
return False
def solve():
h,m=IP()
s=stdin.readline()
hh=int(s[:2])
mm=int(s[3:5])
# print(h,m)
# print(s)
while True:
# print(hh,mm)
if check(str(hh),str(mm)):
ans,rh,rm=getans(str(hh),str(mm))
if check2(str(rh),str(rm),h,m):
print(ans)
return
if mm==m-1:
mm=0
if hh==h-1:
hh=0
else:
hh+=1
else:
mm+=1
return
t=II()
for i in range(t):
solve()
#######
#
#
####### # # # #### # # #
# # # # # # # # # # #
# #### # # #### #### # #
###### # # #### # # # # #
# ``````¶0````1¶1_```````````````````````````````````````
# ```````¶¶¶0_`_¶¶¶0011100¶¶¶¶¶¶¶001_````````````````````
# ````````¶¶¶¶¶00¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶0_````````````````
# `````1_``¶¶00¶0000000000000000000000¶¶¶¶0_`````````````
# `````_¶¶_`0¶000000000000000000000000000¶¶¶¶¶1``````````
# ```````¶¶¶00¶00000000000000000000000000000¶¶¶_`````````
# ````````_¶¶00000000000000000000¶¶00000000000¶¶`````````
# `````_0011¶¶¶¶¶000000000000¶¶00¶¶0¶¶00000000¶¶_````````
# ```````_¶¶¶¶¶¶¶00000000000¶¶¶¶0¶¶¶¶¶00000000¶¶1````````
# ``````````1¶¶¶¶¶000000¶¶0¶¶¶¶¶¶¶¶¶¶¶¶0000000¶¶¶````````
# ```````````¶¶¶0¶000¶00¶0¶¶`_____`__1¶0¶¶00¶00¶¶````````
# ```````````¶¶¶¶¶00¶00¶10¶0``_1111_`_¶¶0000¶0¶¶¶````````
# ``````````1¶¶¶¶¶00¶0¶¶_¶¶1`_¶_1_0_`1¶¶_0¶0¶¶0¶¶````````
# ````````1¶¶¶¶¶¶¶0¶¶0¶0_0¶``100111``_¶1_0¶0¶¶_1¶````````
# ```````1¶¶¶¶00¶¶¶¶¶¶¶010¶``1111111_0¶11¶¶¶¶¶_10````````
# ```````0¶¶¶¶__10¶¶¶¶¶100¶¶¶0111110¶¶¶1__¶¶¶¶`__````````
# ```````¶¶¶¶0`__0¶¶0¶¶_¶¶¶_11````_0¶¶0`_1¶¶¶¶```````````
# ```````¶¶¶00`__0¶¶_00`_0_``````````1_``¶0¶¶_```````````
# ``````1¶1``¶¶``1¶¶_11``````````````````¶`¶¶````````````
# ``````1_``¶0_¶1`0¶_`_``````````_``````1_`¶1````````````
# ``````````_`1¶00¶¶_````_````__`1`````__`_¶`````````````
# ````````````¶1`0¶¶_`````````_11_`````_``_``````````````
# `````````¶¶¶¶000¶¶_1```````_____```_1``````````````````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶0_``````_````_1111__``````````````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶01_`````_11____1111_```````````
# `````````¶¶0¶0¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶1101_______11¶_```````````
# ``````_¶¶¶0000000¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶0¶0¶¶¶1````````````
# `````0¶¶0000000¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶1`````````````
# ````0¶0000000¶¶0_````_011_10¶110¶01_1¶¶¶0````_100¶001_`
# ```1¶0000000¶0_``__`````````_`````````0¶_``_00¶¶010¶001
# ```¶¶00000¶¶1``_01``_11____``1_``_`````¶¶0100¶1```_00¶1
# ``1¶¶00000¶_``_¶_`_101_``_`__````__````_0000001100¶¶¶0`
# ``¶¶¶0000¶1_`_¶``__0_``````_1````_1_````1¶¶¶0¶¶¶¶¶¶0```
# `_¶¶¶¶00¶0___01_10¶_``__````1`````11___`1¶¶¶01_````````
# `1¶¶¶¶¶0¶0`__01¶¶¶0````1_```11``___1_1__11¶000`````````
# `1¶¶¶¶¶¶¶1_1_01__`01```_1```_1__1_11___1_``00¶1````````
# ``¶¶¶¶¶¶¶0`__10__000````1____1____1___1_```10¶0_```````
# ``0¶¶¶¶¶¶¶1___0000000```11___1__`_0111_```000¶01```````
# ```¶¶¶00000¶¶¶¶¶¶¶¶¶01___1___00_1¶¶¶`_``1¶¶10¶¶0```````
# ```1010000¶000¶¶0100_11__1011000¶¶0¶1_10¶¶¶_0¶¶00``````
# 10¶000000000¶0________0¶000000¶¶0000¶¶¶¶000_0¶0¶00`````
# ¶¶¶¶¶¶0000¶¶¶¶_`___`_0¶¶¶¶¶¶¶00000000000000_0¶00¶01````
# ¶¶¶¶¶0¶¶¶¶¶¶¶¶¶_``_1¶¶¶00000000000000000000_0¶000¶01```
# 1__```1¶¶¶¶¶¶¶¶¶00¶¶¶¶00000000000000000000¶_0¶0000¶0_``
# ```````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶00000000000000000000010¶00000¶¶_`
# ```````0¶¶¶¶¶¶¶¶¶¶¶¶¶¶00000000000000000000¶10¶¶0¶¶¶¶¶0`
# ````````¶¶¶¶¶¶¶¶¶¶0¶¶¶00000000000000000000010¶¶¶0011```
# ````````1¶¶¶¶¶¶¶¶¶¶0¶¶¶0000000000000000000¶100__1_`````
# `````````¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶000000000000000000¶11``_1``````
# `````````1¶¶¶¶¶¶¶¶¶¶¶0¶¶¶00000000000000000¶11___1_`````
# ``````````¶¶¶¶¶¶0¶0¶¶¶¶¶¶¶0000000000000000¶11__``1_````
# ``````````¶¶¶¶¶¶¶0¶¶¶0¶¶¶¶¶000000000000000¶1__````__```
# ``````````¶¶¶¶¶¶¶¶0¶¶¶¶¶¶¶¶¶0000000000000000__`````11``
# `````````_¶¶¶¶¶¶¶¶¶000¶¶¶¶¶¶¶¶000000000000011_``_1¶¶¶0`
# `````````_¶¶¶¶¶¶0¶¶000000¶¶¶¶¶¶¶000000000000100¶¶¶¶0_`_
# `````````1¶¶¶¶¶0¶¶¶000000000¶¶¶¶¶¶000000000¶00¶¶01`````
# `````````¶¶¶¶¶0¶0¶¶¶0000000000000¶0¶00000000011_``````_
# ````````1¶¶0¶¶¶0¶¶¶¶¶¶¶000000000000000000000¶11___11111
# ````````¶¶¶¶0¶¶¶¶¶00¶¶¶¶¶¶000000000000000000¶011111111_
# ```````_¶¶¶¶¶¶¶¶¶0000000¶0¶00000000000000000¶01_1111111
# ```````0¶¶¶¶¶¶¶¶¶000000000000000000000000000¶01___`````
# ```````¶¶¶¶¶¶0¶¶¶000000000000000000000000000¶01___1````
# ``````_¶¶¶¶¶¶¶¶¶00000000000000000000000000000011_111```
# ``````0¶¶0¶¶¶0¶¶0000000000000000000000000000¶01`1_11_``
# ``````¶¶¶¶¶¶0¶¶¶0000000000000000000000000000001`_0_11_`
# ``````¶¶¶¶¶¶¶¶¶00000000000000000000000000000¶01``_0_11`
# ``````¶¶¶¶0¶¶¶¶00000000000000000000000000000001```_1_11
| 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 | mir = [-1] * 10
mir[0] = 0
mir[1] = 1
mir[2] = 5
mir[5] = 2
mir[8] = 8
for i in range(int(input())):
h, m = map(int, input().split())
hh, mm = map(int, input().split(':'))
while True:
hs = (hh // 10, hh % 10)
ms = (mm // 10, mm % 10)
m_ = (mir[hs[1]], mir[hs[0]])
h_ = (mir[ms[1]], mir[ms[0]])
if (-1 not in m_) and (-1 not in h_) \
and h_[0] * 10 + h_[1] < h and m_[0] * 10 + m_[1] < m:
print(*hs, ':', *ms, sep='')
break
mm += 1
if mm == m:
mm = 0
hh += 1
if hh == h:
hh = 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 | q = [-1 for i in range(10)]
q[0] = 0
q[1] = 1
q[2] = 5
q[5] = 2
q[8] = 8
def get_reflected(h,m):
nh = int(str(q[m%10]) + str(q[m/10]))
nm = int(str(q[h%10]) + str(q[h/10]))
return [nh,nm]
def is_ref_exist(h,m):
for i in str(h):
if(q[int(i)]==-1):
return False
for i in str(m):
if(q[int(i)]==-1):
return False
return True
def get_ans(h,m):
res = str(m%10) + str(m/10) + ':' + str(h%10) + str(h/10)
return res[::-1]
for _ in range(input()):
h,m = map(int,raw_input().split())
u,v = map(int,raw_input().split(':'))
ans = ''
for i in range(u,h):
sm = 0
if i==u:
sm = v
for j in range(sm,m):
if is_ref_exist(i,j):
ref = get_reflected(i,j)
nh,nm = ref[0],ref[1]
if nh<h and nm<m:
ans = get_ans(i,j)
break
if len(ans):
break
if len(ans)==0:
for i in range(0,u+1):
em = m
if i==u:
em = v
for j in range(0,em):
if is_ref_exist(i,j):
ref = get_reflected(i,j)
nh,nm = ref[0],ref[1]
if nh<h and nm<m:
ans = get_ans(i,j)
break
if len(ans):
break
print ans
| 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.io.*;
import java.lang.*;
public class ProblemD {
static boolean arr[]={true, true,true,false,false,true,false,false,true,false};
static int image[]={0,1,5,-1,-1,2,-1,-1,8,-1};
static int h,m;
public static void main(String[] args) {
MyScanner scan = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t=scan.nextInt();
while(t-->0){
h=scan.nextInt();
m=scan.nextInt();
String s=scan.nextLine();
char ar[]=s.toCharArray();
int a= (ar[0]-'0')*10 + (ar[1]-'0');
int b= (ar[3]-'0')*10 + (ar[4]-'0');
// int a= Integer.parseInt(s.substring(0, 2));
// int b=Integer.parseInt(s.substring(3, 5));
while(!check(a,b)){
b++;
if(b>=m) a++;
b%=m;
a%=h;
}
if(a<10)
System.out.print("0"+a+":");
else System.out.print(a+":");
if(b<10)
System.out.print("0"+b);
else System.out.print(b);
System.out.println();
}
out.close();
}
static boolean check(int a,int b){
if(!arr[a%10] || !arr[a/10] || !arr[b%10] || !arr[b/10]) {
return false;
}
else{
String hh=Integer.toString(a);
String mm=Integer.toString(b);
if(hh.length()==1) hh="0"+hh;
if(mm.length()==1) mm="0"+mm;
int im= image[Character.getNumericValue(hh.charAt(1))]*10 + image[Character.getNumericValue(hh.charAt(0))];
int ih=(image[Character.getNumericValue(mm.charAt(1))])*10 + image[Character.getNumericValue(mm.charAt(0))];
if(im<m && ih<h) return true;
else return false;
}
}
}
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 <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
long long tt;
cin >> tt;
vector<long long> mmm(10);
mmm[0] = 0;
mmm[1] = 1;
mmm[2] = 5;
mmm[3] = -1;
mmm[4] = -1;
mmm[5] = 2;
mmm[6] = -1;
mmm[7] = -1;
mmm[8] = 8;
mmm[9] = -1;
auto Check = [&](long long x) {
return (mmm[x/10] != -1 && mmm[x%10] != -1);
};
while (tt--) {
long long h, m;
string s;
cin >> h >> m >> s;
// s HH:MM
long long hh = 10*(s[0] - '0') + (s[1] - '0');
long long mm = 10*(s[3] - '0') + (s[4] - '0');
auto Cost = [&](long long xx, long long yy) { // xx:yy is after hh:mm
long long cost = 0;
if (xx == hh) {
if (yy >= mm) {
cost = yy - mm;
} else {
cost = h*m + yy - mm;
}
}
if (xx > hh) {
cost = (xx - hh)*m + yy-mm;
}
if (xx < hh) {
cost = ((xx+h-hh)%h)*m + yy-mm;
}
return cost;
};
long long ans = 1e9;
long long ans_hh = 0, ans_mm = 0;
for (long long i = 0; i < h; i++) {
for (long long j = 0; j < m; j++) {
if (Check(i) && Check(j)) {
long long ir = 10*(mmm[i%10]) + mmm[i/10];
long long jr = 10*(mmm[j%10]) + mmm[j/10];
if (ir >= m || jr >= h) continue;
long long cost = Cost(i, j);
if (cost < ans) {
ans_hh = i;
ans_mm = j;
ans = cost;
}
}
}
}
cout << (ans_hh < 10 ? "0" : "");
cout << ans_hh << ":";
cout << (ans_mm < 10 ? "0" : "");
cout << ans_mm << "\n";
}
return 0;
}
// go through problem examples
// for A, B: local structure, brute force
// sums, multiplication -> long long
// lcm, gcd -> prime factorization -> first figure for one factor
// expectation, count -> sumation order
// max -> greedy, binsearch, dp
// bit operations -> figure of single bits
| 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 <algorithm>
#include <cmath>
#include <queue>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <tuple>
#include <deque>
#include <array>
#include <numeric>
#include <bitset>
#include <iomanip>
#include <cassert>
#include <chrono>
#include <random>
#include <limits>
#include <iterator>
#include <functional>
#include <sstream>
#include <fstream>
#include <complex>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
using namespace std;
using ll = long long;
constexpr int INF = 1001001001;
constexpr int mod = 1000000007;
// constexpr int mod = 998244353;
template<class T>
inline bool chmax(T& x, T y){
if(x < y){
x = y;
return true;
}
return false;
}
template<class T>
inline bool chmin(T& x, T y){
if(x > y){
x = y;
return true;
}
return false;
}
bool ok[10];
int convert[10];
void solve(){
int h, m;
string s;
cin >> h >> m >> s;
int H = stoi(s.substr(0, 2)), M = stoi(s.substr(3, 2));
for(;;){
bool flag = true;
int H2 = 0, M2 = 0;
int x = H;
vector<int> a(2);
int k = 0;
while(x > 0){
flag &= ok[x % 10];
a[k++] = x % 10;
x /= 10;
}
M2 = convert[a[0]] * 10 + convert[a[1]];
flag &= (M2 < m);
a[0] = a[1] = 0;
x = M;
k = 0;
while(x > 0){
flag &= ok[x % 10];
a[k++] = x % 10;
x /= 10;
}
H2 = convert[a[0]] * 10 + convert[a[1]];
flag &= (H2 < h);
if(flag){
cout << setfill('0') << right << setw(2) << H << ':';
cout << setfill('0') << right << setw(2) << M << '\n';
return;
}
if(++M == m){
M = 0;
if(++H == h){
H = 0;
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
ok[0] = true;
ok[1] = true; convert[1] = 1;
ok[2] = true; convert[2] = 5;
ok[5] = true; convert[5] = 2;
ok[8] = true; convert[8] = 8;
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 <bits/stdc++.h>
using namespace std;
#define DIM 1000007
long long t, h, m, hh, mm, res, v;
string s;
bool cor(long long h1, long long m1){
swap(h1, m1);
long long hh1, hh2, mm1, mm2;
hh2 = h1/10;
hh1 = h1%10;
mm2 = m1/10;
mm1 = m1%10;
if(hh2==3 || hh2==4 || hh2==6 || hh2==7 || hh2==9 ) return false;
if(hh1==3 || hh1==4 || hh1==6 || hh1==7 || hh1==9 ) return false;
if( mm2==3 || mm2==4 || mm2==6 || mm2==7 || mm2==9 ) return false;
if( mm1==3 || mm1==4 || mm1==6 || mm1==7 || mm1==9) return false;
if(hh2==5) hh2=2;
else if(hh2==2) hh2=5;
if(hh1==5) hh1=2;
else if(hh1==2) hh1=5;
if(mm2==5) mm2=2;
else if(mm2==2) mm2=5;
if(mm1==5) mm1=2;
else if(mm1==2) mm1=5;
h1 = hh1*10+hh2;
m1 = mm1*10+mm2;
if(h1>=h || m1>=m) return false;
return true;
}
int main()
{
cin>>t;
for(int y=1;y<=t;y++){
cin>>h>>m>>s;
hh = (s[0]-'0')*10+(s[1]-'0');
mm = (s[3]-'0')*10+(s[4]-'0');
res=0;
while(!cor(hh, mm)){
mm++;
if(mm>=m){
mm=0;
hh++;
}
if(hh>=h){
res=-1;
break;
}
}
if(res==-1){
cout<<"00:00"<<endl;
}
else{
if(hh<10) cout<<0;
cout<<hh<<':';
if(mm<10) cout<<0;
cout<<mm<<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 | import sys
import os.path
from collections import *
import math
import bisect
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
else:
input = sys.stdin.readline
############## Code starts here ##########################
t = int(input())
nums = Counter({0:0,1:10,2:50,5:20,8:80,
10:1,11:11,12:51,15:21,18:81,
20:5,21:15,22:55,25:25,28:85,
50:2,51:12,52:52,55:22,58:82,
80:8,81:18,82:58,85:28,88:88})
mirror = {1: 1, 0: 0, 2: 5, 5: 2, 8: 8}
while t:
t-=1
hrs,mins = [int(x) for x in input().split()]
s = input().rstrip('\n')
h = int(s[0:2])
m = int(s[3:])
if m:
while m<mins:
if nums[m] and nums[m]<hrs:
break
m+=1
if m == mins:
m = 0
h = (1 + h) % hrs
if h:
while h<hrs:
if nums[h] and nums[h]<mins:
break
h+=1
m = 0
if h==hrs:
h = 0
a = h%10
h//=10
b = h%10
c = m%10
m//=10
d = m%10
print(b,a,":",d,c,sep="")
############## Code ends here ############################
| 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 func(s,n):
l={1:1,2:5,5:2,0:0,8:8}
s1=s%10
s2=s//10
if s1 in l:
s1=l[s1]
else:
return 0
if s2 in l:
s2=l[s2]
else:
return 0
rs=s1*10+s2
if rs<n:
return 1
else:
return 0
for _ in range(int(input())):
n,k=map(int,input().split())
s=input()
ans=0
h=int(s[0:2])
m=int(s[3:5])
while(1):
if func(h,k) and func(m,n):
break
m+=1
if m==k:
m=0
h+=1
if h==n:
h=0
print("{:02d}:{:02d}".format(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 mirror(h, m):
sh = list(str(h).zfill(2))
sm = list(str(m).zfill(2))
if set(['3', '4', '6', '7', '9']) & set(sh + sm):
return False
m = { '0': '0', '1': '1', '2': '5', '5': '2', '8': '8' }
return (int(m[sm[1]] + m[sm[0]]), int(m[sh[1]] + m[sh[0]]))
def tick(h, m, H, M):
m += 1
if m == M:
m = 0
h += 1
if h == H:
h = 0
return (h, m)
def solve():
H, M = map(int, input().split())
h, m = map(int, input().split(':'))
while True:
r = mirror(h, m)
if r:
mh, mm = r
if mh < H and mm < M:
print(str(h).zfill(2) + ':' + str(m).zfill(2))
break
h, m = tick(h, m, H, M)
t = int(input())
while t > 0:
solve()
t -= 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 | #include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>
using namespace std;
int H, M;
bool mirror(int h, int m) {
string sh = to_string(h);
string sm = to_string(m);
if (h < 10)
sh = "0" + sh;
if (m < 10)
sm = "0" + sm;
reverse(sh.begin(), sh.end());
reverse(sm.begin(), sm.end());
for (int i = 0; i < sh.size(); i++) {
switch (sh[i]) {
case '0': break;
case '1': break;
case '2': sh[i] = '5'; break;
case '5': sh[i] = '2'; break;
case '8': break;
default: return false;
}
}
for (int i = 0; i < sh.size(); i++) {
switch (sm[i]) {
case '0': break;
case '1': break;
case '2': sm[i] = '5'; break;
case '5': sm[i] = '2'; break;
case '8': break;
default: return false;
}
}
h = stoi(sm);
m = stoi(sh);
if (h < H && m < M)
return true;
else
return false;
}
int main() {
int T, h, m;
string sh, sm;
cin >> T;
while (T--) {
cin >> H >> M;
getline(cin, sh, ':');
getline(cin, sm);
bool done = false;
for (h = stoi(sh); h < H && !done; h++)
for (m = (h == stoi(sh)) ? stoi(sm) : 0 ; m < M && !done; m++)
if (mirror(h, m)) {
done = true;
sh = to_string(h);
sm = to_string(m);
if (h < 10)
sh = "0" + sh;
if (m < 10)
sm = "0" + sm;
}
if (!done) {
sh = "00";
sm = "00";
}
cout << sh << ":" << sm << 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 vi vector<int>
#define ii pair<int,int>
#define vii vector<ii>
#define si set<int>
#define msi map<string,int>
#define sp " "
const int inf = 2e9;
const int MX = 30;
const int mod = 1e9+7;
int arr[10]={0,1,5,-1,-1,2,-1,-1,8,-1};
int h,m;
string s;
bool checkTime(int hh,int mm){
int nh=0,nm=0;
if(arr[mm/10]==-1||arr[mm%10]==-1||arr[hh/10]==-1||arr[hh%10]==-1) return false;
nh=arr[mm%10]*10+arr[mm/10];
nm=arr[hh%10]*10+arr[hh/10];
if(nh<h&&nm<m)return true;
else return false;
}
int main(){
int tc;cin>>tc;
for(int ntc=1;ntc<=tc;ntc++){
cin>>h>>m;
cin>>s;
int hh=0,mm=0,i=0;
while(s[i]!=':'){
hh=hh*10+(s[i]-'0');
i++;
}i++;
while(i<s.size()){
mm=mm*10+(s[i]-'0');
i++;
}
while(checkTime(hh,mm)==false){
mm++;
if(mm==m){
hh++;
mm=0;
}
if(hh==h){
hh=0;
}
}
if(hh<10)cout<<0;
cout<<hh<<":";
if(mm<10)cout<<0;
cout<<mm<<"\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 | #include <bits/stdc++.h>
typedef long long ll;
#define f(i,a,n) for(long long i=a;i<n;i++)
using namespace std;
int MM[10]={1,1,1,0,0,1,0,0,1,0};
bool mirror(string s)
{
for(int i=0;i<2;i++)
{ if(MM[s[i]-'0']==0)
return false;
}
return true;
}
bool valid(string s,ll mirrorlimit,ll selflimit)
{ string p=s;
reverse(p.begin(),p.end());
f(i,0,2)
{
if(p[i]=='2')p[i]='5';
else if(p[i]=='5')p[i]='2';
}
if(stoi(p)>=mirrorlimit||stoi(s)>=selflimit)
return false;
return true;
}
string change(string s,ll n,ll mirrorlimit,ll selflimit,bool TTT)
{
while(!valid(s,mirrorlimit,selflimit)||!mirror(s)||!TTT)
{ TTT=true;
if(s[0]=='9'&&s[1]=='9')
{
s="00";
break;
}
else if(s[1]=='9')
{
s[1]='0';
s[0]++;
}
else s[1]++;
if(stoi(s)>=selflimit)
{s="00";break;}
}
return s;
}
int main()
{
ll t;
cin>>t;
while(t--)
{ ll limitH,limitM;
cin>>limitH>>limitM;
string s;
cin>>s;
string ansh="",ansm="";
string sh="";
string sm="";
for(int i=0;i<s.length();i++)
{ if(s[i]==':')
{sh=s.substr(0,i);
sm= s.substr(i+1,s.length()-i-1);
break;
}
}
ansh+=sh;
ansm+=sm;
ll sizeh=sh.length();
ll sizem=sm.length();
bool hourchange=false,minchnage=false,TTT=true;
if(!mirror(sh)||!valid(sh,limitM,limitH))
{hourchange=true;}
if(hourchange)
{ ansh=change(sh,sizeh,limitM,limitH,TTT);
ansm="00";
}
else{
if(!mirror(sm)||!valid(sm,limitH,limitM))
minchnage=true;
if(minchnage)
{
ansm=change(sm,sizem,limitH,limitM,TTT);
if(ansm=="00")
{ TTT=false;
ansh=change(sh,sizeh,limitM,limitH,TTT);
}
}
}
cout<<ansh<<":"<<ansm<<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 | def check(time):
arr = time[:]
arr[0] = str(arr[0])
arr[1] = str(arr[1])
if len(arr[0]) == 1:
arr[0] = '0' + arr[0]
if len(arr[1]) == 1:
arr[1] = '0' + arr[1]
for x in arr:
for y in x:
if dic[y] == '-1':
return 0
newarr = [dic[arr[1][1]] + dic[arr[1][0]], dic[arr[0][1]] + dic[arr[0][0]]]
newarr[0] = int(newarr[0])
newarr[1] = int(newarr[1])
if newarr[0] < h and newarr[1] < m:
return 1
else:
return 0
def fun(time):
arr = time[:]
arr[0] = str(arr[0])
arr[1] = str(arr[1])
if len(arr[0]) == 1:
arr[0] = '0' + arr[0]
if len(arr[1]) == 1:
arr[1] = '0' + arr[1]
print(*arr, sep=':')
t = int(input())
dic = {'0':'0', '1':'1', '2':'5', '3':'-1', '4':'-1', '5':'2', '6':'-1', '7':'-1', '8':'8', '9':'-1'}
for _ in range(t):
h, m = map(int, input().split())
time = input().split(':')
time[0] = int(time[0])
time[1] = int(time[1])
c = check(time)
if c == 1:
fun(time)
continue
for i in range(h*m):
time[1] += 1
if time[1] == m:
time[1] = 0
time[0] += 1
if time[0] == h:
time[0] = 0
c = check(time)
if c == 1:
fun(time)
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 | //Implemented By Aman Kotiyal Date:-06-Mar-2021 Time:-7:13:06 pm
import java.io.*;
import java.util.*;
public class ques2
{
public static void main(String[] args)throws Exception{ new ques2().run();}
long mod=1000000000+7;
int h;
int m;
void solve() throws Exception
{
for(int ii=ni();ii>0;ii--)
{
h=ni();
m=ni();
String s[]=ns().split(":");
int a=Integer.parseInt(s[0]);
int b=Integer.parseInt(s[1]);
HashSet<Integer> set=new HashSet<>();
set.add(0);
set.add(1);
set.add(2);
set.add(5);
set.add(8);
while(true)
{
if(isvalid(a,b,set))break;
b++;
if(b>=m)
{
b=b%m;
a++;
}
if(a>=h)
a=a%h;
}
out.println(String.format("%02d:%02d", a,b));
}
}
boolean isvalid(int a,int b,HashSet<Integer> set)
{
String s=a+"";
String ss="";
boolean ans=true;
for (int i = 0; i < s.length(); i++) {
int x=s.charAt(i)-'0';
if(!set.contains(x))
return false;
else
{
if(x==1)
ss=ss+'1';
if(x==2)
ss=ss+'5';
if(x==0)
ss=ss+'0';
if(x==5)
ss=ss+'2';
if(x==8)
ss=ss+'8';
}
}
s=reverse(ss);
if(s.length()==1)
{
s=s+"0";
}
if(Integer.parseInt(s)>=m)
return false;
s=b+"";
ss="";
for (int i = 0; i < s.length(); i++) {
int x=s.charAt(i)-'0';
if(!set.contains(x))
return false;
else
{
if(x==1)
ss=ss+'1';
if(x==2)
ss=ss+'5';
if(x==0)
ss=ss+'0';
if(x==5)
ss=ss+'2';
if(x==8)
ss=ss+'8';
}
}
s=reverse(ss);
if(s.length()==1)
{
s=s+"0";
}
if(Integer.parseInt(s)>=h)
return false;
return ans;
}
/*FAST INPUT OUTPUT & METHODS BELOW*/
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
private SpaceCharFilter filter;
PrintWriter out;
int min(int... ar){int min=Integer.MAX_VALUE;for(int i:ar)min=Math.min(min, i);return min;}
long min(long... ar){long min=Long.MAX_VALUE;for(long i:ar)min=Math.min(min, i);return min;}
int max(int... ar) {int max=Integer.MIN_VALUE;for(int i:ar)max=Math.max(max, i);return max;}
long max(long... ar) {long max=Long.MIN_VALUE;for(long i:ar)max=Math.max(max, i);return max;}
void reverse(int a[]){for(int i=0;i<a.length>>1;i++){int tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}}
void reverse(long a[]){for(int i=0;i<a.length>>1;i++){long tem=a[i];a[i]=a[a.length-1-i];a[a.length-1-i]=tem;}}
String reverse(String s){StringBuilder sb=new StringBuilder(s);sb.reverse();return sb.toString();}
void shuffle(int a[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i=0;i<a.length;i++)
al.add(a[i]);
Collections.sort(al);
for(int i=0;i<a.length;i++)
a[i]=al.get(i);
}
long lcm(long a,long b)
{
return (a*b)/(gcd(a,b));
}
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
/* for (1/a)%mod = ( a^(mod-2) )%mod ----> use expo to calc -->(a^(mod-2)) */
long expo(long p,long q) /* (p^q)%mod */
{
long z = 1;
while (q>0) {
if (q%2 == 1) {
z = (z * p)%mod;
}
p = (p*p)%mod;
q >>= 1;
}
return z;
}
void run()throws Exception
{
in=System.in; out = new PrintWriter(System.out);
solve();
out.flush();
}
private int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
private int ni() throws IOException
{
int c = scan();
while (isSpaceChar(c))
c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = scan();
} while (!isSpaceChar(c));
return res * sgn;
}
private long nl() throws IOException
{
long num = 0;
int b;
boolean minus = false;
while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = scan();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = scan();
}
}
private double nd() throws IOException{
return Double.parseDouble(ns());
}
private String ns() throws IOException {
int c = scan();
while (isSpaceChar(c))
c = scan();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = scan();
} while (!isSpaceChar(c));
return res.toString();
}
private String nss() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
return br.readLine();
}
private char nc() throws IOException
{
int c = scan();
while (isSpaceChar(c))
c = scan();
return (char) c;
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
private boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhiteSpace(c);
}
private 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 | from heapq import *
from sys import *
from math import *
g=[0,1,5,-1,-1,2,-1,-1,8,-1]
def up(s,n):
if s[n]==0:s[n]=1
elif s[n]==1:s[n]=2
elif s[n]==2:s[n]=5
elif s[n]==5:s[n]=8
elif s[n]==8:
if s[n-1]==0:s[n-1]=2
elif s[n-1]==2:s[n-1]=5
elif s[n-1]==5:s[n-1]=8
elif s[n-1]==8:s[n-1]==10
s[n]=0
def add(s,h,m):
up(s,3)
if s[2]*10+s[3]>=min(m,88):
s[2]=0
s[3]=0
up(s,1)
if s[0]*10+s[1]>=min(h,88):
s[0]=0
s[1]=0
def just(s,h,m):
global g
a=s[0]*10+s[1]
b=s[2]*10+s[3]
while True:
#print(a,b)
s[0]=int(a / 10)
s[1]=a%10
s[2]=int(b / 10)
s[3]=b%10
c=True
for i in s:
if g[i]==-1:
c=False
if c==True:break
b+=1
if b>=m:
b=0
a+=1
if a>=h:
a=0
def chk(s,h,m):
global g
ss=s[:]
for i in range(len(ss)):
ss[i]=g[ss[i]]
a=ss[3]*10+ss[2]
b=ss[1]*10+ss[0]
#print(a,b)
if a<h and b<m:
return True
else:
return False
qn=int(input())
for count in range(qn):
h,m=list(map(int,input().split()))
s=list(input())
s.pop(2)
s=list(map(int,s))
just(s,h,m)
while not chk(s,h,m):
#print(s,h,m)
s[3]+=1
just(s,h,m)
print(s[0],end='')
print(s[1],end='')
print(":",end='')
print(s[2],end='')
print(s[3],end='')
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 | t = int(input())
checklist = [0, 1, 2, 5, 8]
for i in range(0, t):
h, m = map(int, input().split())
time = str(input())
mirror = time[::-1]
gggg = mirror.replace("2", "a")
ggg = gggg.replace("5", "b")
aaaa = ggg.replace("b", "2")
finalmirror = aaaa.replace("a", "5")
one = int(time[0])
two = int(time[1])
three = int(time[3])
four = int(time[4])
first = int(finalmirror[:2])
third = int((finalmirror[3:5]))
realfirst = str(time[:2])
realthird = str((time[3:5]))
if one in checklist and two in checklist and three in checklist and four in checklist and first < h and third < m:
print(time)
else:
j = 0
while j < 202:
newfirst = int(realfirst)
newthird = int(realthird)
newthird += 1
if newthird == m:
j = 0
realthird = "00"
newthird = 0
newfirst = newfirst + 1
if newfirst < 10:
realfirst = "0" + str(newfirst)
else:
realfirst = str(newfirst)
if newfirst == h:
print("00:00")
break
else:
ansfirst = realfirst
ansthird = realthird
temp = realfirst.replace("2", "a")
newtemp = temp.replace("5", "b")
new = newtemp.replace("b", "2")
finalfirst = new.replace("a", "5")
gett = realthird.replace("2", "a")
gettt = gett.replace("5", "b")
gott = gettt.replace("b", "2")
finalthird = gott.replace("a", "5")
ansconcat = [int(i) for i in (str(ansfirst) + str(ansthird))]
concat = [int(i) for i in (str(finalfirst) + str(finalthird))]
#print(concat)
strconcat = "".join(str(elem) for elem in concat)
actualmirror = strconcat[::-1]
newone = concat[0]
newtwo = concat[1]
newthree = concat[2]
newfour = concat[3]
mirrorfirst = int((actualmirror[:2]))
mirrorthird = int((actualmirror[2:4]))
if newone in checklist and newtwo in checklist and newthree in checklist and newfour in checklist and mirrorfirst < h and mirrorthird < m:
answer_str = "".join(map(str, ansconcat))
print(answer_str[0:2] + ":" + answer_str[2:4])
break
else:
if newthird < 10:
realthird = "0" + str(newthird)
#print(realthird)
else:
realthird = str(newthird)
ansfirst = realfirst
ansthird = realthird
temp = realfirst.replace("2", "a")
newtemp = temp.replace("5", "b")
new = newtemp.replace("b", "2")
finalfirst = new.replace("a", "5")
gett = realthird.replace("2", "a")
gettt = gett.replace("5", "b")
gott = gettt.replace("b", "2")
finalthird = gott.replace("a", "5")
ansconcat = [int(i) for i in (str(ansfirst) + str(ansthird))]
concat = [int(i) for i in (str(finalfirst) + str(finalthird))]
newone = concat[0]
newtwo = concat[1]
newthree = concat[2]
newfour = concat[3]
strconcat = "".join(str(elem) for elem in concat)
actualmirror = strconcat[::-1]
mirrorfirst = int((actualmirror[:2]))
mirrorthird = int((actualmirror[2:4]))
if newone in checklist and newtwo in checklist and newthree in checklist and newfour in checklist and mirrorfirst < h and mirrorthird < m:
answer_str = "".join(map(str, ansconcat))
print(answer_str[0:2] + ":" + answer_str[2:4])
break
j = j + 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.math.*;
public class Main {
static int func(int num,int m,HashMap<Integer,Integer> set ,int check) {
while(true) {
int a=num;
int ones=a%10;
a/=10;
int tens=a%10;
if(set.containsKey(ones) && set.containsKey(tens) && (set.get(ones)*10+set.get(tens))<check) {
// System.out.println((set.get(ones)*10+set.get(tens))+" "+num);
return num;
}
num+=1;
num=num%m;
}
}
static String print(int num) {
if(num<10) {
return "0"+Integer.toString(num);
}
return Integer.toString(num);
}
public static void main(String[] args) throws IOException
{
FastScanner f = new FastScanner();
int t=1;
t=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
while(t>0) {
t--;
int h=f.nextInt();
int m=f.nextInt();
String l=f.next();
int hh=Integer.parseInt(l.substring(0,2));
int mm=Integer.parseInt(l.substring(3,5));
// System.out.println(h+" "+m);
// System.out.println(l);
// System.out.println(hh+" yo "+mm);
HashMap<Integer,Integer> set=new HashMap<>();
set.put(0,0);
set.put(1,1);
set.put(2,5);
set.put(5,2);
set.put(8,8);
if(mm==0) {
int ansh=func(hh,h,set,m);
System.out.println(print(ansh)+":"+print(mm));
}
else {
int ansm=func(mm,m,set,h);
int ansh=-1;
if(ansm==0) {
ansh=func((hh+1)%h,h,set,m);
// System.out.println((hh+1)%m);
}
else {
ansh=func(hh,h,set,m);
}
if(ansh!=hh) {
ansm=0;
}
System.out.println(print(ansh)+":"+print(ansm));
}
}
out.close();
}
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 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());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
} | 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 | d={0:0,1:1,2:5,5:2,8:8}
a={*d}
R=lambda x:map(int,input().split(x))
t,=R(' ')
while t:
t-=1;h,m=R(' ');x,y=R(':')
for i in range(h*m):
r=x*m+y+i;p=f'{r//m%h:02}';s=f'{r%m:02}';b=u,v,w,q=*map(int,p+s),
if{*b}<a and h>d[q]*10+d[w]and d[v]*10+d[u]<m:
break
print(p,s,sep=':') | 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 Main {
static int ss[]={0,1,5,-1,-1,2,-1,-1,8,-1};
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int h=sc.nextInt();
int m=sc.nextInt();
String time =sc.next();
String[] s =time.split(":");
int hour=Integer.parseInt(s[0]);
int minute=Integer.parseInt(s[1]);
while(true) {
if (minute >= m) {
minute = 0;
hour++;
}
if (hour >= h) {
hour = 0;
}
int a=minute%10;
int b=minute/10;
int c=hour%10;
int d=hour/10;
int hour2=ss[a]*10+ss[b];
int minute2=ss[c]*10+ss[d];
if (check(a, b, c, d) && hour2 < h && minute2 < m) {
System.out.println(d + "" + c + ":" + b + "" + a);
break;
} else {
minute++;
}
}
}
}
private static boolean check(int a, int b, int c, int d) {
if(ss[a]==-1||ss[b]==-1||ss[c]==-1||ss[d]==-1){
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<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include <queue>
#include<sstream>
#include <stack>
#include <set>
#include <bitset>
#include<vector>
#define FAST ios::sync_with_stdio(false)
#define abs(a) ((a)>=0?(a):-(a))
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define rep(i,a,n) for(int i=a;i<=n;++i)
#define per(i,n,a) for(int i=n;i>=a;--i)
#define endl '\n'
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PII;
const int maxn = 1e5+200;
const int inf=0x3f3f3f3f;
const double eps = 1e-7;
const double pi=acos(-1.0);
const int mod = 1e9+7;
inline int lowbit(int x){return x&(-x);}
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
void ex_gcd(ll a,ll b,ll &d,ll &x,ll &y){if(!b){d=a,x=1,y=0;}else{ex_gcd(b,a%b,d,y,x);y-=x*(a/b);}}//x=(x%(b/d)+(b/d))%(b/d);
inline ll qpow(ll a,ll b,ll MOD=mod){ll res=1;a%=MOD;while(b>0){if(b&1)res=res*a%MOD;a=a*a%MOD;b>>=1;}return res;}
inline ll inv(ll x,ll p){return qpow(x,p-2,p);}
inline ll Jos(ll n,ll k,ll s=1){ll res=0;rep(i,1,n+1) res=(res+k)%i;return (res+s)%n;}
inline ll read(){ ll f = 1; ll x = 0;char ch = getchar();while(ch>'9'||ch<'0') {if(ch=='-') f=-1; ch = getchar();}while(ch>='0'&&ch<='9') x = (x<<3) + (x<<1) + ch - '0', ch = getchar();return x*f; }
int dir[4][2] = { {1,0}, {-1,0},{0,1},{0,-1} };
ll h, m;
map<ll,ll> Map;
PII nextTime(PII cur)
{
ll e = 0;
ll hour = cur.fi;
ll mi = cur.se;
mi += 1;
if(mi>=m) mi = 0, e = 1;
hour += e;
if(hour>=h) hour = 0;
PII ans;
ans.fi = hour;
ans.se = mi;
return ans;
}
PII preTime(PII cur)
{
ll e = 0;
ll hour = cur.fi;
ll mi = cur.se;
mi -= 1;
if(mi<0) mi = m-1, e = 1;
hour -= e;
if(hour<0) hour = h-1;
PII ans;
ans.fi = hour;
ans.se = mi;
return ans;
}
bool check(PII cur)
{
ll hour = cur.fi;
ll mi = cur.se;
vector<ll> mirrorMi;
vector<ll> mirrorH;
while(mi) mirrorMi.pb(mi%10), mi /= 10;
while(mirrorMi.size()<2) mirrorMi.pb(0);
while(hour) mirrorH.pb(hour%10), hour /= 10;
while(mirrorH.size()<2) mirrorH.pb(0);
int flag = 1;
for(int i=0; i<mirrorMi.size(); i++) if(mirrorMi[i]!=0&&!Map[mirrorMi[i]]) flag = 0;
for(int i=0; i<mirrorH.size(); i++) if(mirrorH[i]!=0&&!Map[mirrorH[i]]) flag = 0;
if(!flag) return false;
ll curM = Map[mirrorH[0]]*10+Map[mirrorH[1]];
ll curH = Map[mirrorMi[0]]*10 + Map[mirrorMi[1]];
if(curH<h&&curM<m) return true;
return false;
}
int main()
{
Map[0] = 0;
Map[1] = 1;
Map[2] = 5;
Map[5] = 2;
Map[8] = 8;
int kase;
cin>>kase;
while(kase--)
{
h = read(), m = read();
PII cur;
scanf("%lld:%lld",&cur.fi, &cur.se);
PII tmp = cur;
ll step1 = 0;
while(1)
{
if(check(cur)) break;
step1++;
cur = nextTime(cur);
}
// if(step2<step1) cur = tmp;
printf("%02lld:%02lld\n",cur.fi,cur.se);
}
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 | class Time:
def __init__(self, hh, mm) -> None:
self.h = str(hh)
self.m = str(mm)
self.nh = int(hh)
self.nm = int(mm)
if len(self.h) < 2:
self.h = '0'+self.h
if len(self.m) < 2:
self.m = '0'+self.m
def rev(self):
return Time(revers(self.m), revers(self.h))
def p(self):
print(self.h+':'+self.m)
def pp(self):
print(self.nh, self.nm)
def later(a, b):
if a.nh > b.nh or (a.nh == b.nh and a.nm >= b.nm):
return True
else:
return False
def revers(s):
ss = ''
for i in s:
if i == '5':
ss += '2'
elif i == '2':
ss += '5'
else:
ss += i
return ''.join(j for j in reversed(ss))
def ok(t, h, m):
if t.nh < h and t.nm < m:
return True
else:
return False
for _ in range(int(input())):
h, m = [int(i) for i in input().split(' ')]
hh, mm = [i for i in input().split(':')]
time = Time(hh, mm)
v = ['00', '01', '02', '05', '08',
'10', '11', '12', '15', '18',
'20', '21', '22', '25', '28',
'50', '51', '52', '55', '58',
'80', '81', '82', '85', '88']
f = 0
for i in v:
for j in v:
dt = Time(i, j)
if later(dt, time) and ok(dt, h, m) and ok(dt.rev(), h, m):
dt.p()
f = 1
break
if f == 1:
break
if f == 0:
print('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>
#define ll long long
using namespace std;
int mirror[10] = {0, 1, 5, 9999, 9999, 2, 9999, 9999, 8, 9999};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--) {
int h, m, h1, h2, m1, m2;
string s;
cin >> h >> m >> s;
h1 = s[0] - '0';
h2 = s[1] - '0';
m1 = s[3] - '0';
m2 = s[4] - '0';
while(true) {
int hm = mirror[m1] + 10 * mirror[m2];
int mm = mirror[h1] + 10 * mirror[h2];
if (hm < h && mm < m) {
cout << h1 << h2 << ":" << m1 << m2 <<"\n";
break;
}
int m3 = m1 * 10 + m2 + 1;
int h3 = h1 * 10 + h2;
if (m3 == m) {
m3 = 0;
h3++;
if (h3 == h) h3 = 0;
}
h1 = h3 / 10;
h2 = h3 % 10;
m1 = m3 / 10;
m2 = m3 % 10;
}
}
}
| 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 | from collections import Counter
import math
# class Solution(object):
# def __init__(self):
# self.d={}
# def solve(self,vec,level):
# #print "temp_vec:",vec," level=",level
# if len(vec)==0:
# return
# if len(vec)==1:
# self.d[vec[0]]=level
# return
# max_v=max(vec)
# max_index = vec.index(max_v)
# #print("max_v=",max_v," max_index ",max_index)
# self.d[max_v]=level
# self.solve(vec[:max_index],level+1)
# self.solve(vec[max_index+1:], level+1)
def good_reverse_time(h,m,h_lim,m_lim,dic):
h_10=h//10
h_1=h%10
m_10=m//10
m_1=m%10
#print "h10,h1,m_10,m_1",h_10,h_1,m_10,m_1
if h_10 not in dic or h_1 not in dic or m_10 not in dic or m_1 not in dic:
return False
new_h = dic[m_1]*10+dic[m_10]
new_m = dic[h_1]*10+dic[h_10]
return new_h<h_lim and new_m<m_lim
if __name__=="__main__":
n_cases= int(raw_input().strip())
dic={}
dic[0]=0
dic[1]=1
dic[2]=5
dic[5]=2
dic[8]=8
for i in range(0,n_cases):
h,m=map(int,raw_input().split(" "))
th,tm = map(int,raw_input().split(":"))
while(1):
if th==0 and tm==0:
print "00:00"
break
if good_reverse_time(th,tm,h,m,dic):
sth = str(th)
if len(sth)<2:
sth="0"+sth
stm = str(tm)
if len(stm)<2:
stm="0"+stm
print sth+":"+stm
break
tm+=1
if tm ==m:
tm = 0
th += 1
if th == h:
th = 0
| 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.*;
public class Practice {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while (t-- > 0) {
int hrmax = s.nextInt();
int minmax = s.nextInt();
String time = s.next();
String ans = "00:00";
HashMap<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);
int flag=0;
int ghr = Integer.valueOf(time.split(":")[0]);
int gmin = Integer.valueOf(time.split(":")[1]);
for (int i = ghr; i < hrmax; i++) {
if (i == ghr) {
for (int j = gmin; j < minmax; j++) {
if(!map.containsKey(i/10)||!map.containsKey(i%10)||!map.containsKey(j/10)||!map.containsKey(j%10)) {
continue;
}
int nex=(map.get(i%10))*10+map.get(i/10);
int pre=(map.get(j%10))*10+map.get(j/10);
if(nex>=minmax||pre>=hrmax) {
continue;
}
ans=i+":"+j;
flag=1;
break;
}
} else {
for (int j = 0; j < minmax; j++) {
if(!map.containsKey(i/10)||!map.containsKey(i%10)||!map.containsKey(j/10)||!map.containsKey(j%10)) {
continue;
}int nex=(map.get(i%10))*10+map.get(i/10);
int pre=(map.get(j%10))*10+map.get(j/10);
if(nex>=minmax||pre>=hrmax) {
continue;
}ans=i+":"+j;
flag=1;
break;
}
}if(flag==1) {
break;
}
}
String s1=ans.split(":")[0];
if(s1.length()<2) {
while(s1.length()<2) {
s1=0+s1;
}
}
String s2=ans.split(":")[1];
if(s2.length()<2) {
while(s2.length()<2) {
s2=0+s2;
}
}ans=s1+":"+s2;
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 | #include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int N = 55;
int t;
int h, m;
char s[10];
int valid[110] = { 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,100};//25
int find(int x)
{
int l = 0, r = 25;
while (l < r)
{
int mid = l + r >> 1;
if (valid[mid] >= x)
r = mid;
else
l = mid + 1;
}
return l;
}
bool checknum(char c)
{
int x = c - '0';
if (x == 3 || x == 4 || x == 6 || x == 7 || x == 9)
return false;
return true;
}
int getreflect(int c)
{
if (c == 0)
return 0;
if (c == 1)
return 1;
if (c == 2)
return 5;
if (c == 5)
return 2;
if (c == 8)
return 8;
}
bool valck(int x, int mode)
{
int k = valid[find(x)];
if (k != x)
return false;
if (mode == 1 && k > h - 1)
return false;
if (mode == 2 && k > m - 1)
return false;
int temp = k / 10;
temp = getreflect(temp);
k = temp + getreflect(k % 10) * 10;
if (mode == 1 && k > m - 1)
return false;
if (mode == 2 && k > h - 1)
return false;
return true;
}
bool check(char str[])
{
if (!checknum(str[1]) || !checknum(str[2]) || !checknum(str[4]) || !checknum(str[5]))
return false;
if (10 * getreflect(str[5]) + getreflect(str[4]) > h - 1)
return false;
if (10 * getreflect(str[2]) + getreflect(str[1]) > m - 1)
return false;
return true;
}
int main()
{
scanf("%d", &t);
while (t--)
{
scanf("%d%d%s", &h, &m, s + 1);
int hour = 10 * (s[1] - '0') + (s[2] - '0');
int min = 10 * (s[4] - '0') + (s[5] - '0');
if (valck(hour, 1) && valck(min, 2))
puts(s + 1);
else
{
if (valck(hour, 1))
{
while (1)
{
min = valid[find(min + 1)];
if (min > m - 1)
{
while (1)
{
hour = valid[find(hour + 1)];
if (hour > h - 1)
{
hour = 0;
break;
}
if (valck(hour, 1))
break;
}
min = 0;
if (hour < 10)
printf("0%d:00\n", hour);
else
printf("%d:00\n", hour);
break;
}
if (valck(min, 2))
{
if (hour < 10)
printf("0%d:", hour);
else
printf("%d:", hour);
if (min < 10)
printf("0%d\n", min);
else
printf("%d\n", min);
break;
}
}
}
else
{
while (1)
{
hour = valid[find(hour + 1)];
if (hour > h - 1)
{
hour = 0;
break;
}
if (valck(hour, 1))
break;
}
if (hour < 10)
printf("0%d:00\n", hour);
else
printf("%d:00\n", hour);
}
}
}
//printf("%d %d\n", find(89),valid[find(89)]);
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 | l=['0','1','2','5','8']
def g(x):
if x=='2':
return '5'
if x=='5':
return '2'
return x
def f(x,y,p,q):
s1=str(x)
s2=str(y)
for c in s1:
if c not in l:
return False
for c in s2:
if c not in l:
return False
if len(s1)==1:
s1='0'+s1
if len(s2)==1:
s2='0'+s2
s3=int(g(s2[1])+g(s2[0]))
s4=int(g(s1[1])+g(s1[0]))
#print(s1,s2,s3,s4)
if s3<p and s4<q:
return True
return False
for _ in range(int(input())):
h,m=map(int,input().split())
s=input()
x=int(s[:2])
y=int(s[3:])
am=False
while not am:
while x<h and not am:
while y<m and not am:
if f(x,y,h,m):
am=True
s1=str(x)
s2=str(y)
if len(s1)==1:
s1='0'+s1
if len(s2)==1:
s2='0'+s2
print(s1+':'+s2)
y+=1
if y==m:
y=0
x+=1
if x==h:
x=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 | from os import path
import sys,time
# mod = int(1e9 + 7)
from math import ceil, floor,gcd,log,log2 ,factorial,sqrt
from collections import defaultdict ,Counter , OrderedDict , deque;from itertools import combinations,permutations
# from string import ascii_lowercase ,ascii_uppercase
from bisect import *;from functools import reduce;from operator import mul;maxx = float('inf')
I = lambda :int(sys.stdin.buffer.readline())
lint = lambda :[int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda: sys.stdin.readline().strip('\n')
grid = lambda r :[lint() for i in range(r)]
localsys = 0
start_time = time.time()
#left shift --- num*(2**k) --(k - shift)
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)
def ceill(n,x):
return (n+x -1 )//x
T =1
def ok (s,d,h,m,t ):
X , s = [] , '0'*(2- len(s)) + s
for i in s:
if i not in d:
return False
X.append(d[i])
x = ''.join(X)[::-1]
if (t and int(x) < m) or (t ==0 and int(x) < h):
return True
return False
def c(s,x):
return (s+1)%x
def solve():
h,m = map(int , input().split())
s1,s2 = map(int,input().split(':'))
d, cnt, c , fl = {'1':'1' , '2':'5' , '5':'2' , '8':'8','0':'0'} ,h*m , m , True
while cnt :
if ok(str(s1),d,h, m , 1) and ok(str(s2), d,h ,m , 0):
s1, s2 =str(s1) , str(s2)
print('0'*(2- len(s1))+ s1+':'+ '0'*(2- len(s2))+ s2)
return
cnt-=1
s2 ,c = (s2+1)%m, c-1
if c == 0 or (fl and s2 == 0):
c ,fl =m , False
s1 = (s1+1)%h
print('00:00')
def run():
if (path.exists('input.txt')):
sys.stdin=open('input.txt','r')
sys.stdout=open('output.txt','w')
run()
T = I() if T else 1
for _ in range(T):
solve()
if localsys:
print("\n\nTime Elased :",time.time() - start_time,"seconds") | 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;
int c[12];
bool check(int h, int m, int hh, int mm){
int h2 = hh % 10;
hh /= 10;
int h1 = hh % 10;
int m2 = mm % 10;
mm /= 10;
int m1 = mm % 10;
if (c[h1] == -1 || c[h2] == -1 || c[m1] == -1 || c[m2] == -1) return false;
int hh1 = h1, hh2 = h2;
h1 = c[m2];
h2 = c[m1];
m1 = c[hh2];
m2 = c[hh1];
if ( h1 * 10 + h2 < h && m1 * 10 + m2 < m)return true;
return false;
}
void find(int h, int m, int hh, int mm){
while (true){
if (check(h, m, hh, mm)){
if (hh < 10){
cout << "0" << hh;
} else cout <<hh;
cout << ":";
if (mm < 10){
cout << "0" << mm;
} else cout << mm;
cout << endl;
break;
} else {
mm++;
if ( mm == m){
mm = 0;
hh++;
if (hh == h){
hh = 0;
}
}
}
}
}
int main() {
int t;
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
c[0] = 0; c[1] = 1; c[2] = 5; c[3] = -1;
c[4] = -1; c[5] = 2; c[6] = -1; c[7] = -1; c[8] = 8; c[9] = -1;
cin >> t;
while (t--){
int h, m;
int hh, mm;
char c;
cin >> h >> m;
cin >> hh >> c >> mm;
find(h, m, hh, mm);
}
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.io.*;
public class CodeForces1493B {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int t = sc.nextInt();
PrintWriter pw = new PrintWriter(System.out);
while(t-->0) {
int h = sc.nextInt();
int m = sc.nextInt();
String[] s = sc.next().split(":");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
while(!check(a, b, h, m)) {
b++;
if(b >= m) {
b = 0;
a++;
if(a >= h) {
a = 0;
}
}
}
String res = String.format("%2d:%2d",a, b).replaceAll(" ","0");
System.out.println(res);
}
}
static int[] inv = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1};
static boolean check(int a, int b, int h, int m) {
if(inv[a/10] < 0) return false;
if(inv[a%10] < 0) return false;
if(inv[b/10] < 0) return false;
if(inv[b%10] < 0) return false;
int newb = 10*inv[a%10]+inv[a/10];
int newa = 10*inv[b%10]+inv[b/10];
return newa < h && newb < m;
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.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 | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define fastio \
ios_base::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0)
#define scl(n) scanf("%lld", &n)
#define pcl(n) printf("%lld\n", n)
#define pcl1(n) printf("%lld ", n)
#define nln printf("\n")
#define yes printf("YES\n")
#define no printf("NO\n")
#define dev(x) cout << #x << " " << x << " ";
#define PTT pair<ll, ll>
map<ll, ll> mp, mp1;
map<ll, ll>::iterator itr;
int main()
{
ll t, n, k, x, y, a, b, d;
while (cin >> t)
{
vector<ll> vm;
vm.push_back(0);
vm.push_back(1);
vm.push_back(2);
vm.push_back(5);
vm.push_back(8);
for (int i = 0; i < vm.size(); i++)
{
for (int j = 0; j < vm.size(); j++)
{
x = vm[i] * 10 + vm[j];
mp[x] += 1;
}
}
vector<PTT> v;
PTT p;
for (auto k : mp)
{
if (k.first < 10)
{
p.first = k.first;
p.second = k.first * 10;
if (p.first == 2)
{
p.second = 5 * 10;
}
else if (p.first == 5)
{
p.second = 2 * 10;
}
v.push_back(p);
//mp[k.first] = k.first * 10;
}
else
{
d = k.first % 10;
if (d == 2)
{
d = 5;
}
else if (d == 5)
{
d = 2;
}
x = k.first / 10;
if (x == 2)
{
x = 5;
}
else if (x == 5)
{
x = 2;
}
y = d * 10 + x;
//mp[k.first] = y;
p.first = k.first;
p.second = y;
v.push_back(p);
}
//cout << p.first << " " << p.second << endl;
}
//nln;
for (int cs = 0; cs < t; cs++)
{
ll h, m;
string s;
cin >> h >> m;
cin >> s;
ll hr = 0, mn = 0;
hr += ((ll)(s[0] - '0') * 10 + (ll)(s[1] - '0'));
mn += ((ll)(s[3] - '0') * 10 + (ll)(s[4] - '0'));
//cout << hr << " " << mn << "-->";
a = 0, b = 0;
ll c = 0, d = 0;
x = hr, y = mn;
for (int i = 0; i < v.size(); i++)
{
if (v[i].first < x)
{
continue;
}
while (x < v[i].first)
{
x++;
}
if (x == v[i].first && v[i].first <= h - 1 && v[i].second <= m - 1)
{
a = v[i].first;
c = v[i].second;
break;
}
}
for (int i = 0; i < v.size(); i++)
{
if (v[i].first < y)
{
continue;
}
while (y < v[i].first)
{
y++;
}
if (y <= v[i].first && v[i].first <= m - 1 && v[i].second <= h - 1)
{
b = v[i].first;
d = v[i].second;
break;
}
}
if (a < x && a == 0)
{
b = 0;
}
else if (b == 0 && (a == x && b < y))
{
a = 0;
x = hr + 1;
for (int i = 0; i < v.size(); i++)
{
if (v[i].first < x)
{
continue;
}
while (x < v[i].first)
{
x++;
}
if (x <= v[i].first && v[i].first <= h - 1 && v[i].second <= m - 1)
{
a = v[i].first;
c = v[i].second;
break;
}
}
}
if (a > hr)
{
b = 0;
}
//cout << a << " " << c << " " << b << " " << d << endl;
if (a == 0)
{
cout << "00:";
}
else
{
if (a / 10 == 0)
{
cout << "0" << a << ":";
}
else
{
cout << a << ":";
}
}
if (b == 0)
{
cout << "00";
}
else
{
if (b / 10 == 0)
{
cout << "0" << b;
}
else
{
cout << b;
}
}
nln;
}
}
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 changeNum(s,startDay, endDay,h,m):
if (s == endDay):
s = startDay
return s
list1 = list(s)
x = int(s[2:4])
x += 1
nextHr = False
if x == m:
x = 0
nextHr = True
if x < 10:
list1[2] = '0'
list1[3] = str(x)
else:
temp = str(x)
list1[2] = temp[0]
list1[3] = temp[1]
if (nextHr):
x = int(s[0:2])
x += 1
if x == h:
x = 0
if x < 10:
list1[0] = '0'
list1[1] = str(x)
else:
temp = str(x)
list1[0] = temp[0]
list1[1] = temp[1]
newS = ""
for i in list1:
newS += i
return newS
ref = {'0':'0','1':'1','2':'5','5':'2','8':'8',':':':'}
tc = int(input())
for i in range(tc):
h,m = map(int, input().split())
startDay = "0000"
endDay = ""
if h <= 10:
endDay += "0" + str(h - 1)
else:
endDay += str(h-1)
if m <= 10:
endDay += "0" + str(m-1)
else:
endDay += str(m-1)
s = input()
s = s[0:2] + s[3:5]
#s = changeNum(s,startDay,endDay,h,m)
while(True):
allDigRef = True
stemp = ""
for digit in s:
if digit not in ref:
allDigRef = False
break
else:
stemp += ref[digit]
stemp = stemp[::-1]
if not allDigRef:
s = changeNum(s,startDay,endDay,h,m)
else:
validity = False
if stemp[0:2] <= endDay[0:2] and stemp[2:4] <= endDay[2:4]:
validity = True
if (validity):
break
else:
s = changeNum(s,startDay,endDay,h,m)
#print(s)
s = s[0:2] + ':' + s[2:4]
print(s) | 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 |
from __future__ import division
import sys
input = sys.stdin.readline
import math
from math import sqrt, floor, ceil
from collections import Counter
from copy import deepcopy as dc
# from statistics import median, mean
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def insr2():
s = input()
return(s.split(" "))
def prime_factorization(n):
if n == 1:
return [1]
ans=[]
i = 2
cap = sqrt(n)
while i <= cap:
if n % i == 0:
ans.append(i)
n = n//i
cap=sqrt(n)
else:
i += 1
if n > 1:
ans.append(n)
return ans
def binomial(n, k):
if n == 1 or n == k:
return 1
if k > n:
return 0
else:
a = math.factorial(n)
b = math.factorial(k)
c = math.factorial(n-k)
div = a // (b * c)
return div
arr = [-1]*10
arr[0] = 0
arr[1] = 1
arr[2] = 5
arr[5] = 2
arr[8] = 8
def check_time(time, arr=arr):
for i in time:
if arr[int(i)] == -1:
return -1
else:
hour = str(arr[int(time[3])]) + str(arr[int(time[2])])
minute = str(arr[int(time[1])]) + str(arr[int(time[0])])
return (hour, minute)
for _ in range(inp()):
h, m = invr()
f = False
s = insr()
time = s[0]+s[1]+s[3]+s[4]
while str(time) != '9999':
time = str(time)
if len(time) < 4:
time = '0'*(4-len(time)) + time
if check_time(time) == -1:
time = int(time) + 1
else:
if int(check_time(time)[0]) < h and int(check_time(time)[1]) < m:
if int(time[:2]) < h and int(time[2:4]) < m:
print time[:2]+ ":" + time[2:4]
f = True
break
else:
time = int(time) + 1
else:
time = int(time) + 1
if f == False:
print '00:00'
| 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.*;
import java.util.Arrays;
public class B_PlanetLapituletti {
public static boolean check(int[] arr,int h,int m,int a,int b) {
if(arr[a/10]==-1 || arr[a%10]==-1 || arr[b/10]==-1 || arr[b%10]==-1) {
return false;
}
int hr=arr[b%10]*10+arr[b/10];
int min=arr[a%10]*10+arr[a/10];
if(h>hr && m>min) {
return true;
}
return false;
}
public static void main(String args[]) throws NumberFormatException, IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t =Integer.parseInt(br.readLine());
int[] arr=new int[10];
Arrays.fill(arr, -1);
arr[0]=0;
arr[1]=1;
arr[2]=5;
arr[5]=2;
arr[8]=8;
StringBuilder sb=new StringBuilder();
while(t-->0){
String[] time=br.readLine().split(" ");
int h=Integer.parseInt(time[0]);
int m=Integer.parseInt(time[1]);
String[] str=br.readLine().split(":");
int a=Integer.parseInt(str[0]);
int b=Integer.parseInt(str[1]);
while(!check(arr,h,m,a,b)) {
b++;
if(b==m) {
a++;
}
a%=h;
b%=m;
}
if(a>=10){
sb.append(a);
}else if(a==0){
sb.append("00");
}else {
sb.append("0"+a);
}
sb.append(":");
if(b>=10){
sb.append(b);
}else if(b==0){
sb.append("00");
}
else{
sb.append("0"+b);
}
sb.append("\n");
}
System.out.println(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 | import sys
input = iter(sys.stdin.read().splitlines()).__next__
REFLECTIONS = [0, 1, 5, None, None, 2, None, None, 8, None]
def reflect(hh, mm):
# print(hh, mm)
reflections = list(map(REFLECTIONS.__getitem__, [mm % 10, mm // 10, hh % 10, hh // 10]))
if None in reflections:
return None
return 10*reflections[0]+reflections[1], 10*reflections[2]+reflections[3]
def solve():
h, m = map(int, input().split())
hh, mm = map(int, input().split(':'))
reflection = reflect(hh, mm)
while reflection is None or reflection[0] >= h or reflection[1] >= m:
mm += 1
if mm >= m:
mm = 0
hh += 1
if hh >= h:
hh = 0
reflection = reflect(hh, mm)
return f"{hh//10}{hh%10}:{mm//10}{mm%10}"
t = int(input())
output = []
for _ in range(t):
output.append(solve())
print(*output, sep="\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 | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int t;
char num[5] = {'0', '1', '2', '5', '8'};
int h, m;
string s;
vector<string> times;
string reverse(string str)
{
string res;
for (int i = str.size() - 1; i >= 0; i--)
{
if(str[i] == '2')
res += '5';
else if(str[i] == '5')
res += '2';
else
res += str[i];
}
return res;
}
bool inNum(){
bool same[5] = {false};
for (int i = 0; i < 5; ++i) {
if(i != 2){
for (int j = 0; j < 5; ++j) {
if(s[i] == num[j])
same[i] = true;
}
}
}
return same[0] && same[1] && same[3] && same[4];
}
bool isRight(string string1){
int minute = stoi(reverse(string1.substr(0, 2)));
int hour = stoi(reverse(string1.substr(3, 2)));
int hour2 = stoi(string1.substr(0, 2));
int minute2 = stoi(string1.substr(3, 2));
if(minute <= m - 1 && hour <= h - 1 && hour2 <= h - 1 && minute2 <= m - 1)
return true;
else return false;
}
int main() {
cin >> t;
for (int j1 = 0; j1 < 5; ++j1) {
for (int j2 = 0; j2 < 5; ++j2) {
for (int j3 = 0; j3 < 5; ++j3) {
for (int j4 = 0; j4 < 5; ++j4) {
string temp = {num[j1], num[j2], ':', num[j3], num[j4]};
times.push_back(temp);
}
}
}
}
for (int i = 0; i < t; ++i) {
cin >> h >> m;
cin >> s;
if(inNum() && isRight(s)){
cout << s << endl;
} else{
int is0 = true;
int hour2 = stoi(s.substr(0, 2));
int minute2 = stoi(s.substr(3, 2));
int ans = 0;
for (int j = 1; j < 625; ++j) {
int hour = stoi(times[j].substr(0, 2));
int minute = stoi(times[j].substr(3, 2));
if(isRight(times[j])){
if(hour > hour2 || (hour == hour2 && minute > minute2)){
ans = j;
is0 = false;
break;
}
}
}
if(is0) cout << "00:00" << endl;
else cout << times[ans] << 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 |
# *****DO NOT COPY*****
# F
# U ___ ___ ___ ___ ___ ___ _____
# C / /\ ___ / /\ ___ /__/\ / /\ / /\ / /\ / /::\
# K / /::\ / /\ / /:/_ / /\ \ \:\ / /::\ / /::\ / /:/_ / /:/\:\
# / /:/\:\ / /:/ / /:/ /\ / /::\ \ \:\ / /:/\:\ / /:/\:\ / /:/ /\ / /:/ \:\
# Y / /:/~/:/ /__/::\ / /:/ /::\ / /:/\:\ ___ \ \:\ / /:/~/::\ / /:/~/:/ / /:/ /:/_ /__/:/ \__\:|
# O /__/:/ /:/ \__\/\:\__ /__/:/ /:/\:\ / /:/~/::\ /__/\ \__\:\ /__/:/ /:/\:\ /__/:/ /:/___ /__/:/ /:/ /\ \ \:\ / /:/
# U \ \:\/:/ \ \:\/\ \ \:\/:/~/:/ /__/:/ /:/\:\ \ \:\ / /:/ \ \:\/:/__\/ \ \:\/:::::/ \ \:\/:/ /:/ \ \:\ /:/
# \ \::/ \__\::/ \ \::/ /:/ \ \:\/:/__\/ \ \:\ /:/ \ \::/ \ \::/~~~~ \ \::/ /:/ \ \:\/:/
# A \ \:\ /__/:/ \__\/ /:/ \ \::/ \ \:\/:/ \ \:\ \ \:\ \ \:\/:/ \ \::/
# L \ \:\ \__\/ /__/:/ \__\/ \ \::/ \ \:\ \ \:\ \ \::/ \__\/
# L \__\/ \__\/ \__\/ \__\/ \__\/ \__\/
"""
⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⠋⣉⣉⣉⣉⣉⣉⠙⠛⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⡿⠟⢁⣤⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⡈⠻⢿⣿⣿⣿⣿⣿
⣿⣿⣿⡿⠋⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠙⢿⣿⣿⣿
⣿⣿⡟⢀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⢻⣿⣿
⣿⡟⢠⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⢻⣿
⣿⢀⣿⣿⣿⠟⠁⣠⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⣄⠈⠻⣿⣿⣿⡀⣿
⡇⢸⣿⣿⠋⣠⡾⠿⠛⠛⠛⠿⣿⣿⣿⣿⣿⣿⠿⠛⠛⠛⠻⢷⣄⠙⣿⣿⡇⢸
⡇⢸⣿⣿⣾⣿⢀⣠⣤⣤⣤⣤⣀⣿⣿⣿⣿⣀⣤⣤⣤⣤⣄⡀⣿⣷⣾⣿⡇⢸
⡇⠸⠟⣫⣥⣶⣧⠹⠿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠏⣼⣶⣬⣍⠻⠇⢸
⡧⣰⣿⣿⣿⣿⣿⢰⣦⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣴⡆⣿⣿⣿⣿⣿⣆⢼
⡇⣿⣿⣿⣿⣿⡟⠈⠙⠛⠻⠿⠿⠿⠿⠿⠿⠿⠿⠟⠛⠋⠁⢻⣿⣿⣿⣿⣿⢸
⣿⣌⡻⠿⠿⢋⣴⣦⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⡀⢀⣴⣦⡙⠿⠿⢟⣡⣾
⣿⣿⣿⣷⣄⠙⢿⣿⣿⣶⣤⣀⡀⡀⡀⡀⡀⡀⣀⣤⣶⣿⣿⡿⠋⣠⣾⣿⣿⣿
⣿⣿⣿⣿⣿⣷⣦⣉⠛⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⣉⣴⣾⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣤⣌⣉⣉⣉⣉⣉⣉⣡⣤⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿
*****DO NOT COPY******
"""
from sys import stdin
def solve():
return 0
# for i in range(int(input())):
# n, k = [int(i) for i in input().split()]
# l = []
# if n > k:
# for j in range(k + 1, n + 1):
# l.append(j)
#
# for m in range(math.ceil(k / 2), k):
# l.append(m)
#
# le = len(l)
# print(le)
# for a in range(le):
# print(l[a], end=" ")
# print()
# outputs = list(range(1, n + 1))
# outputs.remove(k)
# for i in range(1, n + 1):
# if i <= k and k - i != i and k - i in outputs:
# outputs.remove(i)
#
# outputs = list(map(str, outputs))
# print(len(outputs))
# print(" ".join(outputs))
# for _ in range(int(input())):
# postTimes = [[0 , 0] , [1,1] , [2,5] , [5 , 2] , [8 , 8] , [10, 10], [11, 11] , [12 , 15], [15 , 12] , [18, 18], [20 , 50], [21,51] , [22,55], [25, 52] , [28,58], [50,20], [51,21] , [52,25] , [55,22], [58,28] , [80,80] , [81,81] , [82,85] , [85,82] , [88 ,88]]
#
# h , m = map(int , input().split())
# time = input()
# if time[0] != "0":
# currentHours = int(time[:2])
# else:
# currentHours = int(time[1:2])
# if time[3] != "0":
# currentminutes = int(time[3:5])
# else:
# currentminutes = int(time[4:5])
#
# # print(currentHours , minutes)
#
# outputHour = 0
#
# for i in range(currentHours , h):
# f = 0
# for j in range(25):
# if i == postTimes[j][0]:
# # and int(str(postTimes[j][1])[::-1]) < m
# if i >= 10:
# if int(str(postTimes[j][1])[::-1]) < m:
# outputHour = i
# f = 1
# break
# else:
# if int((str(postTimes[j][1]) + "0")) < m:
# outputHour = i
# f = 1
# break
#
# if f == 1:
# break
#
# outputMinutes = 0
# for i in range(currentminutes ,m):
# f = 0
# for j in range(25):
# if i == postTimes[j][0]:
# if i >= 10:
# if int(str(postTimes[j][1])[::-1]) < h:
# outputMinutes = i
# f = 1
# break
# else:
# if int((str(postTimes[j][1]) + "0")) < h:
# outputMinutes = i
# f = 1
# break
# if f == 1:
# break
# if outputHour < 10:
# outputHour = "0" + str(outputHour)
# else:
# outputHour = str(outputHour)
# if outputMinutes < 10:
# outputMinutes = "0" + str(outputMinutes)
# else:
# outputMinutes = str(outputMinutes)
#
# print(outputHour+":"+outputMinutes)
for _ in range(int(input())):
h, m = [int(i) for i in input().split()]
s = input()
m1 = int(s[3])
m2 = int(s[4])
h1 = int(s[0])
h2 = int(s[1])
vava = [1,1,1,0,0,1,0,0,1,0]
ref = [0,1,5,0,0,2,0,0,8,0]
# f = 1
# break
# else:
# if int((str(postTimes[j][1]) + "0")) < h:
# outputMinutes = i
# f = 1
# break
# if f == 1:
# break
# if outputHour < 10:
# outputHour = "0" + str(outputHour)
# else:
# outputHour = str(outputHour)
# if outputMinutes < 10:
# outputMinutes = "0" + str(outputMinutes)
# else:
# outputMinutes = str(outputMinutes)
#
# print(outputHour+":"+outputMinutes)
while(True):
# print(h1 , h2 , m1 , m2)
if(vava[h1] and vava[h2] and vava[m1] and vava[m2]):
H1 = ref[m2]
H2 = ref[m1]
M1 = ref[h2]
M2 = ref[h1]
if (H1*10 + H2 < h) and (M1*10 + M2 < m):
res = [h1, h2, m1, m2]
break
else:
mins = m1 * 10 + m2
hours = h1 * 10 + h2
if mins == m - 1:
m1 = 0
m2 = 0
if hours == h - 1:
h1 = 0
h2 = 0
else:
hours += 1
h1 = hours // 10
h2 = hours % 10
else:
mins += 1
m1 = mins // 10
m2 = mins % 10# for _ in range(int(input())):
# postTimes = [[0 , 0] , [1,1] , [2,5] , [5 , 2] , [8 , 8] , [10, 10], [11, 11] , [12 , 15], [15 , 12] , [18, 18], [20 , 50], [21,51] , [22,55], [25, 52] , [28,58], [50,20], [51,21] , [52,25] , [55,22], [58,28] , [80,80] , [81,81] , [82,85] , [85,82] , [88 ,88]]
#
# h , m = map(int , input().split())
# time = input()
# if time[0] != "0":
# currentHours = int(time[:2])
# else:
# currentHours = int(time[1:2])
# if time[3] != "0":
# currentminutes = int(time[3:5])
# else:
# currentminutes = int(time[4:5])
#
# # print(currentHours , minutes)
#
else:
mins = m1*10 + m2
hours = h1*10 + h2
if mins==m-1:
m1 = 0
m2 = 0
if hours==h-1:
h1 = 0
h2 = 0
else:
hours += 1
h1 = hours//10
h2 = hours%10
else:
mins += 1
m1 = mins//10
m2 = mins%10
# outputHour = 0
#
# for i in range(currentHours , h):
# f = 0
# for j in range(25):
# if i == postTimes[j][0]:
# # and int(str(postTimes[j][1])[::-1]) < m
# if i >= 10:
# if int(str(postTimes[j][1])[::-1]) < m:
# outputHour = i
# f = 1
# break
# else:
# if int((str(postTimes[j][1]) + "0")) < m:
# outputHour = i
# f = 1
# break
print(res[0] , end="")
print(res[1], end="")
print(":" , end="")
print(res[2], end="")
print(res[3], end="")
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 | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
/*
HashMap<> map=new HashMap<>();
TreeMap<> map=new TreeMap<>();
map.put(p,map.getOrDefault(p,0)+1);
for(Map.Entry<> mx:map.entrySet()){
int v=mx.getValue(),k=mx.getKey();
}for (int i = 1; i <= 1000; i++)
fac[i] = fac[i - 1] * i % mod;
ArrayList<Pair<Character,Integer>> l=new ArrayList<>();
ArrayList<> l=new ArrayList<>();
HashSet<> has=new HashSet<>();
PriorityQueue<Integer> pq=new PriorityQueue<>(new Comparator<Integer>(){
public int compare(Integer a,Integer b){
return Integer.compare(b,a);
}
});
Arrays.sort(ar,new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return Double.compare(a[0], b[0]);
}
});*/
PrintWriter out;
FastReader sc;
long mod=(long)(1e9+7);
int maxint= Integer.MAX_VALUE;
int minint= Integer.MIN_VALUE;
long maxlong=Long.MAX_VALUE;
long minlong=Long.MIN_VALUE;
int[] arr;
boolean find(int a,int b){
if(a<10){
int p=arr[a]*10;
if(p>=b)return true;
}else{
int p=a%10;
a/=10;
p=arr[p]*10+arr[a];
if(p>=b)return true;
}return false;
}
/******************************************************************************************
*****************************************************************************************/
public void sol(){
int h=ni(),m=ni();
int[] ar={0,1,5,-1,-1,2,-1,-1,8,-1};
arr=ar;
String[] s=rl1().split(":");
int hr=Integer.parseInt(s[0]),min=Integer.parseInt(s[1]);
for(int i=hr;i<h;i++){
boolean f=true;
int p=i;
while(p>0){
int q=p%10;
if(ar[q]==-1){
f=!f;
break;
}
p=p/10;
}if(!f||(find(i,m)))continue;
if(i==hr){
for(int j=min;j<m;j++){
p=j;
f=true;
while(p>0){
int q=p%10;
if(ar[q]==-1){
f=!f;
break;
}
p=p/10;
}if(!f||(find(j,h)))continue;
else{
if(i<10&&j<10){
pl("0"+i+":0"+j);
}else if(i<10){
pl("0"+i+":"+j);
}else if(j<10){
pl(i+":0"+j);
}else pl(i+":"+j);
return;
}
}
}else{
for(int j=0;j<m;j++){
p=j;
f=true;
while(p>0){
int q=p%10;
if(ar[q]==-1){
f=!f;
break;
}
p=p/10;
}if(!f||find(j,h))continue;
else{
if(i<10&&j<10){
pl("0"+i+":0"+j);
}else if(i<10){
pl("0"+i+":"+j);
}else if(j<10){
pl(i+":0"+j);
}else pl(i+":"+j);
return;
}
}
}
}pl("00:00");
}
public static void main(String[] args)
{
Main g=new Main();
g.out=new PrintWriter(System.out);
g.sc=new FastReader();
int t=g.ni();
// int t=1;
while(t-->0)
g.sol();
g.out.flush();
}
/****************************************************************************************
*****************************************************************************************/
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 int ni(){
return sc.nextInt();
}public long nl(){
return sc.nextLong();
}public double nd(){
return sc.nextDouble();
}public char[] rl(){
return sc.nextLine().toCharArray();
}public String rl1(){
return sc.nextLine();
}
public void pl(Object s){
out.println(s);
}public void ex(){
out.println();
}
public void pr(Object s){
out.print(s);
}public String next(){
return sc.next();
}public long abs(long x){
return Math.abs(x);
}
public int abs(int x){
return Math.abs(x);
}
public double abs(double x){
return Math.abs(x);
}
public long pow(long x,long y){
return (long)Math.pow(x,y);
}
public int pow(int x,int y){
return (int)Math.pow(x,y);
}
public double pow(double x,double y){
return Math.pow(x,y);
}public long min(long x,long y){
return (long)Math.min(x,y);
}
public int min(int x,int y){
return (int)Math.min(x,y);
}
public double min(double x,double y){
return Math.min(x,y);
}public long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}public long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
void sort1(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
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);
}
}void sort(long[] a) {
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);
}
}void sort1(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a) {
l.add(i);
}
Collections.sort(l,Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
void sort(double[] a) {
ArrayList<Double> l = new ArrayList<>();
for (double i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}int swap(int a,int b){
return a;
}long swap(long a,long b){
return a;
}double swap(double a,double b){
return a;
}
boolean isPowerOfTwo (int x)
{
return x!=0 && ((x&(x-1)) == 0);
}boolean isPowerOfTwo (long x)
{
return x!=0 && ((x&(x-1)) == 0);
}public long max(long x,long y){
return (long)Math.max(x,y);
}
public int max(int x,int y){
return (int)Math.max(x,y);
}
public double max(double x,double y){
return Math.max(x,y);
}long sqrt(long x){
return (long)Math.sqrt(x);
}int sqrt(int x){
return (int)Math.sqrt(x);
}void input(int[] ar,int n){
for(int i=0;i<n;i++)ar[i]=ni();
}void input(long[] ar,int n){
for(int i=0;i<n;i++)ar[i]=nl();
}void fill(int[] ar,int k){
Arrays.fill(ar,k);
}void yes(){
pl("YES");
}void no(){
pl("NO");
}
int[] sieve(int n)
{
boolean prime[] = new boolean[n+1];
int[] k=new int[n+1];
for(int i=0;i<=n;i++) {
prime[i] = true;
k[i]=i;
}
for(int p = 2; p <=n; p++)
{
if(prime[p] == true)
{
// sieve[p]=p;
for(int i = p*2; i <= n; i += p) {
prime[i] = false;
// sieve[i]=p;
while(k[i]%(p*p)==0){
k[i]/=(p*p);
}
}
}
}return k;
}
int strSmall(int[] arr, int target)
{
int start = 0, end = arr.length-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] >= target) {
end = mid - 1;
}
else {
ans = mid;
start = mid + 1;
}
}
return ans;
} int strSmall(ArrayList<Integer> arr, int target)
{
int start = 0, end = arr.size()-1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr.get(mid) > target) {
start = mid + 1;
ans=start;
}
else {
end = mid - 1;
}
}
return ans;
}long mMultiplication(long a,long b)
{
long res = 0;
a %= mod;
while (b > 0)
{
if ((b & 1) > 0)
{
res = (res + a) % mod;
}
a = (2 * a) % mod;
b >>= 1;
}
return res;
}long nCr(int n, int r,
long p)
{
if (n<r)
return 0;
if (r == 0)
return 1;
long[] fac = new long[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;
}long power(long x, long y, long p)
{
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}long modInverse(long n, long p)
{
return power(n, p - 2, p);
}
public static class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + "," + y;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Double(x).hashCode() * 31 + new Double(y).hashCode();
}
public int compareTo(Pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
} | 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;
const int maxn=2e5+10;
const int mod=998244353;
#define ll long long
#define ull unsigned long long
#define pi pair<int,ll>
#define fi first
#define sc second
#define pb push_back
int h,m;
int check(int x)
{
int hour=x/m;
int minute=x-hour*m;
hour%=h;
minute%=m;
char d[4];
if(hour<10) d[0]='0',d[1]=hour+'0';
else d[0]='0'+hour/10,d[1]='0'+hour%10;
if(minute<10) d[2]='0',d[3]=minute+'0';
else d[2]='0'+minute/10,d[3]='0'+minute%10;
/*for(int i=0;i<4;i++) cout<<d[i];
cout<<'\n';*/
int a=0;
int b=0;
for(int i=0;i<4;i++)
{
if(d[i]=='3'||d[i]=='4'||d[i]=='6'||d[i]=='7'||d[i]=='9')
return 0;
if(i==0)
{
if(d[i]=='2')
b+=5;
else if(d[i]=='5')
b+=2;
else
b+=d[i]-'0';
}
else if(i==1)
{
if(d[i]=='2')
b+=50;
else if(d[i]=='5')
b+=20;
else
{
int y=d[i]-'0';
y*=10;
b+=y;
}
}
if(i==2)
{
if(d[i]=='2')
a+=5;
else if(d[i]=='5')
a+=2;
else
a+=d[i]-'0';
}
else if(i==3)
{
if(d[i]=='2')
a+=50;
else if(d[i]=='5')
a+=20;
else
{
int y=d[i]-'0';
y*=10;
a+=y;
}
}
}
//cout<<a<<" "<<b<<'\n';
if(a<h&&b<m)
{
cout<<d[0]<<d[1]<<":"<<d[2]<<d[3]<<'\n';
return 1;
}
return 0;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
while(t--)
{
cin>>h>>m;
string s;
cin>>s;
int H=(s[0]-'0')*10+(s[1]-'0');
int M=(s[3]-'0')*10+(s[4]-'0');
int now=H*m+M;
while(1)
{
if(check(now))
{
break;
}
now++;
}
}
}
| 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 | from sys import stdin
input = stdin.readline
def reflect(n):
a = n // 10
b = n % 10
s = 0
if b == 5:
s += 20
elif b == 2:
s += 50
else:
s += b * 10
if a == 5:
s += 2
elif a == 2:
s += 5
else:
s += a
return s
def next_reflectable(n, m, h):
#print(n, m, h)
for i in range(n, m):
#print(i)
if set(str(i)).issubset({'0','1','2','5','8'}) and reflect(i) < h:
#print("*", str(i))
return "0" + str(i) if i < 10 else str(i)
return "00"
for _ in range(int(input())):
h, m = map(int, input().split())
s = input().strip()
t, k = s.split(":")
#print(k)
q1 = next_reflectable(int(t), h, m)
if q1 == t:
q2 = next_reflectable(int(k), m, h)
#print("!", q2, k)
if q2 == "00" and k != "00":
#print("!!")
q1 = next_reflectable((int(t)+1) % h, h, m)
r = q1 + ":" + q2
else:
r = q1 + ":00"
print(r)
| 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 | """
___. .__ .__ .__ __ __ _________
_____ \_ |__ | |__ |__| _____| |__ ____ | | _| | __ \______ \
\__ \ | __ \| | \| |/ ___/ | \_/ __ \| |/ / |/ / / /
/ __ \| \_\ \ Y \ |\___ \| Y \ ___/| <| < / /
(____ /___ /___| /__/____ >___| /\___ >__|_ \__|_ \_____/____/
\/ \/ \/ \/ \/ \/ \/ \/_____/
"""
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.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(io.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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#endregion
MOD = 1000000007
#from collections import defaultdict as dd,Counter,deque
def si(): return input()
def ii(): return int(input())
def li(): return list(map(int,input().split()))
def mi(): return map(int,input().split())
def sout(v): print(v,end=' ')
def d2b(n): return bin(n).replace("0b","")
def twod(n,m,num):return [[num for x in range(m)] for y in range(n)]
def vow(): return ['a','e','i','o','u']
def let(): return [chr(i) for i in range(97,123)]
def gcd(x, y):
while y:
x, y = y, x % y
return x
def ispow2(x):
return (x and (not(x & (x - 1))))
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i: i+=1
else:
n //= i
factors.append(i)
if n > 1: factors.append(n)
return (list(factors))
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x: return mid
elif arr[mid] > x: return binary_search(arr, low, mid - 1, x)
else: return binary_search(arr, mid + 1, high, x)
else: return -1
def isvalid(ref,h,m,HH,MM):
if h<10:
hour='0'+str(h)
else:
hour=str(h)
if m<10:
mins='0'+str(m)
else:
mins=str(m)
ref_hr=ref[hour[1]]+ref[hour[0]]
ref_min=ref[mins[1]]+ref[mins[0]]
# print(int(ref_min),int(ref_hr),hour,mins,HH,MM)
if int(ref_min[0])*10+int(ref_min[1])<HH and int(ref_hr[0])*10+int(ref_hr[1])<MM: return hour+':'+mins
return False
t=ii()
while t:
t-=1
HH,MM=mi()
a=si()
exc=[3,4,6,7,9]
reflection={'1':'1','2':'5','5':'2','8':'8','0':'0'}
if a[0]=='0':
hour=int(a[1])
else:
hour=int(a[0])*10+int(a[1])
if a[3]=='0':
mins=int(a[4])
else:
mins=int(a[3])*10+int(a[4])
ans='00:00'
# print(hour,mins)
f=0
for h in range(hour,HH):
if h==hour: x=mins
else: x=0
if h%10 in exc: continue
if (h//10)%10 in exc: continue
for m in range(x,MM):
if m%10 in exc: continue
if (m//10)%10 in exc: continue
# print(h,m)
b=isvalid(reflection,h,m,HH,MM)
# print(b,'after return')
if b:
f=1
ans=b
break
if f==1: break
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 | def refPos(twodigitstr):
se = {'1':'1','0':'0','8':'8','2':'5','5':'2'}
a, b = twodigitstr[0], twodigitstr[1]
if a in se and b in se:
return ''.join([se[b], se[a]])
return False
for _ in range(int(input())):
H, M = map(int, input().split())
s = input()
ans = refPos(s[:2])
flag = False
if ans:
if int(ans)<M:
for m in range(int(s[3:]), M):
strM = '0'*(2-len(str(m))) + str(m)
ans1 = refPos(strM)
if ans1:
if int(ans1)<H:
flag = True
print(s[:3]+strM)
break
if not flag:
for h in range(int(s[:2])+1, H):
strH = '0' * (2 - len(str(h))) + str(h)
ans = refPos(strH)
if ans:
if int(ans)<M:
flag = True
print(strH+':'+'00')
break
if not flag:
print('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 | import java.util.*;
// 1:无需package
// 2: 类名必须Main, 不可修改
public class Main {
public static class node {
public Integer a;
public String name;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = Integer.valueOf(in.nextLine());
HashMap<Integer, Integer> map = new HashMap<>();
map.put(0, 0);
map.put(1, 1);
map.put(2, 5);
map.put(8, 8);
map.put(5, 2);
while (t-- > 0) {
String line = in.nextLine();
String[] split = line.split(" ");
int h = Integer.valueOf(split[0]);
int m = Integer.valueOf(split[1]);
line = in.nextLine();
split = line.split(":");
int hh = Integer.valueOf(split[0]);
int mm = Integer.valueOf(split[1]);
for (int i = 0; i < m * h; i++) {
int h1 = hh / 10;
int h2 = hh % 10;
int m1 = mm / 10;
int m2 = mm % 10;
if (map.get(h2) == null || map.get(h1) == null || map.get(m1) == null || map.get(m2) == null) {
mm = mm + 1;
int tmp = mm / m;
mm = mm % m;
hh = hh + tmp;
hh = hh % h;
continue;
}
int nm = map.get(h2) * 10 + map.get(h1);
int nh = map.get(m2) * 10 + map.get(m1);
if (nh < h && nm < m) {
System.out.printf("%02d:%02d\n", hh, mm);
break;
}
mm = mm + 1;
int tmp = mm / m;
mm = mm % m;
hh = hh + tmp;
hh = hh % h;
}
}
}
} | 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 {
private static final boolean TEST_MODE = true;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = getInt(br);
for (int t=0; t<T; t++) {
int[] val = getIntArray(2, br);
String startTime = br.readLine();
process(val[0], val[1], startTime);
}
}
private static void process(int H, int M, String startTimeString) throws Exception {
Clock currTime = new Clock(startTimeString);
while (!currTime.isReflectable()
|| !currTime.isValidTime(H, M)
|| !currTime.getReflection().isValidTime(H, M)) {
// System.out.println(currTime + " || " + currTime.getReflection());
currTime = currTime.getNextTime(true);
}
// System.out.println("RESULT: " + currTime + " || " + currTime.getReflection());
System.out.println(currTime);
}
private static Integer getInt(BufferedReader br) throws Exception {
return Integer.parseInt(br.readLine());
}
private static Long getLong(BufferedReader br) throws Exception {
return Long.parseLong(br.readLine());
}
private static int[] getIntArray(int N, BufferedReader br) throws Exception {
String s = br.readLine();
String[] tokens = s.split(" ");
int[] result = new int[N];
for (int i=0; i<N; i++) {
result[i] = Integer.parseInt(tokens[i]);
}
return result;
}
private static long[] getLongArray(int N, BufferedReader br) throws Exception {
String s = br.readLine();
String[] tokens = s.split(" ");
long[] result = new long[N+1];
for (int i=0; i<N; i++) {
result[i+1] = Long.parseLong(tokens[i]);
}
return result;
}
private static void printArray(String message, Object[] arr) {
if (!TEST_MODE) {
return;
}
System.out.print(message + " : ");
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
class Clock {
int H1;
int H2;
int M1;
int M2;
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
return builder.append(H1).append(H2).append(":").append(M1).append(M2).toString();
}
// Accepts time in the HH:MM format.
public Clock(String clockTime) {
this.H1 = clockTime.charAt(0) - '0';
this.H2 = clockTime.charAt(1) - '0';
this.M1 = clockTime.charAt(3) - '0';
this.M2 = clockTime.charAt(4) - '0';
}
public Clock(int H1, int H2, int M1, int M2) {
this.H1 = H1;
this.H2 = H2;
this.M1 = M1;
this.M2 = M2;
}
public boolean isReflectable() {
return (isReflectableDigit(H1)
&& isReflectableDigit(H2)
&& isReflectableDigit(M1)
&& isReflectableDigit(M2));
}
public boolean isValidTime(int hoursInADay, int minInAHour) {
int hours = H1 * 10 + H2;
int minutes = M1 * 10 + M2;
return ((hours < hoursInADay) && (minutes < minInAHour));
}
public Clock getReflection() {
if (!isReflectable()) {
return null;
}
int newH1 = getReflection(M2);
int newH2 = getReflection(M1);
int newM1 = getReflection(H2);
int newM2 = getReflection(H1);
return new Clock(newH1, newH2, newM1, newM2);
}
/**
* Returns the next closest time on the clock.
* If this needs to be reflectable, {@param reflectableRequired} is honoured.
*
* NOTE: Validity check needs to happen outside. Something like:
* {@code while(!clock.isValidTime(H, M)) { clock = clock.getNextTime(false)}}
*/
public Clock getNextTime(boolean reflectableRequired) {
// Increment till we get something valid and reflectable.
int newH1 = H1, newH2 = H2, newM1 = M1, newM2 = M2;
boolean M1Carry = false, H2Carry = false, H1Carry = false;
// Always increment lowest digit.
newM2 = getNextDigit(this.M2, reflectableRequired);
if (newM2 < this.M2) {
M1Carry = true;
}
if (M1Carry || (reflectableRequired && !isReflectableDigit(M1))) {
newM2 = 0;
newM1 = getNextDigit(this.M1, reflectableRequired);
if (newM1 < this.M1) {
H2Carry = true;
}
}
if (H2Carry || (reflectableRequired && !isReflectableDigit(H2))) {
newM1 = 0;
newM2 = 0;
newH2 = getNextDigit(this.H2, reflectableRequired);
if (newH2 < this.H2) {
H1Carry = true;
}
}
if (H1Carry || (reflectableRequired && !isReflectableDigit(H1))) {
newM1 = 0;
newM2 = 0;
newH2 = 0;
newH1 = getNextDigit(this.H1, reflectableRequired);
}
return new Clock(newH1, newH2, newM1, newM2);
}
private boolean isReflectableDigit(int x) {
switch(x) {
case 0:
case 1:
case 2:
case 5:
case 8: return true;
}
return false;
}
private int getReflection(int x) {
switch(x) {
case 0: return 0;
case 1: return 1;
case 2: return 5;
case 5: return 2;
case 8: return 8;
}
throw new RuntimeException();
}
private int getNextDigit(int x, boolean reflectable) {
if (!reflectable) {
return (x + 1) % 10;
}
switch(x) {
case 0: return 1;
case 1: return 2;
case 2:
case 3:
case 4: return 5;
case 5:
case 6:
case 7: return 8;
case 8:
case 9: return 0;
}
throw new RuntimeException();
}
}
| 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 | //package codeforces;
import java.util.Scanner;
public class PlanetLapituletti {
private static class Clock {
int h, m;
public Clock(int h, int m) {
this.h = h;
this.m = m;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
for(; t > 0; t--) {
Clock maxClock = new Clock(scan.nextInt(), scan.nextInt());
String s = scan.next();
int currentH = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0');
int currentM = (s.charAt(3) - '0') * 10 + (s.charAt(4) - '0');
Clock currentClock = new Clock(currentH, currentM);
while(! isReversable(currentClock, maxClock) ) {
nextClock(currentClock, maxClock);
}
System.out.println(currentClock.h / 10 + "" + currentClock.h % 10 + ":"
+currentClock.m / 10 + "" + currentClock.m % 10);
}
scan.close();
}
private static void nextClock(Clock currentClock, Clock maxClock) {
currentClock.m++;
if (currentClock.m == maxClock.m) {
currentClock.m = 0;
currentClock.h ++; // carry
if (currentClock.h == maxClock.h)
currentClock.h = 0;
}
}
private static boolean isReversable(Clock currentClock, Clock maxClock) {
Clock reversed = reverse(currentClock);
if (reversed != null) {
if (reversed.h < maxClock.h && reversed.m < maxClock.m) {
return true;
}
}
return false;
}
private static Clock reverse(Clock currentClock) {
Integer h = reverseNumber(currentClock.h);
Integer m = reverseNumber(currentClock.m);
if (h != null && m != null) {
return new Clock(m, h);
}
return null;
}
private static Integer reverseNumber(int x) {
Character left = reverseDigit(x / 10);
Character right = reverseDigit(x % 10);
if (left != null && right != null) {
return right * 10 + left;
}
return null;
}
private static Character reverseDigit(int d) {
switch(d) {
case 0: return 0;
case 1: return 1;
case 2: return 5;
case 5: return 2;
case 8: return 8;
}
return null;
}
}
| 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 Main{
static int[] codes= {0,1,5,-1,-1,2,-1,-1,8,-1};
public static boolean check(int nh,int nm,int h,int m) {
if(codes[nh/10]==-1||codes[nh%10]==-1||codes[nm/10]==-1||codes[nm%10]==-1) {
return false;
}
int mm=codes[nh%10]*10+codes[nh/10];
int hh=codes[nm%10]*10+codes[nm/10];
return hh<h&&mm<m;
}
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();
scn.nextLine();
char []arr=scn.nextLine().toCharArray();
int nh=(arr[0]-'0')*10+(arr[1]-'0');
int nm=(arr[3]-'0')*10+(arr[4]-'0');
while(nh!=0||nm!=0) {
if(check(nh,nm,h,m)==true) {
break;
}
if(nm==m-1) {
nh=(nh+1)%h;
}
nm=(nm+1)%m;
}
System.out.println(nh/10+""+nh%10+":"+nm/10+""+nm%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 | // LAZY_LAD_69
using namespace std;
#include<bits/stdc++.h>
//DEFINE
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ll long long int
#define nl "\n"
#define forf(i,a,n) for(ll i=a;i<=n;i++)
#define forb(i,b,n) for(ll i=b;i>=n;i--)
#define pb push_back
#define vll vector<ll>
#define all(qw) qw.begin(),qw.end()
#define read(vec) ll qwe;cin>>qwe;vec.pb(qwe)
#define pll pair<ll,ll>
#define vpll vector<pll>
#define ff first
#define ss second
#define mp make_pair
#define sll set<ll>
#define inset(sett) ll qwer;cin>>qwer;sett.insert(qwer);
//FUNCTIONS
ll hcf(ll a, ll b)
{
if (b==0)return a;
return hcf(b, a % b);
}
ll lcm(ll a,ll b)
{
return (a*b)/hcf(a,b);
}
bool isprime(ll n) {
if(n==1)
{
return false;
}
for (ll i=2;i*i<=n;++i)
{
if(n%i==0)
{
return false;
}
}
return true;
}
void onlinejudge(){
#ifndef ONLINE_JUDGE
freopen("Input.txt", "r", stdin);
freopen("Output.txt", "w", stdout);
#endif // ONLINE_JUDGE
}
//SOLVE
void solve(){
ll h,m;
cin>>h>>m;
string t;
cin>>t;
ll hr,min;ll irmm=0,irhh=0;
string hh="ll",mm="ll";
string rmm="ll",rhh="ll";
hh[0]=t[0];hh[1]=t[1];
mm[0]=t[3];mm[1]=t[4];
hr=stoi(hh);
min=stoi(mm);
ll inhr=hr;
// cout<<hh<<nl;
while(1){
rhh[0]=mm[1];
rhh[1]=mm[0];
if(rhh[0]=='5') rhh[0]='2';
else if(rhh[0]=='2') rhh[0]='5';
if(rhh[1]=='5') rhh[1]='2';
else if(rhh[1]=='2') rhh[1]='5';
irhh=stoi(rhh);
//cout<<"IIRhh "<<rhh<<nl;
//cout<<min<<" "<<irhh<<nl;
if(mm[0]!='3' and mm[0]!='4' and mm[0]!='6' and mm[0]!='7' and mm[0]!='9' and
mm[1]!='3' and mm[1]!='4' and mm[1]!='6' and mm[1]!='7' and mm[1]!='9' and
min<m and irhh<h) break;
else {
min++;
mm=to_string(min);
if(mm.length()==1) mm="0"+mm;
if(min>=m){
mm="00";
min=0;
hr++;
hh=to_string(hr);
}
} if(hh.length()==1) hh="0"+hh;if(mm.length()==1) mm="0"+mm;
// cout<<"YES111"<<nl;
}
// cout<<"YES"<<nl;
//cout<<"hh"<<hh<<"!"<<nl;
while(1){
rmm[0]=hh[1];
rmm[1]=hh[0];
// cout<<"yss1 "<<rmm<<nl;
if(rmm[0]=='5') rmm[0]='2';
else if(rmm[0]=='2') rmm[0]='5';
if(rmm[1]=='5') rmm[1]='2';
else if(rmm[1]=='2') rmm[1]='5';
// cout<<"yss "<<rmm<<nl;
//cout<<"hh"<<hh[1]<<"!"<<nl;
// cout<<"rmm"<<rmm<<nl;
irmm=stoi(rmm);
if(hh[0]!='3' and hh[0]!='4' and hh[0]!='6' and hh[0]!='7' and hh[0]!='9' and
hh[1]!='3' and hh[1]!='4' and hh[1]!='6' and hh[1]!='7' and hh[1]!='9' and
hr<h and irmm<m
) break;
else {
hr++;
hh=to_string(hr);
if(hh.length()==1) hh="0"+hh;
if(hr>=h){
hh="00";
hr=0;
}
}if(hh.length()==1) hh="0"+hh;if(mm.length()==1) mm="0"+mm;
// cout<<"YS "<<hh<<nl;
}
// cout<<"YES"<<nl;
if(hr!=inhr) mm="00";
cout<<hh<<":"<<mm<<nl;
}
//MAIN
int main(){
//onlinejudge();
fastio
ll ttt;ttt=1;
cin>>ttt;
while(ttt--) solve();
return 0;
}
// CHECK FOR EXTREME CASES AND ZEROS;
| 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.lang.*;
import java.util.*;
import java.io.*;
public class Main {
static FastScanner in = new FastScanner();
static int[] v = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1};
static int compute(int x) {
String s = String.valueOf(x);
if (s.length() == 1)
s = "0" + s;
String ans = "";
for (int i = 1; i >= 0; --i) {
if (v[s.charAt(i) - '0'] == -1)
return Integer.MAX_VALUE;
ans += (char)(v[s.charAt(i) - '0'] + '0');
}
return Integer.parseInt(ans);
}
static String good(int x) {
String ans = String.valueOf(x);
if (x < 10)
ans = "0" + ans;
return ans;
}
static void solve() {
int h = in.nextInt(), m = in.nextInt();
char[] s = in.next().toCharArray();
int currH = (s[0] - '0') * 10 + (s[1] - '0');
int currM = (s[3] - '0') * 10 + (s[4] - '0');
while (true) {
if (currM == m) {
++currH;
currM = 0;
}
if (currH == h)
currH = 0;
if (compute(currM) < h && compute(currH) < m) {
System.out.println(good(currH) + ":" + good(currM));
return;
}
++currM;
}
}
public static void main(String[] args) {
int T = in.nextInt();
while (T-- > 0)
solve();
}
static class Pair<X, Y> {
X x;
Y y;
public Pair(X x, Y y) {
this.x = x;
this.y = y;
}
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
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 | #pragma GCC optimize("Ofast")
#pragma GCC optimization("unroll-loops")
#pragma GCC target("avx,avx2,fma")
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define deb(x) cout << #x << " " << x << endl;
#define mod 1000000007
#define mod2 998244353
#define fast std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
#define endl "\n"
#define all(x) (x).begin(), (x).end()
#define rall(v) v.rbegin(), v.rend()
const ll INF = 1e18;
const ll NEGINF = -1 * INF;
ll gcd(ll a, ll b)
{
if (b == 0)
{
return a;
}
return gcd(b, a % b);
}
ll my_pow(ll a, ll n, ll m = INF)
{
ll res = 1;
while (n)
{
if (n % 2)
{
res = (res * a) % m;
n--;
}
a = (a * a) % m;
n /= 2;
}
return res;
}
int h, m;
map<int, int> mp;
bool isValid(int H, int M)
{
int h1 = H / 10;
if (mp.find(h1) == mp.end())
{
return false;
}
int h2 = H % 10;
if (mp.find(h2) == mp.end())
{
return false;
}
int m1 = M / 10;
if (mp.find(m1) == mp.end())
{
return false;
}
int m2 = M % 10;
if (mp.find(m2) == mp.end())
{
return false;
}
int newH1 = mp[m2];
int newH2 = mp[m1];
int newM1 = mp[h2];
int newM2 = mp[h1];
int newHr = newH1 * 10 + newH2;
int newMin = newM1 * 10 + newM2;
if (newHr < h && newMin < m)
{
return true;
}
else
{
return false;
}
}
void solve()
{
cin >> h >> m;
string s;
cin >> s;
mp[0] = 0;
mp[1] = 1;
mp[2] = 5;
mp[5] = 2;
mp[8] = 8;
int hr = (s[0] - '0') * 10 + (s[1] - '0');
int min = (s[3] - '0') * 10 + (s[4] - '0');
// deb(hr);
// deb(min);
while (true)
{
if (isValid(hr, min))
{
if (hr <= 9)
{
cout << 0;
}
cout << hr << ":";
if (min <= 9)
{
cout << 0;
}
cout << min;
cout << endl;
return;
}
else
{
min++;
if (min == m)
{
min = 0;
hr++;
if (hr == h)
{
hr = 0;
}
}
}
}
}
int main()
{
fast;
#ifndef ONLINE_JUDGE
freopen("/home/kalit/Desktop/Data Structures-Algo-Competitive/src/codeforces/input.txt", "r", stdin);
freopen("/home/kalit/Desktop/Data Structures-Algo-Competitive/src/codeforces/output.txt", "w", stdout);
#endif
int T = 1;
cin >> T;
while (T--)
{
solve();
}
//cout<< "Done in " << clock() / CLOCKS_PER_SEC <<"sec"<< 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 | import java.io.*;
import java.util.*;
public class dung {
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
public static void main(String[] args) throws IOException {
// code from here
int t = in.nextInt();
while (t-- > 0) {
solve();
}
// solve();
out.close();
}
private static void solve() {
int th = in.nextInt();
int tm = in.nextInt();
String ct = in.next();
int ph = Integer.parseInt(ct.substring(0, 2));
int pm = Integer.parseInt(ct.substring(3));
// set containing possible times
boolean[] set = new boolean[10];
set[0] = set[1] = set[2] = set[5] = set[8] = true;
for (int m = pm, h = ph;; m++) {
if (m == tm) {
m = 0;
h++;
if (h == th) {
h = 0;
}
}
if (check(set, h, m)) {
if (isValid(th, tm, h, m)) {
StringBuilder sb = new StringBuilder();
if (h < 10) {
sb.append(0);
}
sb.append(h);
sb.append(":");
if (m < 10) {
sb.append(0);
}
sb.append(m);
out.println(sb.toString());
return;
}
}
}
}
private static boolean isValid(int h, int m, int ch, int cm) {
int revh = rev(cm);
int revm = rev(ch);
if ((revh >= 0 && revh < h) && (revm >= 0 && revm < m)) {
return true;
}
return false;
}
private static int rev(int n) {
int res = 0;
int cod = 2;
while (n != 0) {
int rem = (n % 10);
if(rem==2) {
rem=5;
}else if(rem==5) {
rem=2;
}
res = res * 10 + rem;
n /= 10;
cod--;
}
while (cod-- > 0) {
res *= 10;
}
return res;
}
private static boolean check(boolean[] set, int ch, int cm) {
while (ch != 0) {
int rem = ch % 10;
if (!set[rem]) {
return false;
}
ch /= 10;
}
while (cm != 0) {
int rem = cm % 10;
if (!set[rem]) {
return false;
}
cm /= 10;
}
return true;
}
private static int getMax(int[] arr, int s, int e) {
int maxi = s;
for (int i = s + 1; i <= e; i++) {
if (arr[i] > arr[maxi]) {
maxi = i;
}
}
return maxi;
}
private static boolean[] sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// int[] arr = new int[n];
// int j = 0;
// for (int i = 2; i <= n; i++) {
// if (prime[i] == true)
// arr[j++] = i;
// }
return prime;
}
private static long lcm(long n1, long n2) {
return (n1 * n2) / gcd(n1, n2);
}
private static long gcd(long num1, long num2) {
if (num2 == 0) {
return num1;
}
return gcd(num2, num1 % num2);
}
private static int lcm(int n1, int n2) {
return (n1 * n2) / gcd(n1, n2);
}
private static int gcd(int num1, int num2) {
if (num2 == 0) {
return num1;
}
return gcd(num2, num1 % num2);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public String nextLine() throws IOException {
return reader.readLine().trim();
}
}
} | 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 check(a,B):
d = {0:0,1:1,2:5,5:2,8:8}
temp2= 0
if a//10 in d and a%10 in d:
temp2 = d[a//10] + d[a%10]*10
if temp2>=B:
return 0
else:
return 0
return 1
t = int(input())
for i in range(t):
H,M = [int(i) for i in input().split()]
h,m = [int(i) for i in input().split(":")]
while(check(h,M)==0 or check(m,H)==0):
if m==M-1:
m=0
if h==H-1:
h=0
else:
h+=1
else:
m+=1
ans=''
if h<10:
ans+='0'+str(h)
else:
ans+=str(h)
ans+=':'
if m<10:
ans+='0'+str(m)
else:
ans+=str(m)
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 | import io
import os
from collections import Counter, defaultdict, deque
reflect = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
valid = {}
for h1 in [0, 1, 2, 5, 8]:
for h2 in [0, 1, 2, 5, 8]:
h = h1 * 10 + h2
flip = reflect[h2] * 10 + reflect[h1]
valid[h] = flip
def makeClock(h, m):
return str(h).zfill(2) + ":" + str(m).zfill(2)
def solve(H, M, S):
x, y = map(int, S.split(":"))
while True:
# print(x, y)
if x in valid and y in valid:
h = valid[y]
m = valid[x]
if 0 <= h < H and 0 <= m < M:
return makeClock(x, y)
y += 1
if y == M:
y = 0
x += 1
if x == H:
x = 0
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
H, M = [int(x) for x in input().split()]
S = input().decode().rstrip()
ans = solve(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;
vector < int > go = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1};
int inf = 1e9 + 7;
int get(int x) {
string s = to_string(x);
if ((int)s.size() == 1) s = "0" + s;
string answ = "";
for (int i = 1; i >= 0; --i) {
if (go[s[i] - '0'] == -1) return inf;
answ += char(go[s[i] - '0'] + '0');
}
return stoi(answ);
}
string good(int x) {
string ans = to_string(x);
if (x < 10) {
ans = "0" + ans;
}
return ans;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t, h, m, H, M;
cin >> t;
string s;
while (t--) {
cin >> h >> m;
cin >> s;
H = (s[0] - '0') * 10 + s[1] - '0';
M = (s[3] - '0') * 10 + s[4] - '0';
while (1) {
if (M == m) {
H++, M = 0;
}
if (H == h) {
H = 0;
}
if (get(M) < h && get(H) < m) {
cout << good(H) << ":" << good(M) << '\n';
break;
}
M++;
}
}
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.Scanner;
public class B {
private static int[] invs = new int[]{0, 1, 5, -1, -1, 2, -1, -1, 8, -1};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int H = in.nextInt();
int M = in.nextInt();
String time = in.next();
String[] tokens = time.split(":");
int start = M * Integer.parseInt(tokens[0]) + Integer.parseInt(tokens[1]);
while (!isOk(start, H, M)) {
++start;
start %= M * H;
}
System.out.println(String.format("%02d:%02d", start / M, start % M));
}
}
private static boolean isOk(int x, int H, int M) {
x = x % (H * M);
int h = x / M;
int m = x % M;
int fh = flip(h);
int fm = flip(m);
return 0 <= fh && fh < M && 0 <= fm && fm < H;
}
private static int flip(int x) {
int f1 = invs[x % 10];
int f2 = invs[x / 10];
return (f1 < 0 || f2 < 0) ? -1 : f1 * 10 + f2;
}
}
| 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 codeforces {
public static boolean valid(int h,int m,int h2,int m2) {
int h3=0;
int m3=0;
int c=h2%10;
h2/=10;
if(c==0||c==1||c==8) {
m3+=c;
m3*=10;
}else if(c==5) {
m3+=2;
m3*=10;
}else if(c==2) {
m3+=5;
m3*=10;
}else {
return false;
}
c=h2%10;
if(c==0||c==1||c==8) {
m3+=c;
}else if(c==5) {
m3+=2;
}else if(c==2){
m3+=5;
}else {
return false;
}
c=m2%10;
m2/=10;
if(c==0||c==1||c==8) {
h3+=c;
h3*=10;
}else if(c==5) {
h3+=2;
h3*=10;
}else if(c==2) {
h3+=5;
h3*=10;
}else {
return false;
}
c=m2%10;
if(c==0||c==1||c==8) {
h3+=c;
}else if(c==5) {
h3+=2;
}else if(c==2){
h3+=5;
}else {
return false;
}
return h3<h&&m3<m;
}
// public static void pr(int h2,int m2) {
//
// int h3=0;
// int m3=0;
// int c=h2%10;
// h2/=10;
// if(c==0||c==1||c==8) {
// m3+=c;
// m3*=10;
// }else if(c==5) {
// m3+=2;
// m3*=10;
// }else if(c==2) {
// m3+=5;
// m3*=10;
// }
//
// c=h2%10;
// if(c==0||c==1||c==8) {
// m3+=c;
// }else if(c==5) {
// m3+=2;
// }else if(c==2){
// m3+=5;
// }
//
//
// c=m2%10;
// m2/=10;
// if(c==0||c==1||c==8) {
// h3+=c;
// h3*=10;
// }else if(c==5) {
// h3+=2;
// h3*=10;
// }else if(c==2) {
// h3+=5;
// h3*=10;
// }
// c=m2%10;
// if(c==0||c==1||c==8) {
// h3+=c;
// }else if(c==5) {
// h3+=2;
// }else if(c==2){
// h3+=5;
// }
//
//
// pw.print(h3<10?"0"+h3:h3);
// pw.print(":");
// pw.print(m3<10?"0"+m3:m3);
// pw.println();
// }
public static void main(String[] args) throws Exception {
int t=sc.nextInt();
while(t-->0) {
int h=sc.nextInt();
int m=sc.nextInt();
String s=sc.next();
int a=Integer.parseInt(s.substring(0,2));
int b=Integer.parseInt(s.substring(3,5));
while(true) {
if(valid(h, m, a, b)) {
pw.print(a<10?"0"+a:a);
pw.print(":");
pw.print(b<10?"0"+b:b);
pw.println();
break;
}
b++;
if(b==m) {
b=0;
a++;
if(a==h) {
a=0;
}
}
}
}
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class pair implements Comparable<pair> {
long x;
long y;
public pair(long x, long y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Double(x).hashCode() * 31 + new Double(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
static class tuble implements Comparable<tuble> {
int x;
int y;
int z;
public tuble(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return x + " " + y + " " + z;
}
public int compareTo(tuble other) {
if (this.x == other.x) {
if (this.y == other.y) {
return this.z - other.z;
}
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
static long mod = 1000000007;
static Random rn = new Random();
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
} | 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.*;
import java.util.*;
import java.text.DecimalFormat;
public class Main {
static long mod=(long)1e9+7;
static long mod1=998244353;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int t= in.nextInt();
while(t-->0) {
int h=in.nextInt();
int m=in.nextInt();
char[] arr=in.next().toCharArray();
int hh=(arr[0]-'0')*10+(arr[1]-'0');
int mm=(arr[3]-'0')*10+arr[4]-'0';
ArrayList<Integer> valid=new ArrayList<>();
valid.add(0);
valid.add(1);
valid.add(2);
valid.add(5);
valid.add(8);
boolean present=false;
String ans="";
while(!present){
if(valid.contains(hh%10) && valid.contains(hh/10)){
if(valid.contains(mm%10) && valid.contains(mm/10)){
int h_new=getRev(mm);
int m_new=getRev(hh);
if(h_new<h && m_new<m) {
present = true;
String x=String.valueOf(hh);
String y=String.valueOf(mm);
if(x.length()==1)
x="0"+x;
if(y.length()==1)
y="0"+y;
ans=x+":"+y;
}
}
}
// out.println(ans);
mm=(mm+1);
if(mm==m)
{
mm=0;
hh=(hh+1)%h;
}
}
out.println(ans);
}
out.close();
}
static int getRev(int i){
int one=i%10;
int ten=i/10;
if(one==2)
{
one=5;
}
else if(one==5){
one=2;
}
if(ten==2)
ten=5;
else if(ten==5)
ten=2;
return one*10+ten;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static long gcd(long x, long y){
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = Math.max(x, y);
b = Math.min(x, y);
r = b;
while(a % b != 0){
r = a % b;
a = b;
b = r;
}
return r;
}
static long modulo(long a,long b,long c){
long x=1,y=a%c;
while(b > 0){
if(b%2 == 1)
x=(x*y)%c;
y = (y*y)%c;
b = b>>1;
}
return x%c;
}
public static void debug(Object... o){
System.err.println(Arrays.deepToString(o));
}
static String printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.00000000000");
return String.valueOf(ft.format(d));
}
static int countBit(long mask){
int ans=0;
while(mask!=0){
mask&=(mask-1);
ans++;
}
return ans;
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] readArray(int n)
{
int[] arr=new int[n];
for(int i=0;i<n;i++) arr[i]=nextInt();
return arr;
}
}
} | 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 pair<int, int> pii;
#define int long long int
bool isvalid( int H, int M, int h, int m )
{
string hour = to_string(M);
string minu = to_string(H);
reverse(hour.begin(), hour.end());
reverse(minu.begin(), minu.end());
if( hour.length() == 1 )
hour.push_back('0');
if( minu.length() == 1 )
minu.push_back('0');
for( auto &v: hour )
{
if( v == '2' )
{
v = '5';
}
else
{
if( v == '5' )
v = '2';
else
{
if( !( v == '0' || v == '1' || v =='8' ) )
return false;
}
}
}
for( auto &v: minu )
{
if( v == '2' )
{
v = '5';
}
else
{
if( v == '5' )
v = '2';
else
{
if( !( v == '0' || v == '1' || v =='8' ) )
return false;
}
}
}
int candH = stoi(hour), candM = stoi(minu);
return candH <= h && candM <= m;
}
int32_t main()
{
int T = 1;
cin>>T;
while( T-- )
{
int h, m;
cin>>h>>m;
string s;
cin>>s;
string ans = "00:00";
int H, M, pos;
H = stoi( s.substr(0, 2) );
s.erase(0, 3 );
M = stoi(s);
int flag = 0;
while( H < h )
{
while( M < m )
{
if( isvalid( H, M, h - 1, m - 1 ) )
{
string hora = to_string(H), minu = to_string(M);
if( hora.length() < 2 )
hora = "0" + hora;
if( minu.length() < 2 )
minu = "0" + minu;
ans = hora + ":" + minu;
flag = 1;
break;
}
M++;
}
if( flag == 1 )
break;
H++;
M = 0;
}
cout<<ans<<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()
while t:
t-=1;h,m=R();x,y=R(':');y+=x*m;u=v=w=q=N
while 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)
print(r) | 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 | reflected = { '0': '0', '1': '1', '2': '5', '3': '-', '4': '-', '5': '2', '6': '-', '7': '-', '8': '8', '9': '-', ':': ':' }
def getReflectedTime(originTime):
reflectedTime = ''.join(map(lambda digit: reflected[digit], originTime))[::-1]
if '-' in reflectedTime:
return None
return reflectedTime
def getNextMinute(hh, mm, h, m):
mm += 1
if mm == m:
mm = 0
hh += 1
if hh == h:
hh = 0
return (hh, mm)
def solve():
h, m = map(int, input().split())
currentTime = input()
hh, mm = map(int, currentTime.split(':'))
for _ in range(h*m):
displayedTime = '{:0>2d}:{:0>2d}'.format(hh, mm)
reflectedTime = getReflectedTime(displayedTime)
if reflectedTime is not None:
rhh, rmm = map(int, reflectedTime.split(':'))
if rhh < h and rmm < m:
print (displayedTime)
break
hh, mm = getNextMinute(hh, mm, h, m)
t = int(input())
for _ in range(t):
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<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<string>
#include<map>
#include<queue>
#include<vector>
#include<iomanip>
typedef long long ll;
#define re register
//#define inf INT32_MAX
//_LINE_ _TIME_ _DATE_
using namespace std;
const int M = 9e4 + 5;
const int N = 1e5 + 5;
const ll mod = 998244353;
const int inf = 2147483647;
inline void swap(int& a, int& b) {
int k = a;
a = b;
b = k;
}
int read() {
int res = 0, k = 1;
char c = getchar();
while ((c < '0' || c>'9') && c != '-') c = getchar();
if (c == '-') k = -1, c = getchar();
while (c >= '0' && c <= '9') res = res * 10 + c - '0', c = getchar();
return res * k;
}
ll llread() {
ll res = 0LL, k = 1LL;
char c = getchar();
while ((c < '0' || c>'9') && c != '-') c = getchar();
if (c == '-') k = -k, c = getchar();
while (c >= '0' && c <= '9') res = res * 10LL + (ll)(c - '0'), c = getchar();
return res * k;
}
//ll n, m, a[101][2001], tot = 1, f[101][202], sum[101];
int t, h, m, hh, mm, aa[15];
int check(int a, int b, int c, int d) {
int h1, h2, m1, m2;
h1 = b % 10;
h2 = b / 10;
m1 = a % 10;
m2 = a / 10;
//printf("%d %d %d %d\n", h1, h2, m1, m2);
if (aa[h1] == -1 || aa[h2] == -1 || aa[m1] == -1 || aa[m2] == -1) return 0;
//cout << a << " " << b << endl;
//cout << h1 * 10 + h2 << ":" << m1 * 10 + m2 << endl;
h1 = aa[h1], h2 = aa[h2], m1 = aa[m1], m2 = aa[m2];
if (h1 * 10 + h2 < c && m1 * 10 + m2 < d) return 1;
return 0;
}
int main() {
/*n = llread(), m = llread();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%lld", &a[i][j]);
sum[i] += a[i][j];
sum[i] %= mod;
}
}
for (int i = 1; i <= n; i++) {
tot = (sum[i] + 1) * tot % mod;
}
tot = (tot + mod - 1)%mod;
for (int j = 1; j <= m; j++) {
memset(f, 0, sizeof(f));
f[0][n] = 1;
for (int i = 1; i <= n; i++) {
for (int k = n - i; k <= n + i; k++) {
f[i][k] = (f[i-1][k] + f[i-1][k-1]*a[i][j]%mod)%mod +
f[i-1][k+1]*((sum[i]+mod-a[i][j])%mod)%mod;
f[i][k] %= mod;
}
}
for (int i = 1; i <= n; i++) {
tot = (tot + mod - f[n][n + i]) % mod;
}
}
printf("%lld", tot);*/
t = read();
for (int i = 0; i <= 10; i++) aa[i] = -1;
aa[0] = 0, aa[1] = 1, aa[2] = 5, aa[5] = 2, aa[8] = 8;
while (t) {
h = read(), m = read();
scanf("%d:%d", &hh, &mm);
//cout << hh << " " << mm << endl;
while (!check(hh, mm, h, m)) {
mm++;
hh += mm / m;
mm %= m;
hh %= h;
}
if (hh < 10)
cout << "0";
cout << hh;
cout << ":";
if (mm < 10)
cout << "0";
cout << mm;
cout << endl;
t--;
}
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.*;
import java.io.*;
public class B {
BufferedReader input;
BufferedWriter output;
StringTokenizer st;
private static float binarySearch(ArrayList<Long> arr, int start, int end, long x) {
if (end >= start) {
int mid = start + (end - start) / 2;
if (arr.get(mid) == x)
return mid;
if (arr.get(mid) > x)
return binarySearch(arr, start, mid - 1, x);
return binarySearch(arr, mid + 1, end, x);
}
return end+0.5f;
}
char reflect(char c){
switch (c){
case '2':return '5';
case '5':return '2';
}
return c;
}
boolean isValid(String s, int h, int m){
for (int i=0; i<s.length(); i++){
char c = s.charAt(i);
switch (c){
case ':':
case '0':
case '1':
case '2':
case '5':
case '8':
break;
default:
return false;
}
}
int hr = Integer.parseInt(reflect(s.charAt(4))+""+reflect(s.charAt(3)));
int min = Integer.parseInt(reflect(s.charAt(1))+""+reflect(s.charAt(0)));
return hr < h && min < m;
}
long timeInMs(int hr, int min, int minInHr){
return (((long) hr)*minInHr)+min;
}
String timeInString(int hr, int min){
String hs = hr<10 ? "0"+hr : ""+hr;
String ms = min<10 ? "0"+min : ""+min;
return hs+":"+ms;
}
// My Solution
void solve() throws IOException {
int t = getInt();
while (t-->0){
int h = getInt();
int m = getInt();
String s = input.readLine();
String[] times = s.split(":");
int hr = Integer.parseInt(times[0]);
int min = Integer.parseInt(times[1]);
ArrayList<Long> validTimes = new ArrayList<>();
for(int i=0; i<h; i++){
for (int j=0; j<m; j++){
if(isValid(timeInString(i, j), h, m)){
validTimes.add(timeInMs(i, j, m));
}
}
}
Collections.sort(validTimes);
long startTime = timeInMs(hr, min, m);
int index = (int) Math.ceil(binarySearch(validTimes, 0, validTimes.size()-1, startTime));
if(index==validTimes.size())
index = 0;
long ansInMs = validTimes.get(index);
String ans = timeInString((int)ansInMs/m, (int)ansInMs%m);
print(ans+"\n");
}
}
// Some basic functions
int min(int...i){
int min = Integer.MAX_VALUE;
for (int value : i) min = Math.min(min, value);
return min;
}
int max(int...i){
int max = Integer.MIN_VALUE;
for (int value : i) max = Math.max(max, value);
return max;
}
// Printing stuff
void print(int... i) throws IOException {
for (int value : i) output.write(value + " ");
}
void print(long... l) throws IOException {
for (long value : l) output.write(value + " ");
}
void print(String... s) throws IOException {
for (String value : s) output.write(value);
}
void nextLine() throws IOException {
output.write("\n");
}
// Taking Inputs
int[][] getIntMat(int n, int m) throws IOException {
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[i][j] = getInt();
return mat;
}
char[][] getCharMat(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++) {
String s = input.readLine();
for (int j = 0; j < m; j++)
mat[i][j] = s.charAt(j);
}
return mat;
}
int getInt() throws IOException {
if(st ==null || !st.hasMoreTokens())
st = new StringTokenizer(input.readLine());
return Integer.parseInt(st.nextToken());
}
int[] getInts(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = getInt();
return a;
}
long getLong() throws IOException {
if(st==null || !st.hasMoreTokens())
st = new StringTokenizer(input.readLine());
return Long.parseLong(st.nextToken());
}
long[] getLongs(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = getLong();
return a;
}
// Checks whether the code is running on OnlineJudge or LocalSystem
boolean isOnlineJudge() {
if (System.getProperty("ONLINE_JUDGE") != null)
return true;
try {
return System.getProperty("LOCAL")==null;
} catch (Exception e) {
return true;
}
}
// Handling CodeExecution
public static void main(String[] args) throws Exception {
new B().run();
}
void run() throws IOException {
// Defining Input Streams
if (isOnlineJudge()) {
input = new BufferedReader(new InputStreamReader(System.in));
output = new BufferedWriter(new OutputStreamWriter(System.out));
} else {
input = new BufferedReader(new FileReader("input.txt"));
output = new BufferedWriter(new FileWriter("output.txt"));
}
// Running Logic
solve();
output.flush();
// Run example test cases
if (!isOnlineJudge()) {
BufferedReader output = new BufferedReader(new FileReader("output.txt"));
BufferedReader answer = new BufferedReader(new FileReader("answer.txt"));
StringBuilder outFile = new StringBuilder();
StringBuilder ansFile = new StringBuilder();
String temp;
while ((temp = output.readLine()) != null)
outFile.append(temp.trim());
while ((temp = answer.readLine()) != null)
ansFile.append(temp.trim());
if (outFile.toString().equals(ansFile.toString()))
System.out.println("Test Cases Passed!!!");
else
System.out.println("Failed...");
}
}
} | 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 D {
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
static int[] converter = new int[]{0, 1, 5, -1, -1, 2, -1, -1, 8, -1};
static int convert(int time) {
int digit1 = time%10;
time /= 10;
int digit2 = time;
int conv1 = converter[digit1];
int conv2 = converter[digit2];
if(conv1 == -1 || conv2 == -1) return -1;
return conv1 * 10 + conv2;
}
static void solve()
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int t = in.nextInt();
while(t-- > 0) {
int hours = in.nextInt();
int minutes = in.nextInt();
String[] string = in.readString().split(":");
int currentH = Integer.parseInt(string[0]);
int currentM = Integer.parseInt(string[1]);
while(true) {
int convertedH = convert(currentM);
int convertedM = convert(currentH);
// debug(currentH, ':', currentM, convertedH, ':', convertedM);
if(convertedH != -1 && convertedM != -1 && convertedH < hours && convertedM < minutes) {
String currentHS = currentH + "";
String currentMS = currentM + "";
if(currentHS.length() == 1) currentHS = "0" + currentHS;
if(currentMS.length() == 1) currentMS = "0" + currentMS;
out.println(currentHS + ":" + currentMS);
break;
}
currentM ++;
if(currentM == minutes) {
currentM = 0;
currentH++;
}
currentH %= hours;
}
}
out.close();
}
public static void main(String[] args) {
new Thread(null ,new Runnable(){
public void run()
{
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static int[][] graph(int from[], int to[], int n)
{
int g[][] = new int[n][];
int cnt[] = new int[n];
for (int i = 0; i < from.length; i++) {
cnt[from[i]]++;
cnt[to[i]]++;
}
for (int i = 0; i < n; i++) {
g[i] = new int[cnt[i]];
}
Arrays.fill(cnt, 0);
for (int i = 0; i < from.length; i++) {
g[from[i]][cnt[from[i]]++] = to[i];
g[to[i]][cnt[to[i]]++] = from[i];
}
return g;
}
static class Pair implements Comparable<Pair>{
int x,y;
Pair (int x,int y){
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
if (this.x == o.x)
return Integer.compare(this.y,o.y);
return Integer.compare(this.x,o.x);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Integer(x).hashCode() * 31 + new Integer(y).hashCode();
}
@Override
public String toString() {
return x + " " + y;
}
}
static String rev(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x, long y) {
if (y == 0) {
return x;
} else {
return gcd(y, x % y);
}
}
static int gcd(int x, int y) {
if (y == 0) {
return x;
} else {
return gcd(y, x % y);
}
}
static int abs(int a, int b) {
return (int) Math.abs(a - b);
}
static long abs(long a, long b) {
return (long) Math.abs(a - b);
}
static int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
static int min(int a, int b) {
if (a > b) {
return b;
} else {
return a;
}
}
static long max(long a, long b) {
if (a > b) {
return a;
} else {
return b;
}
}
static long min(long a, long b) {
if (a > b) {
return b;
} else {
return a;
}
}
static long pow(long n, long p, long m) {
long result = 1;
if (p == 0) {
return 1;
}
while (p != 0) {
if (p % 2 == 1) {
result *= n;
}
if (result >= m) {
result %= m;
}
p >>= 1;
n *= n;
if (n >= m) {
n %= m;
}
}
return result;
}
static long pow(long n, long p) {
long result = 1;
if (p == 0) {
return 1;
}
if (p == 1) {
return n;
}
while (p != 0) {
if (p % 2 == 1) {
result *= n;
}
p >>= 1;
n *= n;
}
return result;
}
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
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 = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} 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 String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(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;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
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 | #include <iostream>
#include <vector>
#include <iterator>
#include <unordered_map>
#include <map>
#include <algorithm>
#include <utility>
#include <string>
#include <stack>
#include <set>
using namespace std;
typedef long long ll;
set<int> st, stc;
bool checksym(int h1, int h2, int m1, int m2, int h, int m){
if(stc.count(h1)){h1 = h1==2? 5:2;}
if(stc.count(h2)){h2 = h2==2? 5:2;}
if(stc.count(m1)){m1 = m1==2? 5:2;}
if(stc.count(m2)){m2 = m2==2? 5:2;}
if(st.count(h1) && st.count(h2) && st.count(m1) && st.count(m2) && ((m2*10 + m1)<h) && ((h2*10 + h1)<m)){
return true;
}
return false;
}
int main(){
ll T;
cin>>T;
st.insert(0);
st.insert(1);
st.insert(2);
st.insert(5);
st.insert(8);
stc.insert(2);
stc.insert(5);
while(T--){
ll h, m, h1, h2, m1, m2;
cin>>h>>m;
string s;
cin>>s;
h1 = s[0]-'0';
h2 = s[1]-'0';
m1 = s[3]-'0';
m2 = s[4]-'0';
int cm = (h1*10 + h2)*m + m1*10 + m2;
while(!checksym(h1,h2,m1,m2,h,m)){
cm++;
h1 = ((cm/m)%h)/10;
h2 = ((cm/m)%h)%10;
m1 = (cm%m)/10;
m2 = (cm%m)%10;
}
cout<<h1<<h2<<":"<<m1<<m2<<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 | import sys
testing = len(sys.argv) == 4 and sys.argv[3] == "myTest"
if testing:
cmd = sys.stdout
from time import time
start_time = int(round(time() * 1000))
readAll = open(sys.argv[1], 'r').read
sys.stdout = open(sys.argv[2], 'w')
else:
readAll = sys.stdin.read
# ############ ---- I/O Functions ---- ############
flush = sys.stdout.flush
class InputData:
def __init__(self):
self.lines = readAll().split('\n')
self.n = len(self.lines)
self.ii = -1
def input(self):
self.ii += 1
assert self.ii < self.n
return self.lines[self.ii]
inputData = InputData()
input = inputData.input
def intin():
return(int(input()))
def intlin():
return(list(map(int,input().split())))
def chrin():
return(list(input()))
def strin():
return input()
def lout(l, sep="\n", toStr=True):
print(sep.join(map(str, l) if toStr else l))
# ############ ---- I/O Functions ---- ############
# from math import ceil
# from collections import defaultdict as ddict, Counter
# from heapq import *
# from Queue import Queue
dmap = {
'0': '0',
'1': '1',
'2': '5',
'5': '2',
'8': '8'
}
def check(h,m,hh,mm):
h1,h2 = hh
m1,m2 = mm
if (not h1 in dmap) or (not h2 in dmap) or (not m1 in dmap) or (not m2 in dmap):
return False
h1 = dmap[h1]
h2 = dmap[h2]
m1 = dmap[m1]
m2 = dmap[m2]
h1,h2,m1,m2 = [m2,m1,h2,h1]
H = int(''.join([h1,h2]))
M = int(''.join([m1,m2]))
return (H < h) and (M < m)
def add(h,m,hh,mm):
h1,h2 = hh
m1,m2 = mm
H = int(''.join([h1,h2]))
M = int(''.join([m1,m2]))
M += 1
if M == m:
M = 0
H += 1
if H == h:
H = 0
return str(H).zfill(2), str(M).zfill(2)
def main():
h,m = intlin()
hh,mm = strin().split(':')
while not check(h,m,hh,mm):
hh,mm = add(h,m,hh,mm)
print(':'.join([hh,mm]))
for _ in xrange(intin()):
main()
# ans = main()
# print("YES" if ans else "NO")
# if ans:
# lout(ans, ' ')
# main()
if testing:
sys.stdout = cmd
print(int(round(time() * 1000)) - start_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 | // God put a smile upon your face <3
#include <bits/stdc++.h>
#define slld(longvalue) scanf("%lld", &longvalue)
#define ll long long
#define ull unsigned long long
#define pll pair < long long, long long >
#define fastio ios_base:: sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define pb push_back
#define bug printf("BUG\n")
#define mxlld LLONG_MAX
#define mnlld -LLONG_MAX
#define mxd 2e8
#define mnd -2e8
#define pi 3.14159265359
using namespace std;
bool check(ll n, ll pos)
{
return n & (1LL << pos);
}
ll Set(ll n, ll pos)
{
return n = n | (1LL << pos);
}
bool invalid(ll x)
{
while(x)
{
ll y = x % 10;
x /= 10;
if(y == 3 || y == 4 || y == 6 || y == 7 || y == 9) return 1;
}
return 0;
}
ll mirror(ll x)
{
ll ret = 0;
ll cnt = 2;
while(cnt--)
{
ret *= 10;
ll y = x % 10;
x /= 10;
if(y == 1) ret += 1;
if(y == 2) ret += 5;
if(y == 5) ret += 2;
if(y == 8) ret += 8;
if(y == 0) ret += 0;
}
return ret;
}
bool isvalid(ll hh, ll mm, ll h, ll m)
{
if(invalid(hh)) return 0;
if(invalid(mm)) return 0;
hh = mirror(hh);
mm = mirror(mm);
swap(hh,mm);
if(hh >= h) return 0;
if(mm >= m) return 0;
return 1;
}
void next(ll &hh, ll &mm, ll h, ll m)
{
mm++;
if(mm == m)
{
mm = 0;
hh++;
}
if(hh == h)
{
hh = 0;
}
return;
}
int main()
{
ll i, j, k, l, m, n, o, r, q;
ll testcase;
ll input, flag, tag, ans;
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
slld(testcase);
for(ll cs = 1; cs <= testcase; cs++)
{
ll hh, mm, h, m;
char c;
cin >> h >> m >> hh >> c >> mm;
// cout << hh << " ++++ " << mm << " " << cs << endl;
while(isvalid(hh,mm,h,m) == 0)
{
next(hh,mm,h,m);
// break;
}
bool on1 = 0, on2 = 0;
if(hh < 10) on1 = 1;
if(mm < 10) on2 = 1;
if(on1) cout << 0;
cout << hh << ":";
if(on2) cout << 0;
cout << mm << "\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 java.util.*;
import java.io.*;
public class B {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int T = sc.nextInt();
PrintWriter pw = new PrintWriter(System.out);
while(T-->0) {
int h = sc.nextInt();
int m = sc.nextInt();
String[] s = sc.next().split(":");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
while(!check(a, b, h, m)) {
b++;
if(b >= m) {
b = 0;
a++;
if(a >= h) {
a = 0;
}
}
}
String res = String.format("%2d:%2d",a, b).replaceAll(" ","0");
System.out.println(res);
}
}
static int[] inv = {0, 1, 5, -1, -1, 2, -1, -1, 8, -1};
static boolean check(int a, int b, int h, int m) {
if(inv[a/10] < 0) return false;
if(inv[a%10] < 0) return false;
if(inv[b/10] < 0) return false;
if(inv[b%10] < 0) return false;
int newb = 10*inv[a%10]+inv[a/10];
int newa = 10*inv[b%10]+inv[b/10];
return newa < h && newb < m;
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.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 | """from math import *
from bisect import *
from collections import *
from random import *
from decimal import *"""
import sys
input=sys.stdin.readline
def inp():
return int(input())
def st():
return input().rstrip('\n')
def lis():
return list(map(int,input().split()))
def ma():
return map(int,input().split())
t=inp()
maa=set(['0','1','2','5','8'])
remap={'1':'1','2':'5','8':'8','0':'0','5':'2'}
while(t):
t-=1
h,m=ma()
b=input().split(':')
ch=int(b[0])
cm=int(b[1])
while(1):
chh=str(ch)
chh=chh.zfill(2)
cmm=str(cm)
cmm=cmm.zfill(2)
if(chh[0] in maa and chh[1] in maa and cmm[0] in maa and cmm[1] in maa):
chh1=remap[cmm[-1]]+remap[cmm[0]]
cmm1=remap[chh[-1]]+remap[chh[0]]
if(int(chh1)<h and int(cmm1)<m):
print(chh,":",cmm,sep='')
break
cm+=1
if(cm>=m):
cm=0
ch+=1
if(ch>=h):
ch=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.util.*;
import java.io.*;
import java.math.*;
/**
*
* @Har_Har_Mahadev
*/
public class B {
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
private static int N = 0;
private static HashMap<Integer, Integer> map;
public static void process() throws IOException {
int n = sc.nextInt(),m = sc.nextInt();
String curr = sc.next();
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);
// isValidM("01", 1);
int a = Integer.parseInt(""+curr.charAt(0)+""+curr.charAt(1));
int b = Integer.parseInt(""+curr.charAt(3)+""+curr.charAt(4));
while(!(isValid(a+"", m-1) && isValid(b+"", n-1))){
b++;
if(b == m) {
a++;
}
b%=m;
a%=n;
}
if((a+"").length() == 1) {
print("0"+a+":");
}
else print(a+":");
if((b+"").length() == 1) {
print("0"+b);
}
else print(b);
println();
}
private static boolean isValid(String str, int t) {
int n = str.length();
if(n == 1)str = "0"+str;
if(!map.containsKey(str.charAt(0) - '0'))return false;
if(!map.containsKey(str.charAt(1) - '0'))return false;
StringBuilder ff = new StringBuilder(str);
str = ff.reverse().toString();
StringBuilder val = new StringBuilder();
n = str.length();
for(int i = 0; i<(n); i++) {
int f1 = map.get(str.charAt(i) - '0');
val.append(f1);
}
int vv = Integer.parseInt(val.toString());
if(vv > t)return false;
return true;
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
static FastScanner sc;
static PrintWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new PrintWriter(System.out);
} else {
sc = new FastScanner(100);
out = new PrintWriter("output.txt");
}
int t = 1;
t = sc.nextInt();
while (t-- > 0) {
process();
}
out.flush();
out.close();
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Pair)) return false;
// Pair key = (Pair) o;
// return x == key.x && y == key.y;
// }
//
// @Override
// public int hashCode() {
// int result = x;
// result = 31 * result + y;
// return result;
// }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static void println(Object o) {
out.println(o);
}
static void println() {
out.println();
}
static void print(Object o) {
out.print(o);
}
static void pflush(Object o) {
out.println(o);
out.flush();
}
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static int max(int x, int y) {
return Math.max(x, y);
}
static int min(int x, int y) {
return Math.min(x, y);
}
static int abs(int x) {
return Math.abs(x);
}
static long abs(long x) {
return Math.abs(x);
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
static long max(long x, long y) {
return Math.max(x, y);
}
static long min(long x, long y) {
return Math.min(x, y);
}
public static int gcd(int a, int b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
public static long gcd(long a, long b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.longValue();
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
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;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(System.in));
}
FastScanner(int a) throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readArray(int n) throws IOException {
int[] A = new int[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextInt();
}
return A;
}
long[] readArrayLong(int n) throws IOException {
long[] A = new long[n];
for (int i = 0; i != n; i++) {
A[i] = sc.nextLong();
}
return A;
}
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
}
| 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 | /*
Powered by C++11.
Author : Alex_Wei.
*/
#include <bits/stdc++.h>
using namespace std;
//#pragma GCC optimize(3)
//#define int long long
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
using db = double;
using ld = long double;
using pii = pair <int,int>;
using pll = pair <ll,ll>;
using pdd = pair <double,double>;
using vint = vector <int>;
using vpii = vector <pii>;
#define fi first
#define se second
#define pb emplace_back
#define mpi make_pair
#define all(x) x.begin(),x.end()
#define sor(x) sort(all(x))
#define mem(x,v) memset(x,v,sizeof(x))
#define mcpy(x,y) memcpy(x,y,sizeof(y))
namespace IO{
char buf[1<<21],*p1=buf,*p2=buf,obuf[1<<23],*O=obuf;
#ifdef __WIN32
#define gc getchar()
#else
#define gc (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
#endif
#define pc(x) (*O++=x)
#define flush() fwrite(obuf,O-obuf,1,stdout)
inline int read(){
int x=0,sign=0; char s=gc;
while(!isdigit(s))sign|=s=='-',s=gc;
while(isdigit(s))x=(x<<1)+(x<<3)+(s-'0'),s=gc;
return sign?-x:x;
}
void print(int x){
if(x<0)return pc('-'),print(-x),void();
if(x>9)print(x/10);
pc(x%10+'0');
}
}
namespace math{
const int mod=99824353;
const int maxn=2e6+5;
ll ksm(ll a,ll b,ll p){
ll s=1,m=a%p;
while(b){
if(b&1)s=s*m%p;
m=m*m%p,b>>=1;
} return s;
} ll ksm(ll a,ll b){
ll s=1,m=a%mod;
while(b){
if(b&1)s=s*m%mod;
m=m*m%mod,b>>=1;
} return s;
} ll inv(ll x){return ksm(x,mod-2);}
ll fc[maxn],ifc[maxn];
void init_m(int n){
fc[0]=1;
for(int i=1;i<=n;i++)fc[i]=fc[i-1]*i%mod;
ifc[n]=inv(fc[n]);
for(int i=n-1;i>=0;i--)ifc[i]=ifc[i+1]*(i+1)%mod;
} ll C(ll n,ll m){return fc[n]*ifc[m]%mod*ifc[n-m]%mod;}
}
using namespace IO;
//using namespace math;
const int N=2e5+5;
const int inf=0x3f3f3f3f;
int h,m;
int rev(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 -1;
}
bool check(char a,char b,char c,char d){
int aa=rev(d-'0'),bb=rev(c-'0'),cc=rev(b-'0'),dd=rev(a-'0');
if(~aa&&~bb&&~cc&&~dd){
int hh=aa*10+bb,mm=cc*10+dd;
return hh<h&&mm<m;
} return 0;
}
void solve(){
char a,b,c,d;
cin>>h>>m>>a>>b>>c>>c>>d;
while(!check(a,b,c,d)){
d++;
if(d>'9')d='0',c++;
int mm=(c-'0')*10+d-'0';
if(mm>=m)c=d='0',b++;
if(b>'9')b='0',a++;
int hh=(a-'0')*10+b-'0';
if(hh>=h)a=b=c=d='0';
}
cout<<a<<b<<":"<<c<<d<<endl;
}
int main(){
int t=1;
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 | def r(str):
s =""
for i in str:
if(i=="2"):
s = "5" + s
elif(i=="5"):
s= "2" +s
else:
s = i +s
return s
def solve():
l1=list(input().split())
h = l1[0]
m = l1[1]
l2=list(input().split(":"))
h1 = l2[0]
m1 = l2[1]
valid = ["1","2","5","8","0","00","01","02","05","08","10","11","12","15","18","20","21","22","25","28","50","51","52","55","58","80","81","82","85","88","100"]
if(((h1 in valid) and (int(r(h1))<int(m)) )and ((m1 in valid) and (int(r(m1))<int(h)))):
print(h1+":"+m1)
elif(h1 not in valid or int(r(h1))>=int(m)):
while((h1 not in valid) or (int(r(h1))>=int(m)) ):
h1 = str((int(h1)+1) % int(h))
if(int(h1) in [0,1,2,3,4,5,6,7,8,9]):
h1 = "0"+h1
if(int(h1) in [0,1,2,5,8]):
print("0{}:00".format(int(h1)))
else:
print("{}:00".format(h1))
else:
while((m1 not in valid) or (int(r(m1))>=int(h))):
m1 = str((int(m1)+1)%int(m))
if(int(m1) in [0,1,2,3,4,5,6,7,8,9]):
m1 = "0"+m1
if(int(m1)==0):
break
if(int(m1)==0):
h1 = str((int(h1)+1) % int(h))
if(int(h1) in [0,1,2,3,4,5,6,7,8,9]):
h1 = "0"+h1
while((h1 not in valid) or (int(r(h1))>=int(m)) ):
h1 = str((int(h1)+1) % int(h))
if(int(h1) in [0,1,2,3,4,5,6,7,8,9]):
h1 = "0"+h1
if(int(h1) in [0,1,2,5,8]):
print("0{}:00".format(int(h1)))
else:
print("{}:00".format(h1))
else:
if(int(m1) in [1,2,5,8]):
print("{}:0{}".format(h1,int(m1)))
else:
print("{}:{}".format(h1,m1))
t =int(input())
while(t):
solve()
t =t-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 | #include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <string>
#include <random>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdio>
#include <numeric>
#include <iostream>
#include <algorithm>
#include <functional>
#include <unordered_map>
#include <unordered_set>
#define sca(aa) scanf("%d",&aa)
#define scal(aa) scanf("%lld",&aa)
#define lb(x) (x&-x)
#define mid ((s+e)>>1)
//#define int LL
#define ls (p<<1)
#define rs (p<<1|1)
//#define P(x) ((x)*(x))
#define lson ls,s,mid
#define rson rs,mid+1,e
#define IT set<node>::iterator
//#define getchar()(p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf = INT_MAX;
const int N = 2e5 + 100;
const LL MOD = 998244353;
const double eps = 1e-8;
const ull strmod = 212370440130137957ll;//ll11
const int strp = 233;
//char buf[1 << 21], * p1 = buf, * p2 = buf;
inline LL read() {
char ch = getchar(); LL x = 0, f = 1;
while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
while ('0' <= ch && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
return x * f;
}
int p[10] = { 0,1,5,-1,-1,2,-1,-1,8,-1 };
int l, r;
int H, M, h, m;
inline bool bad(int x) { return p[x % 10] == -1 || p[x / 10] == -1; }
inline int rev(int x) { return p[x % 10] * 10 + p[x / 10]; }
void solve()
{
int x = -1, y = -1;
for (int i = 0; i < H; i++)
for (int j = 0; j < M; j++)
if (!bad(i) && !bad(j) && rev(i) < M && rev(j) < H)
{
if (x == -1)
x = i, y = j;
if (i > h || (i == h && j >= m))
{
printf("%02d:%02d\n", i, j);
return;
}
}
printf("%02d:%02d\n", x, y);
return;
}
int main() {
int T;
cin >> T;
while (T--)
{
cin >> H >> M;
bool fg = 0;
scanf("%d:%d", &h, &m);
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.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class PlanetLapituletti {
public static Set<Integer> validDigits = new HashSet<>(Arrays.asList(0, 1, 2, 5, 8));
public static void main(String[] args) {
FastReader fs = new FastReader();
StringBuilder sb = new StringBuilder();
int t = fs.nextInt();
for(int tt = 0; tt < t; tt++) {
int h = fs.nextInt();
int m = fs.nextInt();
String[] time = fs.next().split(":");
int hours = Integer.parseInt(time[0]);
int minutes = Integer.parseInt(time[1]);
while(true) {
if(validTime(hours, minutes, h, m)) {
if(hours < 10) {
sb.append(0);
}
sb.append(hours);
sb.append(":");
if(minutes < 10) {
sb.append(0);
}
sb.append(minutes);
sb.append("\n");
break;
}else {
minutes++;
minutes %= m;
if(minutes == 0) {
hours++;
hours %= h;
}
}
}
}
System.out.println(sb.toString());
}
public static boolean validTime(int hours, int minutes, int h, int m) {
if(!validDigits.contains(hours % 10) || !validDigits.contains(hours / 10)) return false;
if(!validDigits.contains(minutes % 10) || !validDigits.contains(minutes / 10)) return false;
else {
int swap1 = 0;
int swap2 = 0;
if(hours < 10) {
if(hours == 5) swap1 = 20;
else if(hours == 2) swap1 = 50;
else swap1 = hours * 10;
}else {
while(hours > 0) {
int curr = hours % 10;
if(curr == 2) swap1 = (swap1 * 10) + 5;
else if(curr == 5) swap1 = (swap1 * 10) + 2;
else swap1 = (swap1 * 10) + curr;
hours /= 10;
}
}
if(minutes < 10) {
if(minutes == 5) swap2 = 20;
else if(minutes == 2) swap2 = 50;
else swap2 = minutes * 10;
}else {
while(minutes > 0) {
int curr = minutes % 10;
if(curr == 2) swap2 = (swap2 * 10) + 5;
else if(curr == 5) swap2 = (swap2 * 10) + 2;
else swap2 = (swap2 * 10) + curr;
minutes /= 10;
}
}
if(swap1 >= m || swap2 >= h) return false;
else return true;
}
}
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());
}
float nextFloat() {
return Float.parseFloat(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 | #include<bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define ll long long
#define lld long double
#define vc vector<ll>
#define pb push_back
#define all(a) a.begin(),a.end()
const ll MOD=(1e9 +7);
typedef pair<ll,ll>pairs;
ll power(ll a, ll b){ll res=1;a=a%MOD;while(b>0){if(b&1){res=(res*a)%MOD;b--;}a=(a*a)%MOD;b>>=1;}
return res;}
ll ref(ll n){
if(n==2)
return 5;
if(n==5)
return 2;
return n;
}
int main() {
// your code goes here
std::ios::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
ll t,n,i,j,k,c,f;
cin>>t;
while(t--){
ll h,m;
cin>>h>>m;
string s;
cin>>s;
ll h1,h2,m1,m2;
h1=s[0]-'0';
h2=s[1]-'0';
m1=s[3]-'0';
m2=s[4]-'0';
vector<ll> tt={0,1,2,5,8};
vector<ll> ans(5);
ll diff;
ll mn=MOD;
for(auto w:tt){
if(w*10>=h)
break;
for(auto x:tt){
if(w*10+x>=h)
break;
for(auto y:tt){
if(y*10>=m)
break;
for(auto z:tt){
if(10*y+z>=m)
break;
ll r1,r2,r3,r4;
r4=ref(w);
r3=ref(x);
r2=ref(y);
r1=ref(z);
if(10*r1+r2>=h||10*r3+r4>=m)
continue;
diff=(m*(10*w+x)+(10*y+z)-(m*(h1*10+h2)+(m1*10+m2)));
if(diff<0)
diff+=h*m;//(h*(10*w+x)+m*(10*y+z)+h*m-(h*(h1*10+h2)+m*(m1*10+m2)));
if(diff<mn){
mn=diff;
ans[0]=w,ans[1]=x,ans[3]=y,ans[4]=z;
}
}
}
}
}
for(i=0;i<=4;i++){
if(i==2)
cout<<":";
else
cout<<ans[i];
}
cout<<"\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 | c_digits = [0,1,5,-1,-1,2,-1,-1,8,-1]
def normalise(string): #Converts string of general form to the required form HH:MM
n = len(string)
if n ==5:
return string
if n == 3: #string = H:M
return "0"+string[0]+":"+"0"+string[2]
if n == 4:
if string[2] == ":": #string = HH:M
return string[0:3]+"0"+string[3]
else: #string = H:MM
return "0"+string
def correct(string, h,m): #Checks if given string fits the conditions:
#1) Mirror is a valid time
#2) Mirror time occurs on a normal day
string = normalise(string)
a = int(string[0])
b = int(string[1])
c = int(string[3])
d = int(string[4])
#str = ab:cd
if (c_digits[a] == -1 or c_digits[b] == -1 or c_digits[c] == -1 or c_digits[d] == -1):
return False
#Now a',b',c' and d' store the mirror time
a_dash = c_digits[d]
b_dash = c_digits[c]
c_dash = c_digits[b]
d_dash = c_digits[a]
hours = int(str(a_dash)+str(b_dash))
minutes = int(str(c_dash)+str(d_dash))
if hours<=h-1 and minutes<=m-1:
return True
else:
return False
def answer(string,h,m):
hours = int(string[0:2])
minutes = int(string[3:5])
for j in range(minutes, m):
str_dash = str(hours)+":"+str(j)
if (correct(str_dash, h,m)):
return normalise(str_dash)
for i in range(hours+1, h):
for j in range(m):
str_dash = str(i)+":"+str(j)
if correct(str_dash, h,m):
return normalise(str_dash)
return "00:00"
t= int(input())
for i in range(t):
[h,m] = list(map(int, input().split()))
s = input()
print(answer(s,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 | clock = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
mirror = [0, 1, 5, -1, -1, 2, -1, -1, 8, -1]
def check(h1, h2, m1, m2, m, H, M):
if m[h1] == -1 or m[h2] == -1 or m[m1] == -1 or m[m2] == -1:
return False
if m[m2] * 10 + m[m1] < H and m[h2] * 10 + m[h1] < M:
return True
return False
q = int(input())
while q:
h, m = input().split()
h, m = int(h), int(m)
s = input()
h1, h2, m1, m2 = int(s[0]), int(s[1]), int(s[3]), int(s[4])
while True:
if check(h1, h2, m1, m2, mirror, h, m):
print(str(h1) + str(h2) + ':' + str(m1) + str(m2))
break
else:
m2 += 1
if m2 == 10:
m2 = 0
m1 += 1
if (m1 * 10 + m2) >= m:
m1 = 0
m2 = 0
h2 += 1
if h2 == 10:
h2 = 0
h1 += 1
if (h1 * 10 + h2) >= h:
h1 = 0
h2 = 0
q -= 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 Main {
static FastScanner sc = new FastScanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder();
static HashSet<Character> set = new HashSet<>();
public static void main(String[] args) throws Exception {
int n = sc.nextInt();
set.add('0');
set.add('1');
set.add('2');
set.add('5');
set.add('8');
for(int i = 0; i < n; i++) solve();
pw.flush();
}
public static void solve(){
int h = sc.nextInt();
int m = sc.nextInt();
String[] s = sc.next().split(":");
int nowH = Integer.parseInt(s[0]);
int nowM = Integer.parseInt(s[1]);
int now = nowH*m+nowM;
for(int i = 0; i <= h*m; i++){
int tmp = now+i;
char[] tmpH = String.valueOf((tmp/m) % h).toCharArray();
char[] tmpM = String.valueOf(tmp%m).toCharArray();
boolean flg = true;
for(char c : tmpH){
if(!set.contains(c)){
flg = false;
break;
}
}
for(char c : tmpM){
if(!set.contains(c)){
flg = false;
break;
}
}
if(!flg) continue;
if(isOk(tmpH,m) && isOk(tmpM,h)){
if(tmpH.length == 1){
sb.append("0");
}
sb.append(new String(tmpH));
sb.append(":");
if(tmpM.length == 1){
sb.append("0");
}
sb.append(new String(tmpM));
break;
}
}
pw.println(sb.toString());
sb.setLength(0);
}
static boolean isOk(char[] s, int max){
int tmp = 0;
int pow = 10;
for(int i = s.length-1; i >= 0; i--){
if(s[i] == '2'){
tmp += pow*5;
}else if(s[i] == '5'){
tmp += pow*2;
}else{
tmp += pow*(s[i]-'0');
}
pow /= 10;
}
return tmp < max;
}
/*
static boolean isOk2(char[] s, int max){
int tmp = 0;
int pow = 1;
for(int i = s.length-1; i >= 0; i--){
tmp += pow*(s[i]-'0');
pow *= 10;
}
return tmp < max;
}
*/
static class ArrayComparator implements Comparator<int[]> {
@Override
public int compare(int[] a1, int[] a2) {
for (int i = 0; i < a1.length; i++) {
if (a1[i] < a2[i]) {
return -1;
} else if (a1[i] > a2[i]) {
return 1;
}
}
if (a1.length < a2.length) {
return -1;
} else if (a1.length > a2.length) {
return 1;
} else {
return 0;
}
}
}
static class GeekInteger {
public static void save_sort(int[] array) {
shuffle(array);
Arrays.sort(array);
}
public static int[] shuffle(int[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
int randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
public static void save_sort(long[] array) {
shuffle(array);
Arrays.sort(array);
}
public static long[] shuffle(long[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
long randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
}
}
class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String[] nextArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = next();
return a;
}
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;
}
}
| 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 CF {
static Set<Integer> good = new HashSet<>();
static Set<Integer> bad = new HashSet<>();
static Map<Integer, Integer> mirror = new HashMap<>();
private static void sport(int hours, int minutes, String s) {
mirror.put(0, 0);
mirror.put(1, 1);
mirror.put(2, 5);
mirror.put(5, 2);
mirror.put(8, 8);
good.add(0);
good.add(1);
good.add(2);
good.add(5);
good.add(8);
bad.add(3);
bad.add(4);
bad.add(6);
bad.add(7);
bad.add(9);
int h1 = s.charAt(0) - '0';
int h2 = s.charAt(1) - '0';
int m1 = s.charAt(3) - '0';
int m2 = s.charAt(4) - '0';
int h = h1 * 10 + h2;
int m = m1 * 10 + m2;
if (isGood(h, m, hours, minutes)) {
System.out.println(s);
return;
}
for (int j = m + 1; ; j++) {
j = j % minutes;
h = j == 0 ? h + 1 : h;
h %= hours;
if (isGood(h, j, hours, minutes)) {
System.out.println(format(h) + ":" + format(j));
return;
}
}
}
private static String format(int h) {
if (h > 9) {
return String.valueOf(h);
}
return "0" + String.valueOf(h);
}
private static boolean isGood(int h, int m, int hours, int minutes) {
String hf = format(h);
String mf = format(m);
int h1 = hf.charAt(0) - '0';
int h2 = hf.charAt(1) - '0';
int m1 = mf.charAt(0) - '0';
int m2 = mf.charAt(1) - '0';
if (good.contains(h1) && good.contains(h2) && good.contains(m1) && good.contains(m2)) {
m2 = mirror.get(m2);
m1 = mirror.get(m1);
h1 = mirror.get(h1);
h2 = mirror.get(h2);
int newHours = m2 * 10 + m1;
int newMinutes = h2 * 10 + h1;
return newHours < hours && newMinutes < minutes;
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int h = sc.nextInt();
int m = sc.nextInt();
String s = sc.next();
sport(h, m, 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 | #include <bits/stdc++.h>
using namespace std;
map<int, int> M = {{0, 0},
{1, 1},
{2, 5},
{3, -1},
{4, -1},
{5, 2},
{6, -1},
{7, -1},
{8, 8},
{9, -1}};
int T, HH, MM;
string s;
int reflect(int num) {
if (M[num / 10] == -1 || M[num % 10] == -1)
return -1;
return M[num % 10] * 10 + M[num / 10];
}
bool valid(int hour, int minute) {
hour = reflect(hour);
minute = reflect(minute);
if (hour == -1 || minute == -1)
return false;
swap(hour, minute);
if (hour >= HH || minute >= MM)
return false;
return true;
}
int main() {
#ifdef ACM
freopen("input", "r", stdin);
#endif
cin >> T;
while (T--) {
cin >> HH >> MM >> s;
int hour = (s[0] - '0') * 10 + s[1] - '0';
int minute = (s[3] - '0') * 10 + s[4] - '0';
while (!valid(hour, minute)) {
minute++;
if (minute == MM) {
hour = (hour + 1) % HH;
minute = 0;
}
}
printf("%.02d:%.02d\n", hour, minute);
}
} | 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 | from __future__ import division,print_function
from heapq import*
import sys
le = sys.__stdin__.read().split("\n")[::-1]
af=[]
r=[0,1,5,100,100,2,100,100,8,100]
def mirror(h1,m1,h,m):
hm=10*r[m1%10]+r[m1//10]
mm=10*r[h1%10]+r[h1//10]
return hm<h and mm<m
for zorg in range(int(le.pop())):
h,m=list(map(int,le.pop().split()))
s=le.pop()
h1=int(s[:2])
m1=int(s[3:])
while not(mirror(h1,m1,h,m)):
m1+=1
if m1==m:
m1=0
h1+=1
if h1==h:
h1=0
h1=str(h1)
if len(h1)==1:
h1="0"+h1
m1=str(m1)
if len(m1)==1:
m1="0"+m1
af.append(h1+":"+m1)
print("\n".join(map(str,af)))
| 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.io.*;
//import java.math.*;
public class Task{
// ..............code begins here..............
static long mod=(long)1e9+7,inf=(long)1e15;
static void solve() throws IOException {
int[] x=int_arr();
int h=x[0],m=x[1];
String[] s=read().split(":");
int hh=int_v(s[0]),mm=int_v(s[1]);
int[] r=new int[10];
Arrays.fill(r,-1);
r[0]=0;r[1]=1;r[2]=5;r[5]=2;r[8]=8;
for(int i=hh;i<h;i++){
for(int j=mm;j<m;j++){
mm=0;
int ch=i,cm=j;
int d1=ch/10,d2=ch%10,d3=cm/10,d4=cm%10;
if(r[d1]==-1||r[d2]==-1||r[d3]==-1||r[d4]==-1) continue;
else{
int th=r[d4]*10+r[d3],tm=r[d2]*10+r[d1];
if(th>=h||tm>=m) continue;
out.write(d1+""+d2+":"+d3+""+d4+"\n");
return;
}
}
}
out.write("00:00\n");
}
//
public static void main(String[] args) throws IOException{
assign();
int t=int_v(read());
while(t--!=0){
//out.write("Case #"+cn+": ");
solve();
}
out.flush();
}
// taking inputs
static BufferedReader s1;
static BufferedWriter out;
static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;}
static int int_v (String s1){return Integer.parseInt(s1);}
static long long_v(String s1){return Long.parseLong(s1);}
static void sort(int[] a){List<Integer> l=new ArrayList<>();for(int x:a){l.add(x);}Collections.sort(l);for(int i=0;i<a.length;i++){a[i]=l.get(i);}}
static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;}
static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;}
static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));}
//static String setpreciosion(double d,int k){BigDecimal d1 = new BigDecimal(Double.toString(d));return d1.setScale(k,RoundingMode.HALF_UP).toString();}//UP DOWN HALF_UP
static int add(int a,int b){int z=a+b;if(z>=mod)z-=mod;return z;}
static long gcd(long a,long b){if(b==0){return a;}return gcd(b,a%b);}
static long Modpow(long a,long p,long m){long res=1;while(p>0){if((p&1)!=0){res=(res*a)%m;}p >>=1;a=(a*a)%m;}return res%m;}
static long Modmul(long a,long b,long m){return ((a%m)*(b%m))%m;}
static long ModInv(long a,long m){return Modpow(a,m-2,m);}
//static long nck(int n,int r,long m){if(r>n){return 0l;}return Modmul(f[n],ModInv(Modmul(f[n-r],f[r],m),m),m);}
//static long[] f;
} | 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 | correct = {0: 0, 1: 1, 2: 5, 5: 2, 8: 8}
for i in range(int(input())):
h, m = map(int, input().split())
oclock, minute = map(int, input().split(':'))
while True:
a, b = oclock // 10, oclock % 10
c, d = minute // 10, minute % 10
try:
new_oclock = int(str(correct[d]) + str(correct[c]))
new_minute = int(str(correct[b]) + str(correct[a]))
if new_oclock < h and new_minute < m:
break
except KeyError:
pass
minute += 1
if minute == m:
minute = 0
oclock += 1
oclock %= h
oclock, minute = str(oclock), str(minute)
if len(oclock) == 1:
oclock = '0' + oclock
if len(minute) == 1:
minute = '0' + minute
print(oclock, ':', minute, sep='') | 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 sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush,heappop,heapify
from itertools import permutations,combinations
from itertools import accumulate as ac
mod = int(1e9)+7
#mod = 998244353
ip = lambda : int(stdin.readline())
inp = lambda: map(int,stdin.readline().split())
ips = lambda: stdin.readline().rstrip()
out = lambda x : stdout.write(str(x)+"\n")
t = ip()
for _ in range(t):
hours,mins = inp()
s = ips()
valid = [0,1,2,5,8]
ref = {'0':'0','1':'1','2':'5','5':'2','8':'8'}
valid = set(valid)
hr = int(s[0:2])
mi = int(s[3:5])
store_hr = hr
store_mi = mi
step1 = 0
while True:
ch = set()
step1 += 1
if len(str(hr)) == 1:
hr = '0'+str(hr)
else:
hr = str(hr)
if len(str(mi)) == 1:
mi = '0'+str(mi)
else:
mi = str(mi)
for i in str(hr):
ch.add(int(i))
for i in str(mi):
ch.add(int(i))
if len(ch|valid)== len(valid):
cur = hr+mi
cur = cur[::-1]
cur = [ref[i] for i in cur]
ref_hr = cur[0:2]
ref_hr = int(''.join(ref_hr))
ref_mi = cur[2:4]
ref_mi = int(''.join(ref_mi))
if int(ref_hr)< hours and int(ref_mi)< mins:
ans1 = str(hr)+':'+str(mi)
break
else:
hr = int(hr)
mi = int(mi)
mi += 1
if mi == mins:
mi = 0
hr += 1
if hr == hours:
hr = 0
else:
hr = int(hr)
mi = int(mi)
mi += 1
if mi == mins:
mi = 0
hr += 1
if hr == hours:
hr = 0
step2 = 0
hr = store_hr
mi = store_mi
while True:
ch = set()
step2 += 1
if len(str(hr)) == 1:
hr = '0'+str(hr)
else:
hr = str(hr)
if len(str(mi)) == 1:
mi = '0'+str(mi)
else:
mi = str(mi)
for i in str(hr):
ch.add(int(i))
for i in str(mi):
ch.add(int(i))
if len(ch|valid)== len(valid):
cur = hr+mi
cur = cur[::-1]
cur = [ref[i] for i in cur]
ref_hr = cur[0:2]
ref_hr = int(''.join(ref_hr))
ref_mi = cur[2:4]
ref_mi = int(''.join(ref_mi))
if int(ref_hr)< hours and int(ref_mi)< mins:
ans2 = str(hr)+':'+str(mi)
break
else:
hr = int(hr)
mi = int(mi)
mi -= 1
if mi < 0:
mi = mins-1
hr -= 1
if hr < 0:
hr = hours-1
else:
hr = int(hr)
mi = int(mi)
mi -= 1
if mi < 0:
mi = mins-1
hr -= 1
if hr < 0:
hr = hours-1
if step1<step2:
ans = ans1
else:
ans = ans2
print(ans1)
| 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 isvalid(s1,s2):
s1 = str(s1)
s2 = str(s2)
if len(s1)!=2:
s1 = '0'+s1
if len(s2)!=2:
s2 = '0'+s2
a = 0
for i in range(2):
if s1[1-i] not in d.keys():
return 0
a = a*10 + d[s1[1-i]]
b = 0
for i in range(2):
if s2[1-i] not in d.keys():
return 0
b = b*10 + d[s2[1-i]]
if b<h and a<m:
return 1
return 0
d = {'0':0,'1':1,'2':5,'5':2,'8':8}
for _ in range(int(input())):
h,m = map(int,input().split())
s = input()
a,b = s.split(':')
a = int(a)
b = int(b)
f = 0
for i in range(a,h):
if i!=a:
b=0
for j in range(b,m):
#print(i,j)
if isvalid(i,j):
f=1
s1 = str(i)
s2 = str(j)
if len(s1)!=2:
s1 = '0'+s1
if len(s2)!=2:
s2 = '0'+s2
print(s1+":"+s2)
break
if f==1:
break
if f==0:
print("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 | revert = {
'0': '0',
'1': '1',
'2': '5',
'3': '_',
'4': '_',
'5': '2',
'6': '_',
'7': '_',
'8': '8',
'9': '_'
}
def rev(s):
return revert[s[1]] + revert[s[0]]
for _ in range(int(input())):
H, M = tuple(map(int, input().split()))
h, m = tuple(map(int, input().split(':')))
t = h * M + m
while True:
x = str((t // M) % H).zfill(2)
y = str(t % M).zfill(2)
a = rev(str(y))
b = rev(str(x))
if not a.count('_') and not b.count('_') and 0 <= int(a) < H and 0 <= int(b) < M:
print(f'{x}:{y}')
break
t += 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 | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int main()
{
IOS
ll t;
cin>>t;
while(t--)
{
ll h,m;
cin>>h>>m;
string s;
cin>>s;
ll h1=(s[0]-'0')*10+(s[1]-'0'),m1=(s[3]-'0')*10+(s[4]-'0');
vector<ll>v;
v.push_back(0);
v.push_back(1);
v.push_back(8);
v.push_back(2);
v.push_back(5);
map<ll,ll>mx;
mx[1]=1;
mx[0]=0;
mx[2]=5;
mx[8]=8;
mx[5]=2;
sort(v.begin(),v.end());ll f=0;
for(ll i=0;i<h;i++)
{
for(ll j=0;j<m;j++)
{
ll x=(i+h1)%h;ll y=(j+m1);if(y>=m){y%=m;x=(x+1)%h;}
ll x1=x/10;ll x2=x%10;ll y1=y/10;ll y2=y%10;
if(binary_search(v.begin(),v.end(),x1)&&binary_search(v.begin(),v.end(),x2)&&binary_search(v.begin(),v.end(),y1)&&binary_search(v.begin(),v.end(),y2))
{
x1=mx[x1];x2=mx[x2];y1=mx[y1];y2=mx[y2];
ll x3=y2*10+y1;ll y3=x2*10+x1;
if(x3<h&&y3<m)
{ string xx=to_string(x);string yy=to_string(y);
if(xx.size()==1){xx='0'+xx;}if(yy.size()==1){yy='0'+yy;}
cout<<xx<<":"<<yy<<"\n";f=1;break;
}
}
}
if(f){break;}
}
}
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 isCorrect(_h, _m, h, m):
shh, smm = str(_h), str(_m)
if _h < 10:
shh = '0' + shh
if _m < 10:
smm = '0' + smm
s = f'{shh}:{smm}'
if '3' in s or '4' in s or '6' in s or '7' in s or '9' in s:
return False
if _h >= h or _h < 0:
return False
if _m>=m or _m<0:
return False
sRevH = list(smm[::-1])
if sRevH[0] == '2': sRevH[0] = '5'
elif sRevH[0] == '5': sRevH[0] = '2'
if sRevH[1] == '2': sRevH[1] = '5'
elif sRevH[1] == '5': sRevH[1] = '2'
revH = int(''.join(sRevH))
if revH >= h or revH < 0:
return False
sRevM = list(shh[::-1])
if sRevM[0] == '2': sRevM[0] = '5'
elif sRevM[0] == '5': sRevM[0] = '2'
if sRevM[1] == '2': sRevM[1] = '5'
elif sRevM[1] == '5': sRevM[1] = '2'
revM = int(''.join(sRevM))
if revM >= m or revM < 0:
return False
return s
def nextS(s, _h, _m, h, m):
newM = _m
newH = _h
while 1:
res = isCorrect(newH, newM, h, m)
if res:
return res
newM += 1
if newM >= m:
newM = 0
newH += 1
if newH >= h:
newH = 0
t = int(input())
while t > 0:
h, m = list(map(int, input().split()))
s = input()
_h, _m = list(map(int, s.split(':')))
print(nextS(s, _h,_m, h, m))
t -= 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 | from __future__ import division, print_function
from itertools import permutations
import threading,bisect,math,heapq,sys
from collections import deque
# threading.stack_size(2**27)
# sys.setrecursionlimit(10**4)
from sys import stdin, stdout
i_m=9223372036854775807
def cin():
return map(int,sin().split())
def ain(): #takes array as input
return list(map(int,sin().split()))
def sin():
return input()
def inin():
return int(input())
prime=[]
def dfs(n,d,v):
v[n]=1
x=d[n]
for i in x:
if i not in v:
dfs(i,d,v)
return p
def block(x):
v = []
while (x > 0):
v.append(int(x % 2))
x = int(x / 2)
ans=[]
for i in range(0, len(v)):
if (v[i] == 1):
ans.append(2**i)
return ans
"""**************************MAIN*****************************"""
def main():
d = [-1] * 10
d[0],d[1],d[2],d[5],d[8] = 0,1,5,2,8
t=inin()
for _ in range(t):
n,m=cin()
x,y=sin().split(':')
x,y=int(x),int(y)
while 1:
if min(d[x//10],d[x%10],d[y//10],d[y%10])!=-1:
if d[y%10]*10+d[y//10]<n and d[x%10]*10+d[x//10]<m:
print(x//10,x%10,':',y//10,y%10,sep="")
break
y += 1
if y == m:
y = 0
x += 1
if x == n:
x = 0
"""***********************************************"""
def intersection(l,r,ll,rr):
# print(l,r,ll,rr)
if (ll > r or rr < l):
return 0
else:
l = max(l, ll)
r = min(r, rr)
return max(0,r-l+1)
######## Python 2 and 3 footer by Pajenegod and c1729
fac=[]
def fact(n,mod):
global fac
fac.append(1)
for i in range(1,n+1):
fac.append((fac[i-1]*i)%mod)
f=fac[:]
return f
def nCr(n,r,mod):
global fac
x=fac[n]
y=fac[n-r]
z=fac[r]
x=moddiv(x,y,mod)
return moddiv(x,z,mod)
def moddiv(m,n,p):
x=pow(n,p-2,p)
return (m*x)%p
def GCD(x, y):
x=abs(x)
y=abs(y)
if(min(x,y)==0):
return max(x,y)
while(y):
x, y = y, x % y
return x
def Divisors(n) :
l = []
ll=[]
for i in range(1, int(math.sqrt(n) + 1)) :
if (n % i == 0) :
if (n // i == i) :
l.append(i)
else :
l.append(i)
ll.append(n//i)
l.extend(ll[::-1])
return l
def SieveOfEratosthenes(n):
global prime
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
f=[]
for p in range(2, n):
if prime[p]:
f.append(p)
return f
def primeFactors(n):
a=[]
while n % 2 == 0:
a.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
a.append(i)
n = n // i
if n > 2:
a.append(n)
return a
"""*******************************************************"""
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO,self).read()
def readline(self):
while self.newlines == 0:
s = self._fill(); self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
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')
# Cout implemented in Python
class ostream:
def __lshift__(self,a):
sys.stdout.write(str(a))
return self
cout = ostream()
endl = '\n'
# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
conv = ord if py2 else lambda x:x
A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
try:
while True:
if s[i] >= b'R' [0]:
numb = 10 * numb + conv(s[i]) - 48
elif s[i] == b'-' [0]: sign = -1
elif s[i] != b'\r' [0]:
A.append(sign*numb)
numb = zero; sign = 1
i += 1
except:pass
if s and s[-1] >= b'R' [0]:
A.append(sign*numb)
return A
# threading.Thread(target=main).start()
if __name__== "__main__":
main() | 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.*;
import java.util.*;
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());
}
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;
}
}
static FastReader s = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
private static int[] rai(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
return arr;
}
private static int[][] rai(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = s.nextInt();
}
}
return arr;
}
private static long[] ral(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextLong();
}
return arr;
}
private static long[][] ral(int n, int m) {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = s.nextLong();
}
}
return arr;
}
private static int ri() {
return s.nextInt();
}
private static long rl() {
return s.nextLong();
}
private static String rs() {
return s.next();
}
static int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static long gcd(long a,long b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static boolean isPrime(int n) {
//check if n is a multiple of 2
if(n==1)
{
return false;
}
if(n==2)
{
return true;
}
if (n % 2 == 0) return false;
//if not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
static boolean[] sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
boolean prime[] = new boolean[n+1];
for(int i=0;i<n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
// If prime[p] is not changed, then it is a prime
if(prime[p] == true)
{
// Update all multiples of p
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
static boolean isValid(int hours, int mins,int h,int m,HashMap<Integer,Integer> map)
{
// System.out.println(hours+" "+mins);
StringBuilder mid=new StringBuilder();
mid.append(mins);
if(mid.length() <2)
{
mid=new StringBuilder();
mid.append(0).append(mins);
}
StringBuilder str1 = new StringBuilder();
char[] arr=mid.toString().toCharArray();
for(int i=arr.length-1;i>=0;i--)
{
int val=arr[i]-'0';
if(!map.containsKey(val))
{
// System.out.println();
return false;
}
str1.append(map.get(val));
}
mid=new StringBuilder();
mid.append(hours);
if(mid.length() <2)
{
mid=new StringBuilder();
mid.append(0).append(hours);
}
StringBuilder str2 = new StringBuilder();
arr=mid.toString().toCharArray();
for(int i=arr.length-1;i>=0;i--)
{
int val=arr[i]-'0';
if(!map.containsKey(val))
{
// System.out.println();
return false;
}
str2.append(map.get(val));
}
int newHours = Integer.parseInt(str1.toString());
int newMins = Integer.parseInt(str2.toString());
// System.out.println(newHours+" "+newMins);
// System.out.println();
return newHours < h && newMins < m;
}
public static void main(String[] args) {
StringBuilder ans = new StringBuilder();
int t = ri();
// int t=1;
while (t-- > 0)
{
HashMap<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);
int h=ri();
int m=ri();
char[] arr = rs().toCharArray();
int hours=0;
int mins=0;
boolean flag=false;
StringBuilder mid=new StringBuilder();
for(char c:arr)
{
if(c==':')
{
flag = true;
hours=Integer.parseInt(mid.toString());
mid=new StringBuilder();
continue;
}
mid.append(c);
}
mins = Integer.parseInt(mid.toString());
// System.out.println(hours+" "+mins);
int h1=-1,m1=-1;
int count1=0;
while(true)
{
if(isValid(hours,mins,h,m,map))
{
h1 = hours;
m1= mins;
break;
}
mins++;
if(mins==m)
{
mins=0;
hours++;
}
if(hours==h)
{
hours = 0;
}
count1++;
}
int h2=-1,m2=-1;
int count2=0;
while(true)
{
if(isValid(hours,mins,h,m,map))
{
h2=hours;
m2=mins;
break;
}
mins--;
if(mins==-1)
{
mins=m-1;
hours--;
}
if(hours==-1)
{
hours=h-1;
}
count2++;
}
if(count1<=count2)
{
hours=h1;mins=m1;
}
else
{
hours=h2;mins=m2;
}
StringBuilder str1 = new StringBuilder();
str1.append(hours);
if(str1.length()<2)
{
ans.append("0");
}
ans.append(hours).append(":");
str1 = new StringBuilder();
str1.append(mins);
if(str1.length()<2)
{
ans.append("0");
}
ans.append(mins).append("\n");
}
out.print(ans.toString());
out.flush();
}
}
| 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.*;
import java.util.*;
public class tank {
//static StringBuilder IO = new StringBuilder();
static final FastScanner fs = new FastScanner();
static boolean[] isval = {true, true, true, false, false, true, false, false, true,
false};
public static void main(String[] args) {
int t = fs.nextInt();
while(t-->0){
run_case();
}
// run_case();
// System.out.println(IO);
}
static void run_case(){
int h = fs.nextInt(), m = fs.nextInt(), hh, mm;
String d = fs.next();
hh = (d.charAt(1) - '0') + 10*(d.charAt(0) - '0');
mm = (d.charAt(4) - '0') + 10*(d.charAt(3) - '0');
l1:
for (; hh < h; hh++) {
for (; mm < m; mm++) {
if(front(h, m, hh, mm) && back(h, m, hh, mm) && mir(hh, mm)){
break l1;
}
}
if(mm == m){
mm = 0;
}
if(hh == h-1){
hh = -1;
}
}
char[] ans = new char[5];
ans[2] = ':';
ans[1] = Integer.toString(hh%10).charAt(0);
hh /= 10;
ans[0] = Integer.toString(hh).charAt(0);
ans[4] = Integer.toString(mm%10).charAt(0);
mm /= 10;
ans[3] = Integer.toString(mm).charAt(0);
System.out.println(new String(ans));
}
static boolean mir(int h, int m){
return isval[h%10] && isval[h/10] && isval[m%10] && isval[m/10];
}
static boolean front(int h, int m, int hh, int mm){
return hh < h && mm < m;
}
static int[] flip = {0, 1, 5, 3, 4, 2, 6, 7, 8, 9};
static boolean back(int h, int m, int hh, int mm){
int hhh = 10*flip[(mm%10)], mmm = 10*flip[(hh%10)];
hhh += flip[mm/10];
mmm += flip[hh/10];
return hhh < h && mmm < m;
}
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());
}
}
} | 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 sys,os,io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop
from bisect import bisect_left , bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')
def isPrime(x):
for i in range(2,x):
if i*i>x:
break
if (x%i==0):
return False
return True
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
return list(set(l))
def power(x, y, p) :
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def si():
return input()
def prefix_sum(arr):
r = [0] * (len(arr)+1)
for i, el in enumerate(arr):
r[i+1] = r[i] + el
return r
def divideCeil(n,x):
if (n%x==0):
return n//x
return n//x+1
def ii():
return int(input())
def li():
return list(map(int,input().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
def power_set(L):
cardinality=len(L)
n=2 ** cardinality
powerset = []
for i in range(n):
a=bin(i)[2:]
subset=[]
for j in range(len(a)):
if a[-j-1]=='1':
subset.append(L[j])
powerset.append(subset)
powerset_orderred=[]
for k in range(cardinality+1):
for w in powerset:
if len(w)==k:
powerset_orderred.append(w)
return powerset_orderred
def fastPlrintNextLines(a):
# 12
# 3
# 1
#like this
#a is list of strings
print('\n'.join(map(str,a)))
def sortByFirstAndSecond(A):
A = sorted(A,key = lambda x:x[0])
A = sorted(A,key = lambda x:x[1])
return list(A)
#__________________________TEMPLATE__________________OVER_______________________________________________________
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
# else:
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def isValid(hh,mm,l,h,m):
c = hh
while(c):
x = c%10
if l[x]==-1:
return 0
c//=10
c = mm
while(c):
x = c%10
if l[x]==-1:
return 0
c//=10
hh = str(hh)
if len(hh)==1:
hh = '0'+hh
mm = str(mm)
if len(mm)==1:
mm = '0'+mm
hh = list(hh)
mm = list(mm)
hh.reverse()
mm.reverse()
hh[0]=str(l[int(hh[0])])
hh[1]=str(l[int(hh[1])])
mm[0]=str(l[int(mm[0])])
mm[1]=str(l[int(mm[1])])
hh=int(''.join(hh))
mm=int(''.join(mm))
if hh<m and mm<h:
return 1
return 0
def solve():
h,m = li()
H,M = input().split(":")
H = int(H)
M = int(M)
ans = -1
l = [0,1,5,-1,-1,2,-1,-1,8,-1]
f = 0
ansm = 10000000000000000000000000
hh = H
mm = M
c = 0
while(c<=h*m+1):
if isValid(hh,mm,l,h,m)==1:
ans = [hh,mm]
ans[0]=str(ans[0])
ans[1]=str(ans[1])
if len(ans[0])==1:
ans[0]='0'+ans[0]
if len(ans[1])==1:
ans[1]='0'+ans[1]
a =ans[0]+':'+ans[1]
print(a)
return
mm+=1
if mm==m:
mm=0
hh+=1
c+=1
if hh==h:
hh = 0
t = 1
t = int(input())
for _ in range(t):
solve()
| PYTHON3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.