text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Tags: geometry Correct Solution: ``` n, d = [int(i) for i in input().split()] m = int(input()) for i in range(m): x, y = [int(i) for i in input().split()] if y <= n - abs(x - n + d) and y >= abs(x - d): print('YES') else: print('NO') ```
10,800
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Tags: geometry Correct Solution: ``` def inF(d,n,x,y): mg = 0.7071067811865475 x1 = (x-y)*mg y1 = (x+y)*mg if x1>=-d*mg and x1<=d*mg: if y1>=d*mg and y1<=(2*n-d)*mg: return True return False n,d = list(map(int,input().split())) m=int(input()) x=[] y=[] for i in range(m): x1,y1 = list(map(int,input().split())) x.append(x1) y.append(y1) for i in range(m): if inF(d,n,x[i],y[i]): print('YES') else: print('NO') ```
10,801
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Tags: geometry Correct Solution: ``` n, d = map(int, input().split()) q = int(input()) for i in range(q): x, y = map(int, input().split()) if x >= d - y and y <= 2 * n - d - x and abs(x - y) <= d: print("YES") else: print("NO") ```
10,802
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Tags: geometry Correct Solution: ``` #------------------------------what is this I don't know....just makes my mess faster-------------------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #----------------------------------Real game starts here-------------------------------------- ''' ___________________THIS IS AESTROIX CODE________________________ KARMANYA GUPTA ''' n , d = list(map(int, input().split())) for i in range(int(input())): x , y = list(map(int, input().split())) a = y-x b = y+x if a < d and a > -d and b > d and b < 2*n - d: print("YES") elif a == d or a == -d or b == d or b == 2*n - d: print("YES") else: print("NO") ```
10,803
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Tags: geometry Correct Solution: ``` n, d = list(map(int, input().split())) m = int(input()) def lfunc(x1, y1, x2, y2, x): if x2!=x1: k = (y2 - y1)/(x2-x1) else: k = 0 b = y1 - k * x1 return k*x+b k = 0 for i in range(m): x, y = list(map(int, input().split())) if y<=lfunc(0,d,n-d,n,x) and y>=lfunc(d,0,n,n-d,x)\ and y<=lfunc(n,n-d,n-d,n,x) and y>=lfunc(d,0,0,d,x): print('YES') else: print('NO') ```
10,804
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Tags: geometry Correct Solution: ``` n,d = map(int,input().split()) m = int(input()) ans = [] for i in range(m): x1,y1 = map(int,input().split()) t1 = x1+y1 t2 = x1-y1 if t1>=d and t1<=(2*n-d) and t2>=(-d) and t2<=d: ans.append('YES') else: ans.append('NO') for i in ans: print(i) ```
10,805
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Submitted Solution: ``` def yes(x,y): global n, d return 'YES' if y >= -x + n and y >= x - n and y <= -x + d + d - n and y <= x + n else 'NO' d, n = map(int, input().split()) k = int(input()) for i in range(k): x1, y1 = map(int, input().split()) print(yes(x1, y1)) ``` Yes
10,806
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Submitted Solution: ``` n, d = map(int, input().split()) k = int(input()) for i in range(k): x, y = map(int, input().split()) if y <= x + d and y >= x - d and y >= -x + d and y <= -x + 2*n - d: print("YES") else: print("NO") ``` Yes
10,807
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Submitted Solution: ``` n, d = [int(x) for x in input().split()] m = int(input()) def ch(n, d, x, y): if(n - y + x >= n - d and x + y >= d and n - x + y >= n - d and n - x + n - y >= d): return True else: return False for i in range(0, m): x, y = [int(j) for j in input().split()] if(ch(n, d, x, y)): print("YES") else: print("NO") ``` Yes
10,808
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Submitted Solution: ``` n, d = map(int, input().split()) m = int(input()) for i in range(m): x, y = map(int, input().split()) if ((x + y >= d and 0 <= x <= d) or (d <= x <= n and y >= x - d)) and ((0 <= x <= n - d and y <= x + d) or (n - d <= x <= n and x + y <= 2 * n - d)): print("YES") else: print("NO") ``` Yes
10,809
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Submitted Solution: ``` n,d = map(int,input().split()) m = int(input()) for i in range(m): x,y = map(int,input().split()) s = x+y if (x+y<d) | (x+y>2*n-d): print('NO') elif x>y: if (x+d>y): print('NO') else: print('YES') elif x<y: if (y-d>x): print('NO') else: print('YES') else: print('YES') ``` No
10,810
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Submitted Solution: ``` n, d = map(int, input().split()) n_kuz = int(input()) for i in range(n_kuz): x, y = map(int, input().split()) one = y*(n-d) + x*(d-n) - d*(n-d) two = y*d + x*d - d**2 three = y*d + x*d + ((n-d)**2 - n**2) four = y*(n-d) + x*(d-n) + (d*n - d**2) print(one, two, three, four) if one <= 0 and two >= 0 and three <= 0 and four >= 0: print("YES") else: print("NO") ``` No
10,811
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Submitted Solution: ``` n, d = map(int, input().split()) # ввод с клавиатуры через пробел m = int(input()) # ввод i = int(0) # целочисленное значение 0 j = int(0) # целочисленное значение 0 c = list() # пустой список if 1 <= d <= n <= 100 and 1 <= m <= 100: # проверка границ ввода while i < m: # цикл x, y = map(int, input().split()) # непрерывный ввод через пробел i += 1 # сложение значения i и 1 if not ((x - y) <= d and (x + y) >= -d): # проверка c.append(0) # добавление в конец списка 0 elif not (n + n - d >= (x + y) >= d): # проверка c.append(0) # добавление в конце списка 0 else: c.append(1) # добавление в конце списка 0 while j < m: # цикл if c[j] == 1: # прверка каждого j-го элемента print("YES") # вывод YES else: # (иначе) условие, если не выполнилось if print("NO") # вывод NO j += 1 # сложение значения j и 1 ``` No
10,812
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border). Input The first line contains two integers n and d (1 ≤ d < n ≤ 100). The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers. The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper. Output Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO". You can print each letter in any case (upper or lower). Examples Input 7 2 4 2 4 4 1 6 3 4 5 Output YES NO NO YES Input 8 7 4 4 4 2 8 8 1 6 1 Output YES NO YES YES Note The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield. The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield. <image> Submitted Solution: ``` coord = input() coord = coord.split(" ") colvo = input() kuz = [] while len(kuz) != int(colvo): kuz.append(input()) otv = "" for i in kuz: i = i.split(" ") if i[0] <= coord[0] and i[1] <= coord[1]: otv += "YES\n" else: otv += "NO\n" print(otv) ``` No
10,813
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Suppose you are given a sequence S of k pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_k, b_k). You can perform the following operations on it: 1. Choose some position i and increase a_i by 1. That can be performed only if there exists at least one such position j that i ≠ j and a_i = a_j. The cost of this operation is b_i; 2. Choose some position i and decrease a_i by 1. That can be performed only if there exists at least one such position j that a_i = a_j + 1. The cost of this operation is -b_i. Each operation can be performed arbitrary number of times (possibly zero). Let f(S) be minimum possible x such that there exists a sequence of operations with total cost x, after which all a_i from S are pairwise distinct. Now for the task itself ... You are given a sequence P consisting of n pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n). All b_i are pairwise distinct. Let P_i be the sequence consisting of the first i pairs of P. Your task is to calculate the values of f(P_1), f(P_2), ..., f(P_n). Input The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of pairs in sequence P. Next n lines contain the elements of P: i-th of the next n lines contains two integers a_i and b_i (1 ≤ a_i ≤ 2 ⋅ 10^5, 1 ≤ b_i ≤ n). It is guaranteed that all values of b_i are pairwise distinct. Output Print n integers — the i-th number should be equal to f(P_i). Examples Input 5 1 1 3 3 5 5 4 2 2 4 Output 0 0 0 -5 -16 Input 4 2 4 2 3 2 2 1 1 Output 0 3 7 1 Submitted Solution: ``` print("""0 0 0 -5 -16""") ``` No
10,814
Provide tags and a correct Python 3 solution for this coding contest problem. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Tags: implementation, math Correct Solution: ``` n = int(input()) xy = input().split(" ") x = int(xy[0]) y = int(xy[1]) wx = 1 wy = 1 bx = n by = n if x < y: white = (x-1) + (y-x) black = (n-y) + (y-x) else: white = (y-1) + (x-y) black = (n-x) + (x-y) if white <= black: print('White') else: print('Black') ```
10,815
Provide tags and a correct Python 3 solution for this coding contest problem. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Tags: implementation, math Correct Solution: ``` def go(): n = int(input()) x, y = [int(i) for i in input().split(' ')] a = 1 + 1 b = n + n c = x + y distance_w = c - a distance_b = b - c if distance_w == distance_b: return 'White' if distance_w < distance_b: return 'White' return 'Black' print(go()) ```
10,816
Provide tags and a correct Python 3 solution for this coding contest problem. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Tags: implementation, math Correct Solution: ``` gcd = lambda a, b: gcd(b, a % b) if b else a def main(): n = int(input()) x, y = map(int, input().split()) if max(n - x, n - y) < max(x - 1, y - 1): print("Black") else: print("White") main() ```
10,817
Provide tags and a correct Python 3 solution for this coding contest problem. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Tags: implementation, math Correct Solution: ``` n = int(input()) [x,y] = [int(x) for x in input().split()] xw = yw = 1 xb = yb = n maxi = max(x,y) mini = min(x,y) sw = mini-xw + maxi-mini sb = xb-maxi + maxi-mini if sw <= sb: print('White') else: print('Black') ```
10,818
Provide tags and a correct Python 3 solution for this coding contest problem. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Tags: implementation, math Correct Solution: ``` n=int(input()) a,b=map(int,input().split()) a,b=min(a,b),max(a,b) x=a-1+b-a y=n-b+b-a if(x<=y): print("White") else: print("Black") ```
10,819
Provide tags and a correct Python 3 solution for this coding contest problem. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Tags: implementation, math Correct Solution: ``` n = int(input()) x, y = list(map(int, input().split(" "))) n1 = abs(x-1) + abs(y-1) n2 = abs(x-n) + abs(y-n) if n1 > n2: print("Black") else: print("White") ```
10,820
Provide tags and a correct Python 3 solution for this coding contest problem. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Tags: implementation, math Correct Solution: ``` n=int(input()) (x,y)=map(int,input().split()) if ((x-1)+(y-1))>((n-x)+(n-y)): print("Black") else: print("White") ```
10,821
Provide tags and a correct Python 3 solution for this coding contest problem. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Tags: implementation, math Correct Solution: ``` n = int(input()) x, y = map(int, input().split()) w = max(abs(x-1), abs(y-1)) b = max(abs(x-n), abs(y-n)) if b < w: print("Black") else: print("White") ```
10,822
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Submitted Solution: ``` a=int(input()) n, m=map(int, input().split()) mh=min(abs(1-n),abs(1-m)) mb=min(abs(a-n),abs(a-m)) if mh<=mb: print("White") else: print("Black") ``` Yes
10,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Submitted Solution: ``` n = int(input()) x, y = map(int, input().split()) #w = ((x-1) ** 2 + (y-1) ** 2) ** 0.5 #b = ((n-x) ** 2 + (n-y) ** 2) ** 0.5 w = max((x-1), (y-1)) b = max((n-x), (n-y)) if (w <= b): print("White") else: print("Black") ``` Yes
10,824
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Submitted Solution: ``` n=int(input()) x,y=input().split() x=int(x) y=int(y) s=x*y a=n-x+1 b=n-y+1 c=a*b if s<=c: print("white") elif c<s: print("black") ``` Yes
10,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Submitted Solution: ``` import math n = int(input()) s = input() a = s.split(" ") x, y = int(a[0]), int(a[1]) if x == y and x*2 > n and n % 2 == 0: print("Black") elif x < y and x*2 > n: print("Black") else: dis1 = math.sqrt(pow(x - 1, 2) + pow(y - 1, 2)) dis2 = math.sqrt(pow(x - n, 2) + pow(y - n, 2)) if dis1 <= dis2: print("White") else: print("Black") ``` Yes
10,826
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Submitted Solution: ``` white = [1,1] black = [0, 0] target = ["x", "y"] black[0] = black[1] = int(input()) target[0], target[1] = map(int, input().split()) white_move = max(target[0]-white[0], target[1]-white[1]) black_move = max(black[0]-target[0], black[1]-target[1]) print(white_move) print(black_move) if(black_move >=white_move): print("White") else: print("Black") ``` No
10,827
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Submitted Solution: ``` import math n = int(input()) x, y = map(int, input().split(" ")) white = math.sqrt((x - 1) * (x - 1) + (y - 1) * (y - 1)) black = math.sqrt((x - n) * (x - n) + (y - n) * (y - n)) if n % 2 == 0: if white == black: if x > n / 2 and y > n / 2: print("Black") else: print("White") else: if white == black: print("White") elif white < black: print("White") elif x > n / 2 and y > n / 2: print("Black") else: print("Black") ``` No
10,828
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Submitted Solution: ``` num=int(input()) a,b=map(int,input().split(' ')) xw=1 yw=1 xb=num yb=num c=0 c2=0 if xb==b: c=yb-a if xw==b: c2=yw-a else: c2=yw-a xw+=c2 yw+=c2 c2+=abs(b-xw) else: c=yb-a xb-=c yb-=c c+=abs(b-xb) if xw==b: c2=yw-a else: c2=yw-a xw+=c2 yw+=c2 c2+=abs(b-xw) if c<c2: print('Black') else: print('White') ``` No
10,829
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column. The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)... Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules: As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time. The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win. Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited. Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first. Input The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field. The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell. Output In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win. You can print each letter in any case (upper or lower). Examples Input 4 2 3 Output White Input 5 3 5 Output Black Input 2 2 2 Output Black Note An example of the race from the first sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (4,4) into the cell (3,3). 3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins. <image> An example of the race from the second sample where both the white king and the black king move optimally: 1. The white king moves from the cell (1,1) into the cell (2,2). 2. The black king moves form the cell (5,5) into the cell (4,4). 3. The white king moves from the cell (2,2) into the cell (3,3). 4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins. <image> In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins. <image> Submitted Solution: ``` n=int(input()) x,y=map(int,input().split()) a=x-1 b=n-x if(a<b): print("WHITE") else: print("BLACK") ``` No
10,830
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Tags: combinatorics, math, strings Correct Solution: ``` import sys from fractions import gcd from itertools import groupby as gb from itertools import permutations as perm from collections import Counter as C from collections import defaultdict as dd sys.setrecursionlimit(10**5) mod = 998244353 n = int(input()) s = input() if s == s[0]*n: print(n*(n+1)//2) exit() g = gb(s) gg = gb(s[::-1]) a = 0 a_c,b_c = '','' b = 0 for k,v in g: a = len(list(v)) a_c = k break for k,v in gg: b = len(list(v)) b_c = k break res = 0 if a_c == b_c: res += a * b res += a + b + 1 print(int(res)%mod) ```
10,831
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Tags: combinatorics, math, strings Correct Solution: ``` MOD = 998244353 n = int(input()) s = input() pref = s[0] suff = s[-1] lpref = 0 lsuff = 0 for i in range(len(s)): if s[i] == pref: lpref = lpref + 1 else: break for i in range(len(s)): if s[len(s)-1-i] == suff: lsuff = lsuff + 1 else: break if pref == suff: res = (((lpref+1) % MOD) * ((lsuff+1) % MOD)) % MOD else: res = (lpref + lsuff + 1) % MOD print(res) ```
10,832
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Tags: combinatorics, math, strings Correct Solution: ``` modu = 998244353 n = int(input()) s = input() # first = s[0] fans = 0 for i in range(n): if s[i] == s[0]: fans = fans+1 else: break s2 = s[::-1] lans = 0 for i in range(n): if s2[i] == s2[0]: lans = lans+1 else: break if s[0]==s2[0] and len(set(s))>1: print((fans*lans+lans+fans+1)%modu) elif len(set(s))>1: print((fans+lans+1)%modu) else: print((2**(fans))%modu) ```
10,833
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Tags: combinatorics, math, strings Correct Solution: ``` import sys #import math data = sys.stdin.readlines() n = data[0] s = data[1] s = list(s[:len(s) - 1]) diferente1 = -1 diferente2 = -1 for i in range(len(s)): if s[i] != s[0] and diferente1 == -1: diferente1 = i if s[-(i+1)] != s[-1] and diferente2 == -1: diferente2 = i if diferente1 != -1 and diferente2 != -1: break if s[0] == s[-1]: print((diferente1+1)*(diferente2+1)%998244353) else: print(diferente1+diferente2+1) ```
10,834
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Tags: combinatorics, math, strings Correct Solution: ``` from sys import stdin,stdout n=int(stdin.readline()) st=stdin.readline() cntl=0 cntr=0 for i in st: if(st[0] == i): cntl+=1 else: break for j in range(n-1,-1,-1): if(st[j] == st[n-1]): cntr+=1 else: break if(st[0] == st[n-1]): print(((cntl+1)*(cntr+1))%998244353) else: print(((cntl+cntr+1))%998244353 ) ```
10,835
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Tags: combinatorics, math, strings Correct Solution: ``` import sys,math,bisect from random import randint inf = float('inf') mod = 998244353 "========================================" def lcm(a,b): return int((a/math.gcd(a,b))*b) def gcd(a,b): return int(math.gcd(a,b)) def tobinary(n): return bin(n)[2:] def binarySearch(a,x): i = bisect.bisect_left(a,x) if i!=len(a) and a[i]==x: return i else: return -1 def lowerBound(a, x): i = bisect.bisect_left(a, x) if i: return (i-1) else: return -1 def upperBound(a,x): i = bisect.bisect_right(a,x) if i!= len(a)+1 and a[i-1]==x: return (i-1) else: return -1 def primesInRange(n): ans = [] 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 for p in range(2, n+1): if prime[p]: ans.append(p) return ans def primeFactors(n): factors = [] while n % 2 == 0: factors.append(2) n = n // 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: factors.append(i) n = n // i if n > 2: factors.append(n) return factors def isPrime(n,k=5): if (n <2): return True for i in range(0,k): a = randint(1,n-1) if(pow(a,n-1,n)!=1): return False return True "=========================================" """ n = int(input()) n,k = map(int,input().split()) arr = list(map(int,input().split())) """ from collections import deque,defaultdict,Counter import heapq,string n=int(input()) s=input() cnt=0 if n==2: print(3) else: pref = 1 for i in range(1,n): if s[i]==s[i-1]: pref+=1 else: break suff=1 for i in range(n-2,-1,-1): if s[i]==s[i+1]: suff+=1 else: break if s[0]==s[-1]: print((suff+1+pref+(suff*pref))%mod) else: print((suff+pref+1)%mod) ```
10,836
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Tags: combinatorics, math, strings Correct Solution: ``` import sys n = int((sys.stdin.readline()).strip()) s = (sys.stdin.readline()).strip() counter = {} lower = 0 for i in range(n): counter[s[i]]=1 if len(counter)>1: lower = i break counter = {} upper = n-1 for i in reversed(range(n)): counter[s[i]]=1 if len(counter)>1: upper = i break mod = 998244353 if s[0]==s[-1]: ans = (((lower +1)%mod)*((n-upper)%mod))%mod else: ans = (((lower +1)%mod)+((n-upper)%mod)-1)%mod print(ans) ```
10,837
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Tags: combinatorics, math, strings Correct Solution: ``` n = int(input()) s = list(input()) c =[s[0]] m =[s[-1]] for i in range(len(s)-1): if(s[i]==s[i+1]): c.append(s[i+1]) else: break s.reverse() for i in range(len(s)-1): if(s[i]==s[i+1]): m.append(s[i+1]) else: break if(s[0]!=s[-1]): print((len(c)+len(m)+1)%998244353) else: print((len(c)+1)*(len(m)+1)%998244353) ```
10,838
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Submitted Solution: ``` n = int(input()) s = input() for i in range(n-1): if s[i+1]==s[i]: pass else: l = i+1 break for i in range(n-1): if s[n-1-(i+1)]==s[n-1-i]: pass else: r = n-1-i-1 break ans =0 temp = 0 inf = 998244353 if s[0]==s[-1]: #ans = (n-r)*l+n-r ans = ans+ n%inf -r%inf ans = ans%inf temp = temp+n%inf - r%inf temp = temp%inf temp = temp *(l%inf) temp = temp%inf ans = ans+temp ans = ans%inf else: ans = ans+l%inf+n%inf -r%inf #ans = n-r+l ans = ans%inf print(ans) ``` Yes
10,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Submitted Solution: ``` n = int(input()) s = input() fs = s[0] indf = 0 for i in range(n): if s[i] != fs: break indf += 1 ls = s[-1] indl = 0 for i in range(-1, -n, -1): if s[i] != ls: break indl += 1 mas = [] for i in range(n): if s[i] not in mas: mas.append(s[i]) if s == s[0] * n: ans = (n * (n + 1) // 2) elif s[0] == s[-1]: ans = ((indf + 1) * (indl + 1)) else: ans = (indf + indl + 1) print(ans % 998244353) ``` Yes
10,840
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Submitted Solution: ``` Mod = 998244353 n = int(input()) string = input() front = 1 i= 1 while(i<n): if(string[i]==string[0]): front+=1 else: break i+=1 rear = 1 i = n-2 while(i>=0): if(string[i]==string[n-1]): rear+=1 else: break i-=1 if(front+rear>n): n = n%Mod ans = n*(n+1)%Mod elif(string[0]!=string[n-1]): ans = front%Mod +rear%Mod ans = (ans + 1)%Mod else: Mid = n -(front+rear) front = front%Mod rear = rear%Mod ans = (front+rear+1)%Mod temp = (front*rear)%Mod ans = (ans+temp)%Mod print(ans) ``` Yes
10,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Submitted Solution: ``` n=int(input()) s=input() ans=0 k1,k2=0,-1 for i in range(1,n): if s[i]!=s[0]: k1=i break for i in range(n-2,-1,-1): if s[i]!=s[-1]: k2=i break if s[0]==s[-1]: ans=(k1+1)*(n-k2) else: ans+=k1+n-k2-1 ans+=1 print(ans%998244353) ``` Yes
10,842
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Submitted Solution: ``` n = int(input()) s = input() list_s = list(s) count_char =0 x=-1 current_char = list_s[x] while(current_char == list_s[-1]): count_char+=1 x = x-1 current_char = list_s[x] if list_s[0] == list_s[-1]: print(count_char*3) else: print(count_char*2) ``` No
10,843
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Submitted Solution: ``` n = int(input()) s = input().strip() head = s[0] cnt1 = 1 tmp = 0 for i in range(1,n//2): if s[i] == head: cnt1 += 1 else: tmp = i-1 break tail = s[n-1] cnt2 = 1 for i in range(n-2,tmp,-1): if s[i] == tail: cnt2 += 1 else: break if head != tail: print(cnt1+cnt2+1) else: print((cnt1+1)*(cnt2+1)) ``` No
10,844
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Submitted Solution: ``` import sys import math data = sys.stdin.readlines() n = data[0] s = data[1] data = list(s[:len(s) - 1]) diferente1 = -1 diferente2 = -1 for i in range(len(s)): if s[i] != s[0] and diferente1 == -1: diferente1 = i if s[-(i+1)] != s[-1] and diferente2 == -1: diferente2 = i if diferente1 != -1 and diferente2 != -1: break if s[0] == s[-1]: #print((diferente1+1)*(diferente2+1)) print("Hola") else: #print(diferente1+diferente2+1) print(s[-3]) ``` No
10,845
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s of length n consisting only of lowercase Latin letters. A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not. Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one). It is guaranteed that there is at least two different characters in s. Note that you can remove the whole string and it is correct. Also note that you should remove at least one character. Since the answer can be rather large (not very large though) print it modulo 998244353. If you are Python programmer, consider using PyPy instead of Python when you submit your code. Input The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the length of the string s. The second line of the input contains the string s of length n consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in s. Output Print one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal. Examples Input 4 abaa Output 6 Input 7 aacdeee Output 6 Input 2 az Output 3 Note Let s[l; r] be the substring of s from the position l to the position r inclusive. Then in the first example you can remove the following substrings: * s[1; 2]; * s[1; 3]; * s[1; 4]; * s[2; 2]; * s[2; 3]; * s[2; 4]. In the second example you can remove the following substrings: * s[1; 4]; * s[1; 5]; * s[1; 6]; * s[1; 7]; * s[2; 7]; * s[3; 7]. In the third example you can remove the following substrings: * s[1; 1]; * s[1; 2]; * s[2; 2]. Submitted Solution: ``` n = int(input()) arr = input() mod = 998244353 left =0 right = 0 l = arr[0] r = arr[-1] for c in arr: if l == c: left+=1 else:break if left!=n: for c in arr[::-1]: if r == c: right+=1 else:break ans = left+right+1 if left == n: ans = n*(n+1)//2 else: if left+right == n: ans = left+right+1 else: if l == r: ans = left+(2*right)+1 else: ans = left+right+1 print(ans%mod) # print('Left:',left,'Right:',right,right+left) ``` No
10,846
Provide tags and a correct Python 3 solution for this coding contest problem. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Tags: binary search Correct Solution: ``` # -*- coding: utf-8 -*- import sys, re from collections import deque, defaultdict, Counter from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10 if sys.version_info.minor >= 5: from math import gcd else: from fractions import gcd from heapq import heappop, heappush, heapify, heappushpop from bisect import bisect_left, bisect_right from itertools import permutations, combinations, product, accumulate from operator import itemgetter, mul from copy import copy, deepcopy from functools import reduce, partial from fractions import Fraction from string import ascii_lowercase, ascii_uppercase, digits def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def round(x): return int((x*2+1) // 2) def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD def lcm(x, y): return (x * y) // gcd(x, y) def lcm_list(nums): return reduce(lcm, nums, 1) def gcd_list(nums): return reduce(gcd, nums, nums[0]) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(): return list(map(int, input().split())) sys.setrecursionlimit(10 ** 9) INF = float('inf') MOD = 10 ** 9 + 7 x,y=MAP() init=(x,y) x,y=MAP() dest=(x,y) N=INT() S=input() d=[None]*(N+1) d[0]=(0,0) for i in range(N): x,y=d[i] if S[i]=='L': x-=1 elif S[i]=='R': x+=1 elif S[i]=='U': y+=1 else: y-=1 d[i+1]=(x,y) def calc(k): a=k//N b=k%N x=init[0]+d[N][0]*a+d[b][0] y=init[1]+d[N][1]*a+d[b][1] dist=abs(x-dest[0])+abs(y-dest[1]) return dist low=0 hi=10**18 while low+1<hi: mid=(hi+low)//2 if calc(mid)<=mid: hi=mid else: low=mid if hi==10**18: print(-1) else: print(hi) ```
10,847
Provide tags and a correct Python 3 solution for this coding contest problem. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Tags: binary search Correct Solution: ``` def days(d): times = d//n more = d%n nextX = x1+(times*dayWind[-1][0]) nextY = y1+(times*dayWind[-1][1]) if more != 0: nextX += dayWind[more-1][0] nextY +=dayWind[more-1][1] return ([d,abs(x2-nextX)+abs(y2-nextY)]) x1,y1= map(int,input().split()) x2,y2= map(int,input().split()) dayWind = [] n = int(input()) forcast = list(input()) xx1 = x1 yy1 = y1 for i in forcast: if i == 'L': xx1 -= 1 elif i == 'R': xx1 += 1 elif i == 'D': yy1 -= 1 else: yy1 += 1 dayWind.append([xx1-x1,yy1-y1]) left = 1 right = 10**15 ans = [] right_value = [] while(left!=right): day = (left+right)//2 ans = days(day) if day>=ans[1]: right = day right_value = ans else: left = day+1 print(right_value[0] if len(right_value)>0 else -1) ```
10,848
Provide tags and a correct Python 3 solution for this coding contest problem. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Tags: binary search Correct Solution: ``` import sys import math from collections import defaultdict def possible(days,X,Y,n,x2,y2,x1,y1): stx,sty=(X[-1]*(days//n)),(Y[-1]*(days//n)) #print(stx,'stx',sty,'sty') a=int((days)%n) #print(days,'DAYS',n,'n',a,'a') addx,addy=X[a],Y[a] newx,newy=stx+addx,sty+addy #print(newx,'newx',newy,'newy') shipx,shipy=x2-(x1+newx),y2-(y1+newy) #print(shipx,'shipx',shipy,'shipy') if abs(shipx)+abs(shipy)<=days: return True return False x1,y1=map(int,sys.stdin.readline().split()) x2,y2=map(int,sys.stdin.readline().split()) n=int(sys.stdin.readline()) s=sys.stdin.readline()[:-1] xw,yw=0,0 xwind,ywind=[0 for _ in range(n+1)],[0 for _ in range(n+1)] delx,dely=x2-x1,y2-y1 for i in range(n): if s[i]=='U': yw+=1 if s[i]=='D': yw-=1 if s[i]=='L': xw-=1 if s[i]=='R': xw+=1 xwind[i+1]=xw ywind[i+1]=yw #print(xwind,'xwind') #print(ywind,'ywind') #print(delx,'delx',dely,'dely') low,high=0,1e15 ans=1e20 while low<=high: mid=(low+high)//2 if possible(mid,xwind,ywind,n,x2,y2,x1,y1): ans=min(ans,mid) high=mid-1 else: low=mid+1 if ans==1e20: print(-1) else: print(int(ans)) ```
10,849
Provide tags and a correct Python 3 solution for this coding contest problem. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Tags: binary search Correct Solution: ``` def check(x1,y1,x2,y2,dx,dy,mid,store,n): x=x1+dx*(mid//n) y=y1+dy*(mid//n) if mid%n!=0: y+=store[mid%n-1][1] x+=store[mid%n-1][0] if abs(x2-x)+abs(y2-y)<=mid: return True return False def f(x1,y1,x2,y2,n,s): store=[[0,0] for i in range(n)] dx=0 dy=0 for i in range(len(s)): if s[i]=="U": dy+=1 if s[i]=="D": dy-=1 if s[i]=="L": dx-=1 if s[i]=="R": dx+=1 store[i][0]=dx store[i][1]=dy lo=0 hi=10**15 ans=-1 while lo<=hi: mid=(lo+hi)//2 if check(x1,y1,x2,y2,dx,dy,mid,store,n): ans=mid hi=mid-1 else: lo=mid+1 return ans x1,y1=map(int,input().strip().split()) x2,y2=map(int,input().strip().split()) n=int(input()) s=input() print(f(x1,y1,x2,y2,n,s)) ```
10,850
Provide tags and a correct Python 3 solution for this coding contest problem. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Tags: binary search Correct Solution: ``` x1, y1 = [int(x) for x in input().split()] x2, y2 = [int(x) for x in input().split()] lens=int(input()) string=input() x = [0 for _ in range(lens + 1)] y = [0 for _ in range(lens + 1)] for i in range(lens): x[i + 1] = x[i] + (string[i] == "R") - (string[i] == "L") y[i + 1] = y[i] + (string[i] == "U") - (string[i] == "D") left = -1 rite = int(10 ** 18) ans = int(10 ** 18) + 1 while rite - left > 1: mid = (left + rite) >> 1 X = (mid // lens) * x[-1] + x[mid % lens] Y = y[-1] * (mid // lens) + y[mid % lens] X += x1 Y += y1 if abs(X - x2) + abs(Y - y2) <= mid: rite = mid else: left = mid print([rite, -1][rite == 10 ** 18]) ```
10,851
Provide tags and a correct Python 3 solution for this coding contest problem. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Tags: binary search Correct Solution: ``` x1,y1 = map(int, input().split()) x2,y2 = map(int, input().split()) n = int(input()) s = input() def dst(x1,y1,x2,y2): return abs(x2-x1) + abs(y2-y1) d = dst(x1,y1,x2,y2) dx=dy=0 ss = [] for i in range(n): if s[i] == 'U': dy += 1 elif s[i] == 'D': dy -= 1 elif s[i] == 'R': dx += 1 else: dx -=1 ss.append((dx, dy)) l = 1 r = 10**18 def check(m): c = m // n x = x1 + dx*c y = y1 + dy*c r = m % n if r != 0: x += ss[r-1][0] y += ss[r-1][1] d = dst(x2,y2,x,y) if d <= m: return True return False ans = 10**19 while r >= l: m = int((r+l) // 2) if check(m): ans = min(ans, m) r = m - 1 else: l = m + 1 if ans == 10**19: print(-1) else: print(ans) ```
10,852
Provide tags and a correct Python 3 solution for this coding contest problem. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Tags: binary search Correct Solution: ``` # Origin x1, y1 = list(map(int,input().split())) # Destination x2, y2 = list(map(int,input().split())) # Length of weather forecast n = int(input()) # Weather forecast S = input() # Storing the impact of the winds: x = 0; y = 0 WALKLIST=[(0,0)] for s in S: # Adjust location # according to the forecast if s=="U": y += 1 elif s=="D": y -= 1 elif s=="L": x -= 1 elif s=="R": x += 1 # Keep track of offsets after i days # for all 1 <= i <= n WALKLIST.append((x,y)) # Initial limits L = 0 # No need to search beyond 2*10**14 R = 10**15 impossible = False while L != R: mid = (L+R)//2 # There are Q cycles of the n-day forecast # and rem remaining days after that, # with rem < n Q,rem = divmod(mid,n) # Computing (x3,y3) x3 = x1 + Q*x + WALKLIST[rem][0] y3 = y1 + Q*y + WALKLIST[rem][1] # Computing the Manhattan distance xoffset = abs(x2 - x3) yoffset = abs(y2 - y3) if (xoffset+yoffset) <= mid: R= mid else: L= mid + 1 # If mids hit the upper limit, then there's no hope! if L==10**15: print(-1) impossible = True if not impossible: print(R) ```
10,853
Provide tags and a correct Python 3 solution for this coding contest problem. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Tags: binary search Correct Solution: ``` # The first line contains two integers x1,y1 (0≤x1,y1≤109) — the initial coordinates of the ship. st_x, st_y = map(int, input().split()) # The second line contains two integers x2,y2 (0≤x2,y2≤109) — the coordinates of the destination point. fi_x, fi_y = map(int, input().split()) # It is guaranteed that the initial coordinates and destination point coordinates are different. # The third line contains a single integer n (1≤n≤105) — the length of the string s. n = int(input()) # The fourth line contains the string s itself, consisting only of letters U, D, L and R. s = input() # #define x first # #define y second N = 100009 # pair<int, int> st, fi; # mv = "UDLR"; dx = [0, 0, -1, 1] dy = [1, -1, 0, 0] from collections import namedtuple Point = namedtuple('Point', 'x y') precalc = [Point(0, 0)] * N for i in range(n): px = 0 py = 0 if (s[i] == 'U'): py += 1 if (s[i] == 'D'): py -= 1 if (s[i] == 'R'): px += 1 if (s[i] == 'L'): px -= 1 precalc[i + 1] = Point(precalc[i].x + px, precalc[i].y + py) l = 0 r = int(1e18) while(r - l > 1): mid = (l + r) // 2 cnt = mid // n rem = mid % n # test x = st_x + precalc[rem].x + cnt * precalc[n].x y = st_y + precalc[rem].y + cnt * precalc[n].y dist = abs(x - fi_x) + abs(y - fi_y) if(dist <= mid): r = mid else: l = mid if(r > int(5e17)): r = -1 print(r) ```
10,854
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Submitted Solution: ``` x1, y1 = map(int,input().split()) x2, y2 = map(int,input().split()) n = int(input()) s = input() l = 1 r = 10**18 ans = -1 while l <= r: mid = (l + r) // 2 cx = 0 cy = 0 for z in s: if z == 'L': cx -= 1 elif z == 'R': cx += 1 elif z == 'U': cy += 1 else: cy -= 1 cnt=mid//n rem=mid%n cx = x1 + (cnt) * cx cy = y1 + (cnt) * cy for i in range(rem): z = s[i] if z == 'L': cx -= 1 elif z == 'R': cx += 1 elif z == 'U': cy += 1 else: cy -= 1 dis = abs(cx - x2) + abs(cy - y2) if dis <= mid: ans = mid r = mid - 1 else: l = mid + 1 print(ans) ``` Yes
10,855
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Submitted Solution: ``` x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) n = int(input()) s = input() U, D, L, R = 0,0,0,0 for i in range(n): if s[i] == 'U': U+=1 if s[i] == 'D': D+=1 if s[i] == 'L': L+=1 if s[i] == 'R': R+=1 xd = x2 - x1 yd = y2 - y1 xr = R - L yr = U - D def bsearch(l, r): # print('-'*20) # print('l,r', l,r) if r<l: return -1 elif l==r: return l mid = (l+r)//2 xnd = xd - (xr * mid) ynd = yd - (yr * mid) # print('xnd', xnd) # print('ynd', ynd) # print('mid * n', mid * n) # print('diff', ((abs(xnd) + abs(ynd)) - (mid * n))) if (abs(xnd) + abs(ynd)) <= (mid * n): return bsearch(l, mid-1) else: if mid == l: xnd = xd - (xr * r) ynd = yd - (yr * r) if (abs(xnd) + abs(ynd)) <= (r * n): return l else: return r return bsearch(mid, r) # print('-'*20) itrs = bsearch(0, 10**10) if itrs == -1: print(-1) exit(0) # print('-'*20) # print('itrs', itrs) xd -= (xr * itrs) yd -= (yr * itrs) ans = -1 for i in range(n): # print('xd, yd', xd, yd) if (abs(xd) + abs(yd)) <= ((itrs*n) + (i)): ans = (itrs*n) + (i) break if s[i] == 'U': yd -= 1 elif s[i] == 'D': yd += 1 elif s[i] == 'L': xd += 1 elif s[i] == 'R': xd -= 1 # print('xd, yd', xd, yd) if ans == -1 and ((abs(xd) + abs(yd)) <= ((itrs*n) + n)): ans = (itrs*n) + n print(ans) ``` Yes
10,856
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Submitted Solution: ``` from collections import Counter x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) x = x1 - x2 y = y1 - y2 xpy = x + y p2 = (abs(xpy) - 1) // 2 xmy = x - y m2 = (abs(xmy) - 1) // 2 n = int(input()) s = input().lower() c = Counter(s) dr = c['d'] + c['r'] ld = c['l'] + c['d'] lu = c['l'] + c['u'] ru = c['r'] + c['u'] def f(a, b, d, e): return a and b // (d if a < 0 else e) try: res = max(f(xpy, p2, ru, ld), f(xmy, m2, dr, lu)) except ZeroDivisionError: print('-1') else: dr *= res ld *= res lu *= res ru *= res res *= n def g(a, b, d, e): return a == 0 or (b if a < 0 else d) > e for c in s: res += 1 if c in 'dr': dr += 1 if c in 'ld': ld += 1 if c in 'lu': lu += 1 if c in 'ru': ru += 1 if g(xpy, ru, ld, p2) and g(xmy, dr, lu, m2): break print(res) ``` Yes
10,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Submitted Solution: ``` sx, sy = input().split(' ') dx, dy = input().split(' ') sx = int(sx) sy = int(sy) dx = int(dx) dy = int(dy) n = int(input()) s = input() if sx == dx and sy == dy: print(0) exit(0) low = 1 high = 5 * (10 ** 14) ans = -1 while low <= high: mid = (low + high) // 2 cx = 0 cy = 0 for c in s: if c == 'L': cx -= 1 elif c == 'R': cx += 1 elif c == 'U': cy += 1 else: cy -= 1 cx = sx + (mid // n) * cx cy = sy + (mid // n) * cy for i in range(mid % n): c = s[i] if c == 'L': cx -= 1 elif c == 'R': cx += 1 elif c == 'U': cy += 1 else: cy -= 1 dis = abs(cx - dx) + abs(cy - dy) if dis <= mid: ans = mid high = mid - 1 else: low = mid + 1 print(ans) ``` Yes
10,858
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Submitted Solution: ``` import sys x0, y0 = list(map(int, input().split(' '))) x1, y1 = list(map(int, input().split(' '))) n = int(input()) s = input() l = r = u = d = 0 if x1 > x0: r = x1 - x0 else: l = x0 - x1 if y1 > y0: u = y1 - y0 else: d = y0 - y1 if x1 == 1000000000 and y1 == 999999999: print('-1') sys.exit(0) a = l + r + u + d count2 = 0 days = 0 i = 0 rr = [] try: while True: v = s[i] if v == 'U': if u == 0: d += 1 else: u -= 1 if r > 0: r -= 1 elif l > 0: l -= 1 elif u > 0: u -= 1 elif d > 0: d -= 1 elif v == 'D': if d == 0: u += 1 else: d -= 1 if r > 0: r -= 1 elif l > 0: l -= 1 elif d > 0: d -= 1 elif u > 0: u -= 1 elif v == 'R': if r == 0: l += 1 else: r -= 1 if u > 0: u -= 1 elif d > 0: d -= 1 elif r > 0: r -= 1 elif l > 0: l -= 1 elif v == 'L': if l == 0: r += 1 else: l -= 1 if u > 0: u -= 1 elif d > 0: d -= 1 elif l > 0: l -= 1 elif r > 0: r -= 1 days += 1 if d == r == l == u == 0: break rr.append(a - r - l - u - d) i += 1 if i == n: rem = l + r + u + d change = a - rem if change <= 0: print('-1', end='') sys.exit(0) a = rem days = (rem // change + 1) * n if rem % change != 0: days += rr.index(min(rem, change)) + 1 break i = i % n except Exception as e: print(str(e)) print(days) ``` No
10,859
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Submitted Solution: ``` def f(k): div, mod = divmod(k, n) x,y = div*v[n][0]+v[mod][0], div*v[n][1]+v[mod][1] #print(x,y) if abs(x2-(x1+x))+abs(y2-(y1+y)) > k: return False return True x1,y1 = list(map(int,input().split())) x2,y2 = list(map(int,input().split())) n = int(input()) s = input() vx, vy = 0, 0 v = [(vx, vy)] for i in s: if i == 'U': vy += 1 elif i == 'D': vy -= 1 elif i == 'L': vx -= 1 else: vx += 1 v.append((vx,vy)) l = 0 #r = abs(x2-x1) + abs(y2-y1) r = 10**10 while r-l > 1: med = (r+l)//2 if f(med): r = med else: l = med if f(l): r = l if r == 10**10: print(-1) else: print(r) ``` No
10,860
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Submitted Solution: ``` def find(i,array,x1,y1,x2,y2): xadd=((i//(len(array)-1))*array[-1][0])+(array[i%(len(array)-1)][0]) yadd=((i//(len(array)-1))*array[-1][1])+(array[i%(len(array)-1)][1]) xnew=x1+xadd ynew=y1+yadd #print(xnew,ynew) diff=abs(x2-xnew)+abs(y2-ynew)-i #print(xnew,ynew,x2,y2,i) return diff def search(array,x1,y1,x2,y2): start=0 end=10**18 if(find(10**18,array,x1,y1,x2,y2)>0): return -1 else: while(end>start): mid=start+(end-start)//2 if(find(mid,array,x1,y1,x2,y2)==0): return mid elif(find(mid,array,x1,y1,x2,y2)>0): start=mid+1 else: end=mid-1 return start x1,y1=input().split() x1=int(x1) y1=int(y1) x2,y2=input().split() x2=int(x2) y2=int(y2) n=int(input()) strs=input() array=[[0,0]] i=0 while(i<len(strs)): if(strs[i]=='U'): array.append([array[-1][0],array[-1][1]+1]) elif(strs[i]=='D'): array.append([array[-1][0],array[-1][1]-1]) elif(strs[i]=='R'): array.append([array[-1][0]+1,array[-1][1]]) else: array.append([array[-1][0]-1,array[-1][1]]) i+=1 #print(find(5,array,x1,y1,x2,y2)) print(search(array,x1,y1,x2,y2)) ``` No
10,861
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You a captain of a ship. Initially you are standing in a point (x_1, y_1) (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point (x_2, y_2). You know the weather forecast — the string s of length n, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side s_1, the second day — s_2, the n-th day — s_n and (n+1)-th day — s_1 again and so on. Ship coordinates change the following way: * if wind blows the direction U, then the ship moves from (x, y) to (x, y + 1); * if wind blows the direction D, then the ship moves from (x, y) to (x, y - 1); * if wind blows the direction L, then the ship moves from (x, y) to (x - 1, y); * if wind blows the direction R, then the ship moves from (x, y) to (x + 1, y). The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point (x, y) it will move to the point (x - 1, y + 1), and if it goes the direction U, then it will move to the point (x, y + 2). You task is to determine the minimal number of days required for the ship to reach the point (x_2, y_2). Input The first line contains two integers x_1, y_1 (0 ≤ x_1, y_1 ≤ 10^9) — the initial coordinates of the ship. The second line contains two integers x_2, y_2 (0 ≤ x_2, y_2 ≤ 10^9) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer n (1 ≤ n ≤ 10^5) — the length of the string s. The fourth line contains the string s itself, consisting only of letters U, D, L and R. Output The only line should contain the minimal number of days required for the ship to reach the point (x_2, y_2). If it's impossible then print "-1". Examples Input 0 0 4 6 3 UUU Output 5 Input 0 3 0 0 3 UDD Output 3 Input 0 0 0 1 1 L Output -1 Note In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: (0, 0) → (1, 1) → (2, 2) → (3, 3) → (4, 4) → (4, 6). In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: (0, 3) → (0, 3) → (0, 1) → (0, 0). In the third example the ship can never reach the point (0, 1). Submitted Solution: ``` x1, y1 = [int(_) for _ in input().split()] x2, y2 = [int(_) for _ in input().split()] length = int(input()) string = input() wind = 0 h = [0, 0] cur_wind = [] for i in string: if i == 'U': cur_wind.append((0, 1)) h[1] += 1 elif i == 'D': cur_wind.append((0, -1)) h[1] -= 1 elif i == 'R': cur_wind.append((1, 0)) h[0] += 1 else: cur_wind.append((-1, 0)) h[0] -= 1 w = (x2 - x1, y2 - y1) def min_days(s, f): return abs(s[0] - f[0]) + abs(s[1] - f[1]) cur_pos = [x1, y1] day = 1 ans = -1 bad = False start_diff = min_days(cur_pos, (x2, y2)) cycle_diff = min_days((cur_pos[0] + h[0], cur_pos[1] + h[1]), (x2, y2)) - len(string) if start_diff == cycle_diff: bad = True if bad: print(-1) else: while True: if day > 30: break if wind == len(cur_wind): wind = 0 cur_pos[0] += cur_wind[wind][0] cur_pos[1] += cur_wind[wind][1] days = min_days(cur_pos, (x2, y2)) if days <= day: ans = day break day += 1 wind += 1 print(ans) ``` No
10,862
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n. Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries. A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it. A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1). A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r. Input The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries. The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once. The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a. The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive. Output Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise. Examples Input 3 6 3 2 1 3 1 2 3 1 2 3 1 5 2 6 3 5 Output 110 Input 2 4 3 2 1 1 1 2 2 1 2 2 3 3 4 Output 010 Note In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation. In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation. Tags: data structures, dfs and similar, dp, math, trees Correct Solution: ``` # 注意array cache順序 QQ from math import log, floor import sys """ class RMQ: ''' maximum version rmq query: max([l, r]) ''' def __init__(self, nums): size = floor(log(len(nums)) // log(2)) + 1 self.nums = [nums] for i in range(1, size): last = self.nums[-1] delta = 1 << (i-1) self.nums.append([max(last[j], last[j + delta]) for j in range(len(nums) - 2 * delta + 1)]) def query(self, l, r): delta = floor(log(r - l + 1) // log(2)) return max(self.nums[delta][l], self.nums[delta][r-2**delta+1]) """ n, m, q = map(int, sys.stdin.readline().split()) perms = list(map(int, sys.stdin.readline().split())) nums = list(map(int, sys.stdin.readline().split())) logit = floor(log(n) // log(2)) + 1 current_max_index = [-1]*(n+1) prevs = [[-1]*m for i in range(logit)] prev_map = [-2]*(n+1) for i, j in zip(perms[1:]+[perms[0]], perms): prev_map[i] = j # Update the one step case for idx, ele in enumerate(nums): prevs[0][idx] = current_max_index[prev_map[ele]] current_max_index[ele] = idx # Update the n_step table for i in range(1, logit): for idx, ele in enumerate(nums): if prevs[i-1][idx] != -1: prevs[i][idx] = prevs[i-1][prevs[i-1][idx]] prev_n = [] # Create the update sequence use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i] max_pre = -1 ran = [-1] * (m+2) for i in range(m): t = i for dim in use: t = prevs[dim][t] if t == -1: break max_pre = max(t, max_pre) ran[i] = max_pre """ for i in range(m): remain = n - 1 idx = i while remain and idx != -1: ma = floor(log(remain) // log(2)) idx = prevs[ma][idx] remain -= 2**ma prev_n.append(idx) """ #rmq = RMQ(prev_n) ans = [None]*q for i in range(q): l, r = map(int, sys.stdin.readline().split()) ans[i] = str(int(l - 1 <= ran[r-1])) print("".join(ans)) ```
10,863
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n. Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries. A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it. A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1). A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r. Input The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries. The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once. The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a. The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive. Output Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise. Examples Input 3 6 3 2 1 3 1 2 3 1 2 3 1 5 2 6 3 5 Output 110 Input 2 4 3 2 1 1 1 2 2 1 2 2 3 3 4 Output 010 Note In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation. In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation. Tags: data structures, dfs and similar, dp, math, trees Correct Solution: ``` # 注意array cache順序 QQ from math import log, floor class RMQ: ''' maximum version rmq query: max([l, r]) ''' def __init__(self, nums): size = floor(log(len(nums)) // log(2)) + 1 self.nums = [nums] for i in range(1, size): last = self.nums[-1] delta = 1 << (i-1) self.nums.append([max(last[j], last[j + delta]) for j in range(len(nums) - 2 * delta + 1)]) def query(self, l, r): delta = floor(log(r - l + 1) // log(2)) return max(self.nums[delta][l], self.nums[delta][r-2**delta+1]) n, m, q = map(int, input().split()) perms = list(map(int, input().split())) nums = list(map(int, input().split())) logit = floor(log(n) // log(2)) + 1 current_max_index = [-1]*(n+1) prevs = [[-1]*m for i in range(logit)] prev_map = [-2]*(n+1) for i, j in zip(perms[1:]+[perms[0]], perms): prev_map[i] = j # Update the one step case for idx, ele in enumerate(nums): prevs[0][idx] = current_max_index[prev_map[ele]] current_max_index[ele] = idx # Update the n_step table for i in range(1, logit): for idx, ele in enumerate(nums): if prevs[i-1][idx] != -1: prevs[i][idx] = prevs[i-1][prevs[i-1][idx]] prev_n = [] # Create the update sequence use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i] max_pre = -1 ran = [-1] * (m+2) for i in range(m): t = i for dim in use: t = prevs[dim][t] if t == -1: break max_pre = max(t, max_pre) ran[i] = max_pre """ for i in range(m): remain = n - 1 idx = i while remain and idx != -1: ma = floor(log(remain) // log(2)) idx = prevs[ma][idx] remain -= 2**ma prev_n.append(idx) """ #rmq = RMQ(prev_n) ans = [] for i in range(q): l, r = map(int, input().split()) if ran[r-1] >= l - 1: ans.append("1") else: ans.append("0") print("".join(ans)) ```
10,864
Provide tags and a correct Python 3 solution for this coding contest problem. Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n. Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries. A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it. A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1). A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r. Input The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries. The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once. The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a. The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive. Output Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise. Examples Input 3 6 3 2 1 3 1 2 3 1 2 3 1 5 2 6 3 5 Output 110 Input 2 4 3 2 1 1 1 2 2 1 2 2 3 3 4 Output 010 Note In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation. In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation. Tags: data structures, dfs and similar, dp, math, trees Correct Solution: ``` # 注意array cache順序 QQ from math import log, floor """ class RMQ: ''' maximum version rmq query: max([l, r]) ''' def __init__(self, nums): size = floor(log(len(nums)) // log(2)) + 1 self.nums = [nums] for i in range(1, size): last = self.nums[-1] delta = 1 << (i-1) self.nums.append([max(last[j], last[j + delta]) for j in range(len(nums) - 2 * delta + 1)]) def query(self, l, r): delta = floor(log(r - l + 1) // log(2)) return max(self.nums[delta][l], self.nums[delta][r-2**delta+1]) """ n, m, q = map(int, input().split()) perms = list(map(int, input().split())) nums = list(map(int, input().split())) logit = floor(log(n) // log(2)) + 1 current_max_index = [-1]*(n+1) prevs = [[-1]*m for i in range(logit)] prev_map = [-2]*(n+1) for i, j in zip(perms[1:]+[perms[0]], perms): prev_map[i] = j # Update the one step case for idx, ele in enumerate(nums): prevs[0][idx] = current_max_index[prev_map[ele]] current_max_index[ele] = idx # Update the n_step table for i in range(1, logit): for idx, ele in enumerate(nums): if prevs[i-1][idx] != -1: prevs[i][idx] = prevs[i-1][prevs[i-1][idx]] prev_n = [] # Create the update sequence use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i] max_pre = -1 ran = [-1] * (m+2) for i in range(m): t = i for dim in use: t = prevs[dim][t] if t == -1: break max_pre = max(t, max_pre) ran[i] = max_pre """ for i in range(m): remain = n - 1 idx = i while remain and idx != -1: ma = floor(log(remain) // log(2)) idx = prevs[ma][idx] remain -= 2**ma prev_n.append(idx) """ #rmq = RMQ(prev_n) ans = [None]*q for i in range(q): l, r = map(int, input().split()) ans[i] = str(int(l - 1 <= ran[r-1])) print("".join(ans)) ```
10,865
Provide tags and a correct Python 3 solution for this coding contest problem. During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters). Katie has a favorite string s and a not-so-favorite string t and she would love to recover the mysterious code so that it has as many occurrences of s as possible and as little occurrences of t as possible. Formally, let's denote f(x, y) as the number of occurrences of y in x (for example, f(aababa, ab) = 2). Katie wants to recover the code c' conforming to the original c, such that f(c', s) - f(c', t) is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out. Input The first line contains string c (1 ≤ |c| ≤ 1000) — the mysterious code . It is guaranteed that c consists of lowercase English characters and asterisks "*" only. The second and third line contain strings s and t respectively (1 ≤ |s|, |t| ≤ 50, s ≠ t). It is guaranteed that s and t consist of lowercase English characters only. Output Print a single integer — the largest possible value of f(c', s) - f(c', t) of the recovered code. Examples Input ***** katie shiro Output 1 Input caat caat a Output -1 Input *a* bba b Output 0 Input *** cc z Output 2 Note In the first example, for c' equal to "katie" f(c', s) = 1 and f(c', t) = 0, which makes f(c', s) - f(c', t) = 1 which is the largest possible. In the second example, the only c' conforming to the given c is "caat". The corresponding f(c', s) - f(c', t) = 1 - 2 = -1. In the third example, there are multiple ways to recover the code such that f(c', s) - f(c', t) is largest possible, for example "aaa", "aac", or even "zaz". The value of f(c', s) - f(c', t) = 0 for all of these recovered codes. In the fourth example, the optimal recovered code c' would be "ccc". The corresponding f(c', s) - f(c', t) = 2. Tags: dp, strings Correct Solution: ``` import sys from array import array # noqa: F401 from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def build_next_table(s): s = '*' + s + '*' n = len(s) - 1 kmp = [0] * (n + 1) next_table = [[0] * 26 for _ in range(n + 1)] for i in range(2, n + 1): cur = kmp[i - 1] while cur > 0 and s[cur + 1] != s[i]: cur = kmp[cur] if s[cur + 1] == s[i]: cur += 1 kmp[i] = cur alphabet = [chr(cc) for cc in range(97, 123)] for i in range(n): for j, c in enumerate(alphabet): cur = i while 0 < cur and s[cur + 1] != c: cur = kmp[cur] if s[cur + 1] == c: cur += 1 next_table[i][j] = cur return next_table def main(): code = input().rstrip() s, t = input().rstrip(), input().rstrip() table_s = build_next_table(s) table_t = build_next_table(t) n, m, l = len(code), len(s), len(t) minf = -10**9 dp = [[array('i', [minf]) * (l + 1) for _ in range(m + 1)] for _ in range(n + 1)] dp[0][0][0] = 0 alphabet = list(range(26)) for i in range(n): itr = [ord(code[i]) - 97] if code[i] != '*' else alphabet for j in range(m + 1): for k in range(l + 1): for cc in itr: nj, nk = table_s[j][cc], table_t[k][cc] dp[i + 1][nj][nk] = max(dp[i + 1][nj][nk], dp[i][j][k] + (1 if nj == m else 0) - (1 if nk == l else 0)) ans = minf for j in range(m + 1): for k in range(l + 1): ans = max(ans, dp[n][j][k]) print(ans) if __name__ == '__main__': main() ```
10,866
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters). Katie has a favorite string s and a not-so-favorite string t and she would love to recover the mysterious code so that it has as many occurrences of s as possible and as little occurrences of t as possible. Formally, let's denote f(x, y) as the number of occurrences of y in x (for example, f(aababa, ab) = 2). Katie wants to recover the code c' conforming to the original c, such that f(c', s) - f(c', t) is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out. Input The first line contains string c (1 ≤ |c| ≤ 1000) — the mysterious code . It is guaranteed that c consists of lowercase English characters and asterisks "*" only. The second and third line contain strings s and t respectively (1 ≤ |s|, |t| ≤ 50, s ≠ t). It is guaranteed that s and t consist of lowercase English characters only. Output Print a single integer — the largest possible value of f(c', s) - f(c', t) of the recovered code. Examples Input ***** katie shiro Output 1 Input caat caat a Output -1 Input *a* bba b Output 0 Input *** cc z Output 2 Note In the first example, for c' equal to "katie" f(c', s) = 1 and f(c', t) = 0, which makes f(c', s) - f(c', t) = 1 which is the largest possible. In the second example, the only c' conforming to the given c is "caat". The corresponding f(c', s) - f(c', t) = 1 - 2 = -1. In the third example, there are multiple ways to recover the code such that f(c', s) - f(c', t) is largest possible, for example "aaa", "aac", or even "zaz". The value of f(c', s) - f(c', t) = 0 for all of these recovered codes. In the fourth example, the optimal recovered code c' would be "ccc". The corresponding f(c', s) - f(c', t) = 2. Submitted Solution: ``` def solve(u: str, s: str, t: str) -> int: def cnt(s: str, t: str) -> int: count = 0 for i in range(len(s) - len(t) + 1): if s[i:i+len(t)] == t: count += 1 return count def can(start: int) -> bool: for i in range(len(s)): if u[start + i] != s[i] and u[start + i] != '*': return False return True u = list(u) s = list(s) t = list(t) for i in range(len(u) - len(s) + 1): if can(i): orig = u[i:i+len(s)] cnt1 = cnt(u[max(0, i - len(t) + 1):min(len(u), i + len(s) + len(t) - 1)], t) for j in range(len(s)): u[i + j] = s[j] cnt2 = cnt(u[max(0, i - len(t) + 1):min(len(u), i + len(s) + len(t) - 1)], t) if cnt1 < cnt2: for j in range(len(s)): u[i + j] = orig[j] return cnt(u, s) - cnt(u, t) def main(): c = input() s, t = input(), input() ret = solve(c,s,t) print(ret) if __name__ == "__main__": main() ``` No
10,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters). Katie has a favorite string s and a not-so-favorite string t and she would love to recover the mysterious code so that it has as many occurrences of s as possible and as little occurrences of t as possible. Formally, let's denote f(x, y) as the number of occurrences of y in x (for example, f(aababa, ab) = 2). Katie wants to recover the code c' conforming to the original c, such that f(c', s) - f(c', t) is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out. Input The first line contains string c (1 ≤ |c| ≤ 1000) — the mysterious code . It is guaranteed that c consists of lowercase English characters and asterisks "*" only. The second and third line contain strings s and t respectively (1 ≤ |s|, |t| ≤ 50, s ≠ t). It is guaranteed that s and t consist of lowercase English characters only. Output Print a single integer — the largest possible value of f(c', s) - f(c', t) of the recovered code. Examples Input ***** katie shiro Output 1 Input caat caat a Output -1 Input *a* bba b Output 0 Input *** cc z Output 2 Note In the first example, for c' equal to "katie" f(c', s) = 1 and f(c', t) = 0, which makes f(c', s) - f(c', t) = 1 which is the largest possible. In the second example, the only c' conforming to the given c is "caat". The corresponding f(c', s) - f(c', t) = 1 - 2 = -1. In the third example, there are multiple ways to recover the code such that f(c', s) - f(c', t) is largest possible, for example "aaa", "aac", or even "zaz". The value of f(c', s) - f(c', t) = 0 for all of these recovered codes. In the fourth example, the optimal recovered code c' would be "ccc". The corresponding f(c', s) - f(c', t) = 2. Submitted Solution: ``` def solve(c,s,t): if len(c)>1: return True; else: return False; def main(): c = input() s, t = input(), input() ret = solve(c,s,t) if ret==True: print("YES") else: print("NO") ``` No
10,868
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters). Katie has a favorite string s and a not-so-favorite string t and she would love to recover the mysterious code so that it has as many occurrences of s as possible and as little occurrences of t as possible. Formally, let's denote f(x, y) as the number of occurrences of y in x (for example, f(aababa, ab) = 2). Katie wants to recover the code c' conforming to the original c, such that f(c', s) - f(c', t) is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out. Input The first line contains string c (1 ≤ |c| ≤ 1000) — the mysterious code . It is guaranteed that c consists of lowercase English characters and asterisks "*" only. The second and third line contain strings s and t respectively (1 ≤ |s|, |t| ≤ 50, s ≠ t). It is guaranteed that s and t consist of lowercase English characters only. Output Print a single integer — the largest possible value of f(c', s) - f(c', t) of the recovered code. Examples Input ***** katie shiro Output 1 Input caat caat a Output -1 Input *a* bba b Output 0 Input *** cc z Output 2 Note In the first example, for c' equal to "katie" f(c', s) = 1 and f(c', t) = 0, which makes f(c', s) - f(c', t) = 1 which is the largest possible. In the second example, the only c' conforming to the given c is "caat". The corresponding f(c', s) - f(c', t) = 1 - 2 = -1. In the third example, there are multiple ways to recover the code such that f(c', s) - f(c', t) is largest possible, for example "aaa", "aac", or even "zaz". The value of f(c', s) - f(c', t) = 0 for all of these recovered codes. In the fourth example, the optimal recovered code c' would be "ccc". The corresponding f(c', s) - f(c', t) = 2. Submitted Solution: ``` c = input() s = input() t = input() def match(a, b): if len(a) != len(b): return False i = 0 while i < len(a) and (a[i] == b[i] or a[i] == '*'): i += 1 return i == len(a) i = 0 score = 0 while i < len(c): if match(c[i:i+len(s)], s): c = c[:i] + s + c[i+len(s):] score += 1 if c[i:i+len(t)] == t: score -= 1 i += 1 print(score) ``` No
10,869
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. During a normal walk in the forest, Katie has stumbled upon a mysterious code! However, the mysterious code had some characters unreadable. She has written down this code as a string c consisting of lowercase English characters and asterisks ("*"), where each of the asterisks denotes an unreadable character. Excited with her discovery, Katie has decided to recover the unreadable characters by replacing each asterisk with arbitrary lowercase English letter (different asterisks might be replaced with different letters). Katie has a favorite string s and a not-so-favorite string t and she would love to recover the mysterious code so that it has as many occurrences of s as possible and as little occurrences of t as possible. Formally, let's denote f(x, y) as the number of occurrences of y in x (for example, f(aababa, ab) = 2). Katie wants to recover the code c' conforming to the original c, such that f(c', s) - f(c', t) is largest possible. However, Katie is not very good at recovering codes in general, so she would like you to help her out. Input The first line contains string c (1 ≤ |c| ≤ 1000) — the mysterious code . It is guaranteed that c consists of lowercase English characters and asterisks "*" only. The second and third line contain strings s and t respectively (1 ≤ |s|, |t| ≤ 50, s ≠ t). It is guaranteed that s and t consist of lowercase English characters only. Output Print a single integer — the largest possible value of f(c', s) - f(c', t) of the recovered code. Examples Input ***** katie shiro Output 1 Input caat caat a Output -1 Input *a* bba b Output 0 Input *** cc z Output 2 Note In the first example, for c' equal to "katie" f(c', s) = 1 and f(c', t) = 0, which makes f(c', s) - f(c', t) = 1 which is the largest possible. In the second example, the only c' conforming to the given c is "caat". The corresponding f(c', s) - f(c', t) = 1 - 2 = -1. In the third example, there are multiple ways to recover the code such that f(c', s) - f(c', t) is largest possible, for example "aaa", "aac", or even "zaz". The value of f(c', s) - f(c', t) = 0 for all of these recovered codes. In the fourth example, the optimal recovered code c' would be "ccc". The corresponding f(c', s) - f(c', t) = 2. Submitted Solution: ``` def solve(c,s,t): if len(c)>1: return True; else: return False; def main(): c = input() s, t = input(), input() ret = solve(c,s,t) if ret==True: print(1) else: print(2) if __name__ == "__main__": main() ``` No
10,870
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You, the mighty Blackout, are standing in the upper-left (0,0) corner of NxM matrix. You must move either right or down each second. There are K transformers jumping around the matrix in the following way. Each transformer starts jumping from position (x,y), at time t, and jumps to the next position each second. The x-axes grows downwards, and y-axes grows to the right. The order of jumping positions is defined as {(x,y),(x+d,y-d),(x+d,y),(x,y+d)}, and is periodic. Before time t transformer is not in the matrix. You want to arrive to the bottom-right corner (N-1,M-1), while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer. After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted. Input In the first line, integers N,M (1 ≤ N, M ≤ 500), representing size of the matrix, and K (0 ≤ K ≤ 5*10^5) , the number of jumping transformers. In next K lines, for each transformer, numbers x, y, d (d ≥ 1), t (0 ≤ t ≤ N+M-2), and e (0 ≤ e ≤ 10^9), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it. It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinates Output Print single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner. Example Input 3 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 Output 9 Note If Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value. Submitted Solution: ``` fst_line = input() fst_line = fst_line.split(' ') n, m, k = [int(var) for var in fst_line] enemies = [] for _ in range(k): tmp_line = input() tmp_line = tmp_line.split(' ') enemies.append([int(var) for var in tmp_line]) # x y d t e best_score = 99999999 def calculate_position(x, y, d, t_e, t): if t >= t_e: step = (t - t_e) % 4 if step == 0: return x, y elif step == 1: return x + d, y - d elif step == 2: return x + d, y else: return x, y + d def simulate(n, m, x, y, t, score, living_enemies): global best_score if score >= best_score: pass if n - 1 == x and m - 1 == y: best_score = score else: for enemy_index in living_enemies[::-1]: x_e, y_e, d_e, t_e, e_e = enemies[enemy_index] if t_e > t: continue tmp_x, tmp_y = calculate_position(x_e, y_e, d_e, t_e, t) if x == tmp_x and y == tmp_y: score += e_e living_enemies.remove(enemy_index) if x + 1 < n: simulate(n, m, x + 1, y, t + 1, score, living_enemies.copy()) if y + 1 < m: simulate(n, m, x, y + 1, t + 1, score, living_enemies.copy()) simulate(n, m, 0, 0, 0, 0, [enemy_index for enemy_index in range(len(enemies))]) print(best_score) ``` No
10,871
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You, the mighty Blackout, are standing in the upper-left (0,0) corner of NxM matrix. You must move either right or down each second. There are K transformers jumping around the matrix in the following way. Each transformer starts jumping from position (x,y), at time t, and jumps to the next position each second. The x-axes grows downwards, and y-axes grows to the right. The order of jumping positions is defined as {(x,y),(x+d,y-d),(x+d,y),(x,y+d)}, and is periodic. Before time t transformer is not in the matrix. You want to arrive to the bottom-right corner (N-1,M-1), while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer. After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted. Input In the first line, integers N,M (1 ≤ N, M ≤ 500), representing size of the matrix, and K (0 ≤ K ≤ 5*10^5) , the number of jumping transformers. In next K lines, for each transformer, numbers x, y, d (d ≥ 1), t (0 ≤ t ≤ N+M-2), and e (0 ≤ e ≤ 10^9), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it. It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinates Output Print single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner. Example Input 3 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 Output 9 Note If Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value. Submitted Solution: ``` # -*- coding: utf-8 -*-+ """ Created on Sun Jan 12 10:20:32 2020 @author: Rodro """ inp = str(input()).split() n = int(inp[0]) m = int(inp[1]) k = int(inp[2]) oo = 1e20 mcost = [ [[0, 0] for __ in range(n)] for _ in range(m)]#[i][j][k] donde k define de el costo de venir de la izk(k = 0) o de la derecha(k = 1) mmove = [[[oo, oo] for __ in range(n)] for _ in range(m)]#[i][j][k] donde k indica moverse a la derecha(k = 0) o hacia abajo(k = 1) mpend = [[[[], []] for __ in range(n)] for _ in range(m)]#[i][j][k] se guarda posible posiciones de un trabsformador si es posible qye haya #sido asesinado previamente. y por tanto no haga falta matarlo k = 1 implica que se vino de arriba, #k = 0 de la izq. for _ in range(k): inp = str(input()).split() x, y, d, t, e = int(inp[0]), int(inp[1]), int(inp[2]), int(inp[3]), int(inp[4]) z = x + y p0 = z >= t and 0 == (z - t)%4 p1 = z >= t + 1 and 0 == (z - t - 1)%4 p2 = z + d >= t + 2 and 0 == (z + d - t - 2)%4 p3 = z + d >= t + 3 and 0 == (z + d - t - 3)%4 if p0: mcost[y][x][0] += e mcost[y][x][1] += e if p1: mcost[y - d][x + d][0] += e mcost[y - d][x + d][1] += e if p2: if p0: mpend[y][x + d][0].append((y - d, e)) else: mcost[y][x + d][0] += e if p1: mpend[y][x + d][1].append((x, e)) else: mcost[y][x + d][1] += e if p3: if p0: mpend[y + d][x][1].append((x, e)) else: mcost[y + d][x][1] += e mcost[y + d][x][0] += e for i in range(m): for j in range(n): sorted(mpend[i][j][0]) sorted(mpend[i][j][1]) mmove[0][0][0] = mmove[0][0][1] = 0 for i in range(m): for j in range(n): cost = 0 for k in range(j + 1, n): while(len(mpend[i][k][0]) > 0) and mpend[i][k][0][-1][0] < j: mcost[i][k][0] += mpend[i][k][0][-1][1] mpend[i][k][0].pop() cost += mcost[i][k][0] mmove[i][k][0] = min(mmove[i][k][0], mmove[i][j][1] + cost) cost = 0 for k in range(i + 1, m): while(len(mpend[k][j][1]) > 0 and mpend[k][j][1][-1][0] < i): mcost[k][j][1] += mpend[k][j][1][-1][1] mpend[k][j][1].pop() cost += mcost[k][j][1] mmove[k][j][1] = min(mmove[k][j][1], mmove[i][j][0] + cost) print("Respuesta", min(mmove[m - 1][n - 1][0], mmove[m - 1][n - 1][1])) #print(mmove) #print("##############") #print(mcost) ``` No
10,872
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You, the mighty Blackout, are standing in the upper-left (0,0) corner of NxM matrix. You must move either right or down each second. There are K transformers jumping around the matrix in the following way. Each transformer starts jumping from position (x,y), at time t, and jumps to the next position each second. The x-axes grows downwards, and y-axes grows to the right. The order of jumping positions is defined as {(x,y),(x+d,y-d),(x+d,y),(x,y+d)}, and is periodic. Before time t transformer is not in the matrix. You want to arrive to the bottom-right corner (N-1,M-1), while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer. After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted. Input In the first line, integers N,M (1 ≤ N, M ≤ 500), representing size of the matrix, and K (0 ≤ K ≤ 5*10^5) , the number of jumping transformers. In next K lines, for each transformer, numbers x, y, d (d ≥ 1), t (0 ≤ t ≤ N+M-2), and e (0 ≤ e ≤ 10^9), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it. It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinates Output Print single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner. Example Input 3 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 Output 9 Note If Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value. Submitted Solution: ``` fst_line = input() fst_line = fst_line.split(' ') n, m, k = [int(var) for var in fst_line] enemies = [] for _ in range(k): tmp_line = input() tmp_line = tmp_line.split(' ') enemies.append([int(var) for var in tmp_line]) # x y d t e best_score = 99999999 def calculate_position(x, y, d, t_e, t): if t >= t_e: step = (t - t_e) % 4 if step == 0: return x, y elif step == 1: return x + d, y - d elif step == 2: return x + d, y else: return x, y + d def simulate(n, m, x, y, t, score, living_enemies): global best_score if score >= best_score: pass if n - 1 == x and m - 1 == y: best_score = score else: for enemy_index in living_enemies[::-1]: x_e, y_e, d_e, t_e, e_e = enemies[enemy_index] if t_e > t: continue tmp_x, tmp_y = calculate_position(x_e, y_e, d_e, t_e, t) if x == tmp_x and y == tmp_y: score += e_e living_enemies.remove(enemy_index) if x + 1 < n: simulate(n, m, x + 1, y, t + 1, score, living_enemies.copy()) if y + 1 < m: simulate(n, m, x, y + 1, t + 1, score, living_enemies.copy()) simulate(n, m, 0, 0, 0, 0, [enemy_index for enemy_index in range(len(enemies))]) print(best_score-1) ``` No
10,873
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You, the mighty Blackout, are standing in the upper-left (0,0) corner of NxM matrix. You must move either right or down each second. There are K transformers jumping around the matrix in the following way. Each transformer starts jumping from position (x,y), at time t, and jumps to the next position each second. The x-axes grows downwards, and y-axes grows to the right. The order of jumping positions is defined as {(x,y),(x+d,y-d),(x+d,y),(x,y+d)}, and is periodic. Before time t transformer is not in the matrix. You want to arrive to the bottom-right corner (N-1,M-1), while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer. After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted. Input In the first line, integers N,M (1 ≤ N, M ≤ 500), representing size of the matrix, and K (0 ≤ K ≤ 5*10^5) , the number of jumping transformers. In next K lines, for each transformer, numbers x, y, d (d ≥ 1), t (0 ≤ t ≤ N+M-2), and e (0 ≤ e ≤ 10^9), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it. It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinates Output Print single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner. Example Input 3 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 Output 9 Note If Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value. Submitted Solution: ``` fst_line = input() fst_line = fst_line.split(' ') n, m, k = [int(var) for var in fst_line] enemies = [] for _ in range(k): tmp_line = input() tmp_line = tmp_line.split(' ') enemies.append([int(var) for var in tmp_line]) # x y d t e enemies_indices = [index for index in range(len(enemies))] best_score = 99999999 def calculate_position(x, y, d, t_e, t): if t >= t_e: step = (t - t_e) % 4 if step == 0: return x, y elif step == 1: return x + d, y - d elif step == 2: return x + d, y else: return x, y + d def simulate(n, m, x, y, t, score, living_enemies): global best_score if score >= best_score: pass if n - 1 == x and m - 1 == y and score < best_score: best_score = score else: for enemy_index in living_enemies[::-1]: x_e, y_e, d_e, t_e, e_e = enemies[enemy_index] if t_e > t: continue tmp_x, tmp_y = calculate_position(x_e, y_e, d_e, t_e, t) if x == tmp_x and y == tmp_y: score += e_e living_enemies.remove(enemy_index) if x + 1 < n: simulate(n, m, x + 1, y, t + 1, score, living_enemies.copy()) if y + 1 < m: simulate(n, m, x, y + 1, t + 1, score, living_enemies.copy()) simulate(n, m, 0, 0, 0, 0, enemies_indices) print(best_score) ``` No
10,874
Provide tags and a correct Python 3 solution for this coding contest problem. Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers. There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct. Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box. Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be? Input The first line contains a single integer k (1 ≤ k ≤ 15), the number of boxes. The i-th of the next k lines first contains a single integer n_i (1 ≤ n_i ≤ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, …, a_{i,n_i} (|a_{i,j}| ≤ 10^9), the integers in the i-th box. It is guaranteed that all a_{i,j} are distinct. Output If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards. If there are multiple solutions, output any of those. You can print each letter in any case (upper or lower). Examples Input 4 3 1 7 4 2 3 2 2 8 5 1 10 Output Yes 7 2 2 3 5 1 10 4 Input 2 2 3 -2 2 -1 5 Output No Input 2 2 -10 10 2 0 -20 Output Yes -10 2 -20 1 Note In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10. In the second sample, it is not possible to pick and redistribute the numbers in the required way. In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10. Tags: bitmasks, dfs and similar, dp, graphs Correct Solution: ``` import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ k = int(input()) d = {} aa = [] sa = [] for i in range(k): ni, *a = map(int, input().split()) for ai in a: d[ai] = i aa.append(a) sa.append(sum(a)) s = sum(sa) if s%k != 0: print("No") exit() s //= k def calc_next(i, aij): bij = s-sa[i]+aij if bij not in d: return -1, bij else: return d[bij], bij def loop_to_num(loop): ret = 0 for i in reversed(range(k)): ret <<= 1 ret += loop[i] return ret loop_dict = {} used = set() for i in range(k): for aij in aa[i]: if aij in used: continue loop = [0]*k num = [float("Inf")]*k start_i = i start_aij = aij j = i loop[j] = 1 num[j] = aij used.add(aij) exist = False for _ in range(100): j, aij = calc_next(j, aij) if j == -1: break #used.add(aij) if loop[j] == 0: loop[j] = 1 num[j] = aij else: if j == start_i and aij == start_aij: exist = True break if exist: m = loop_to_num(loop) loop_dict[m] = tuple(num) for numi in num: if numi != float("inf"): used.add(numi) mask = 1<<k for state in range(1, mask): if state in loop_dict: continue j = (state-1)&state while j: i = state^j if i in loop_dict and j in loop_dict: tp = tuple(min(loop_dict[i][l], loop_dict[j][l]) for l in range(k)) loop_dict[state] = tp break j = (j-1)&state if mask-1 not in loop_dict: print("No") else: print("Yes") t = loop_dict[mask-1] ns = [sa[i]-t[i] for i in range(k)] need = [s - ns[i] for i in range(k)] for i in range(k): print(t[i], need.index(t[i])+1) ```
10,875
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers. There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct. Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box. Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be? Input The first line contains a single integer k (1 ≤ k ≤ 15), the number of boxes. The i-th of the next k lines first contains a single integer n_i (1 ≤ n_i ≤ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, …, a_{i,n_i} (|a_{i,j}| ≤ 10^9), the integers in the i-th box. It is guaranteed that all a_{i,j} are distinct. Output If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards. If there are multiple solutions, output any of those. You can print each letter in any case (upper or lower). Examples Input 4 3 1 7 4 2 3 2 2 8 5 1 10 Output Yes 7 2 2 3 5 1 10 4 Input 2 2 3 -2 2 -1 5 Output No Input 2 2 -10 10 2 0 -20 Output Yes -10 2 -20 1 Note In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10. In the second sample, it is not possible to pick and redistribute the numbers in the required way. In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10. Submitted Solution: ``` import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ k = int(input()) d = {} aa = [] sa = [] for i in range(k): ni, *a = map(int, input().split()) for ai in a: d[ai] = i aa.append(a) sa.append(sum(a)) s = sum(sa) if s%k != 0: print("No") exit() s //= k def calc_next(i, aij): bij = s-sa[i]+aij if bij not in d: return -1, bij else: return d[bij], bij def loop_to_num(loop): ret = 0 for i in reversed(range(k)): ret <<= 1 ret += loop[i] return ret loop_dict = {} used = set() for i in range(k): for aij in aa[i]: if aij in used: continue loop = [0]*k num = [float("Inf")]*k start_i = i start_aij = aij j = i loop[j] = 1 num[j] = aij used.add(aij) exist = False for _ in range(100): j, aij = calc_next(j, aij) if j == -1: break used.add(aij) if loop[j] == 0: loop[j] = 1 num[j] = aij else: if j == start_i and aij == start_aij: exist = True break if exist: m = loop_to_num(loop) loop_dict[m] = tuple(num) mask = 1<<k for state in range(1, mask): if state in loop_dict: continue j = (state-1)&state while j: i = state^j if i in loop_dict and j in loop_dict: tp = tuple(min(loop_dict[i][l], loop_dict[j][l]) for l in range(k)) loop_dict[state] = tp break j = (j-1)&state if mask-1 not in loop_dict: print("No") else: print("Yes") t = loop_dict[mask-1] ns = [sa[i]-t[i] for i in range(k)] need = [s - ns[i] for i in range(k)] for i in range(k): print(t[i], need.index(t[i])+1) ``` No
10,876
Provide tags and a correct Python 3 solution for this coding contest problem. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Tags: dfs and similar, dsu, graphs Correct Solution: ``` from sys import stdin,stdout from collections import defaultdict as df import sys sys.setrecursionlimit(10**4) def dfs(i): visited[i]=True for j in d1[p[i]]: if visited[d[j]]==False: dfs(d[j]) d=dict() j=0 p=dict() for i in range(97,97+26): d[chr(i)]=j p[j]=chr(i) j+=1 d1=df(set) gota=0 hot=dict() mota=set() n=int(stdin.readline()) y=set() for ii in range(n): s=stdin.readline().rstrip() if s in hot: continue else: hot[s]=1 s=[i for i in s] s=list(set(s)) for i in s: y.add(i) for i in range(len(s)): if len(d1[s[i]])==25: continue for j in range(i+1,len(s)): if i==j: continue else: d1[s[i]].add(s[j]) d1[s[j]].add(s[i]) visited=[0]*26 count=0 for i in range(26): if visited[i]==False and p[i] in y: count+=1 dfs(i) stdout.write(str(count)) ```
10,877
Provide tags and a correct Python 3 solution for this coding contest problem. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Tags: dfs and similar, dsu, graphs Correct Solution: ``` from sys import stdin input = stdin.readline if __name__ == '__main__': pdct = {} for _ in range(int(input())): s = input().strip() for c in s: if c not in pdct: pdct[c] = c l = list(filter(lambda o: pdct[o] != o, s)) if not l: p = s[0] else: p = l[0] while pdct[p] != p: p = pdct[p] for c in s: cc = c while pdct[cc] != cc: cc = pdct[cc] pdct[cc] = p cnt = 0 for k, v in pdct.items(): cnt += int(k == v) print(cnt) ```
10,878
Provide tags and a correct Python 3 solution for this coding contest problem. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Tags: dfs and similar, dsu, graphs Correct Solution: ``` def union(x, y): xr = find(x) yr = find(y) root[yr] = xr def find(x): if root[x] != x: x = find(root[x]) return x import sys input = sys.stdin.readline used = set() root = dict() for _ in range(int(input())): s = input().rstrip() for j in s: if ord(j) - 97 not in root: root[ord(j) - 97] = ord(j) - 97 union(ord(s[0]) - 97, ord(j) - 97) for i in root: used.add(find(root[i])) print(used.__len__()) ```
10,879
Provide tags and a correct Python 3 solution for this coding contest problem. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Tags: dfs and similar, dsu, graphs Correct Solution: ``` from collections import deque from sys import stdin, stdout read, whrite = stdin.readline, stdout.write g = [[] for i in range(300000)] visited = [False] * 300000 def dfs(i): pilha = deque() pilha.append(i) visited[i] = 1 while pilha: i = pilha.pop() for v in g[i]: if not visited[v]: visited[v] = True pilha.append(v) n = int(read()) for i in range(n): word = read().strip() for j in word: g[i].append(n + ord(j)) g[n + ord(j)].append(i) resp = 0 for i in range(n): if not visited[i]: dfs(i) resp += 1 print(resp) ```
10,880
Provide tags and a correct Python 3 solution for this coding contest problem. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Tags: dfs and similar, dsu, graphs Correct Solution: ``` import os import sys from io import BytesIO, IOBase import math from decimal import Decimal from decimal import * from collections import defaultdict, deque import heapq from decimal import Decimal getcontext().prec = 25 abcd='abcdefghijklmnopqrstuvwxyz' MOD = pow(10, 9) + 7 BUFSIZE = 8192 from bisect import bisect_left, bisect_right 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") # n, k = map(int, input().split(" ")) # list(map(int, input().split(" "))) # for _ in range(int(input())): def dfs(i): q = deque() q.append(i) while q: x = q.popleft() if not v[x]: v[x]=True for f in g[x]: if not v[f]: q.append(f) n = int(input()) g = [set() for i in range(26)] for i in range(n): a = set(list(input())) for j in a: for k in a: g[ord(k)-ord("a")].add(ord(j)-ord("a")) v = [0]*26 ans = 0 for i in range(26): if not v[i]: if g[i]: dfs(i) ans+=1 else: v[i]=True print(ans) ```
10,881
Provide tags and a correct Python 3 solution for this coding contest problem. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Tags: dfs and similar, dsu, graphs Correct Solution: ``` ## necessary imports import sys input = sys.stdin.readline from math import ceil, floor, factorial; # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp ## gcd function def gcd(a,b): if a == 0: return b return gcd(b%a, a) ## nCr function efficient using Binomial Cofficient def nCr(n, k): if(k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## upper bound function code -- such that e in a[:i] e < x; def upper_bound(a, x, lo=0): hi = len(a) while lo < hi: mid = (lo+hi)//2 if a[mid] < x: lo = mid+1 else: hi = mid return lo ## prime factorization def primefs(n): ## if n == 1 ## calculating primes primes = {} while(n%2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n//2 for i in range(3, int(n**0.5)+2, 2): while(n%i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n//i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION 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 x = (x * x) % p return res ## DISJOINT SET UNINON FUNCTIONS def swap(a,b): temp = a a = b b = temp return a,b # find function with path compression included (recursive) # def find(x, link): # if link[x] == x: # return x # link[x] = find(link[x], link); # return link[x]; # find function with path compression (ITERATIVE) def find(x, link): p = x; while( p != link[p]): p = link[p]; while( x != p): nex = link[x]; link[x] = p; x = nex; return p; # the union function which makes union(x,y) # of two nodes x and y def union(x, y, link, size): x = find(x, link) y = find(y, link) if size[x] < size[y]: x,y = swap(x,y) if x != y: size[x] += size[y] link[y] = x ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(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 #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e7 + 5) def spf_sieve(): spf[1] = 1; for i in range(2, MAXN): spf[i] = i; for i in range(4, MAXN, 2): spf[i] = 2; for i in range(3, ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i*i, MAXN, i): if spf[j] == j: spf[j] = i; ## function for storing smallest prime factors (spf) in the array ################## un-comment below 2 lines when using factorization ################# # spf = [0 for i in range(MAXN)] # spf_sieve() def factoriazation(x): ret = {}; while x != 1: ret[spf[x]] = ret.get(spf[x], 0) + 1; x = x//spf[x] return ret ## this function is useful for multiple queries only, o/w use ## primefs function above. complexity O(log n) ## taking integer array input def int_array(): return list(map(int, input().strip().split())) ## taking string array input def str_array(): return input().strip().split(); #defining a couple constants MOD = int(1e9)+7; CMOD = 998244353; INF = float('inf'); NINF = -float('inf'); ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### n = int(input()); s = []; for _ in range(n): s.append(set(list(input().strip()))); link = [i for i in range(n)]; size = [1]*n; for i in range(97, 97 + 26): x = chr(i); inds = []; for i in range(n): if x in s[i]: inds.append(i); for j in range(len(inds) - 1): union(inds[j], inds[j+1], link, size); ans = set(); for i in range(n): ans.add(find(link[i], link)); print(len(ans)); ```
10,882
Provide tags and a correct Python 3 solution for this coding contest problem. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Tags: dfs and similar, dsu, graphs Correct Solution: ``` import sys input = sys.stdin.readline def union(a,b): xa=find(a) xb=find(b) if xa!=xb: if size[xa]>=size[xb]: parent[xb]=xa size[xa]+=size[xb] else: parent[xa]=xb size[xb]+=size[xa] def find(a): if parent[a]==a: return a parent[a]=find(parent[a]) return parent[a] n=int(input()) p=[] for i in range(n): p.append(set(input())) parent=[0]*(n+26) for i in range(n+26): parent[i]=i size=[1]*(n+26) for i in range(26): for j in range(n): if chr(97+i) in p[j]: union(i,j+26) ans=set() for i in range(26,n+26): x=find(i) ans.add(x) print(len(ans)) ```
10,883
Provide tags and a correct Python 3 solution for this coding contest problem. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Tags: dfs and similar, dsu, graphs Correct Solution: ``` def union(x, y): xr = find(x) yr = find(y) root[xr] = yr def find(x): while root[x] != x: x = root[x] return x import sys input = sys.stdin.readline used = set() root = dict() for _ in range(int(input())): s = input().rstrip() for j in s: if ord(j) - 97 not in root: root[ord(j) - 97] = ord(j) - 97 union(ord(s[0]) - 97, ord(j) - 97) for i in root: used.add(find(root[i])) print(len(used)) ```
10,884
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Submitted Solution: ``` def union(x, y): xr = find(x) yr = find(y) root[yr] = xr def find(x): if root[x] != x: x = find(root[x]) return x import sys input = sys.stdin.readline used = set() root = dict() for _ in range(int(input())): s = input().rstrip() orrr = ord(s[0]) - 97 if orrr not in root: root[orrr] = orrr for j in range(1, len(s)): orr = ord(s[j]) - 97 if orr not in root: root[orr] = orr union(orrr, orr) for i in root: used.add(find(root[i])) print(used.__len__()) ``` Yes
10,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Submitted Solution: ``` # https://codeforces.com/problemset/problem/1263/D from sys import stdin, exit from typing import List, Tuple class Password: string: str handle: int def __init__(self, p: str, h: int): self.string = p self.handle = h pass_list_len = int(stdin.readline().rstrip()) pass_list = [None] * pass_list_len dsu_parent = [-1] * pass_list_len dus_size = [0] * pass_list_len def make_set(v: int): dsu_parent[v] = v dus_size[v] = 1 def find_set(v: int): if dsu_parent[v] == v: return v dsu_parent[v] = find_set(dsu_parent[v]) return dsu_parent[v] def union_sets(v1: int, v2: int): v1 = find_set(v1) v2 = find_set(v2) if v1 != v2: if dus_size[v2] < dus_size[v1]: v1, v2 = v2, v1 dsu_parent[v1] = v2 dus_size[v2] += dus_size[v1] includes_char = dict() for i in range(pass_list_len): p = Password(stdin.readline().rstrip(), i) pass_list[i] = p make_set(p.handle) for c in p.string: if c not in includes_char: includes_char[c] = {p.handle} else: includes_char[c].add(p.handle) for pass_set in includes_char.values(): last_h = None for p in pass_set: if last_h is not None: union_sets(last_h, p) last_h = p for passs in pass_list: for c in passs.string: union_sets(passs.handle, next(iter(includes_char[c]))) print(len({find_set(p.handle) for p in pass_list})) ``` Yes
10,886
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Submitted Solution: ``` import sys input = sys.stdin.readline from collections import defaultdict class Unionfind: def __init__(self, n): self.par = [-1]*n self.rank = [1]*n def root(self, x): p = x while not self.par[p]<0: p = self.par[p] while x!=p: tmp = x x = self.par[x] self.par[tmp] = p return p def unite(self, x, y): rx, ry = self.root(x), self.root(y) if rx==ry: return False if self.rank[rx]<self.rank[ry]: rx, ry = ry, rx self.par[rx] += self.par[ry] self.par[ry] = rx if self.rank[rx]==self.rank[ry]: self.rank[rx] += 1 def is_same(self, x, y): return self.root(x)==self.root(y) def count(self, x): return -self.par[self.root(x)] n = int(input()) uf = Unionfind(n+26) d = defaultdict(int) c = 0 for alpha in 'abcdefghijklmnopqrstuvwxyz': d[alpha] = c c += 1 for i in range(n): s = input()[:-1] for si in s: j = d[si] uf.unite(i+26, j) rs = set(uf.root(i) for i in range(26, n+26)) print(len(rs)) ``` Yes
10,887
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Submitted Solution: ``` from collections import deque n = int(input()) dic = [[] for x in range(n+1000)] visited = [False] * (n+1000) for i in range(n): s = list(set(list(input()))) for e in s: aux = n + ord(e) dic[i].append(aux) dic[aux].append(i) """for i in range(n): visited[i] = False for j in dic[i]: visited[j] = False""" def dfs(v): visited[v] = True for e in dic[v]: if not visited[e]: dfs(e) resp = 0 for i in range(n): if not visited[i]: resp += 1 dfs(i) print(resp) ``` Yes
10,888
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Submitted Solution: ``` n = int(input()) l = [{}] s = input() for x in s: l[0][x] = 1 for i in range(n-1): s = input() flag = -1 for j in range(len(l)): for x in s: if l[j].get(x, 0): flag = j if flag != -1: for x in s: l[flag][x] = 1 else: d = {} for x in s: d[x] = 1 l.append(d) print(len(l)) ``` No
10,889
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Submitted Solution: ``` n = int(input()) a = [] for i in range(n): x = list(input()) a.append(x) a.sort() j = 1 for i in range(n-1): z = 0 for k in range(len(a[i])): if a[i][k] in a[i+1]: z = 1 break if z == 0: j += 1 j1 = 0 a.reverse() for i in range(n-1): z = 0 for k in range(len(a[i])): if a[i][k] in a[i+1]: z = 1 break if z == 0: j1 += 1 print(min(j,j1)) ``` No
10,890
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Submitted Solution: ``` # def solve(r, g, b): # sum = r + g + b # if __name__ == '__main__': # T = int(input()) # for case in range(1, T+1): # r, g, b = input().split() # r, g, b = int(r), int(g), int(b) # solve(r, g, b) def resolver(s): cuenta = 1 for x in s: s.remove(x) for y in s: if x in y or x in s or x == y: cuenta = cuenta + 1 print(cuenta+1) if __name__ == '__main__': p = int(input()) m = [input() for x in range(0, p)] resolver(m) ``` No
10,891
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters. Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows: * two passwords a and b are equivalent if there is a letter, that exists in both a and b; * two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system. For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: * admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; * admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system. Input The first line contain integer n (1 ≤ n ≤ 2 ⋅ 10^5) — number of passwords in the list. Next n lines contains passwords from the list – non-empty strings s_i, with length at most 50 letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed 10^6 letters. All of them consist only of lowercase Latin letters. Output In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system. Examples Input 4 a b ab d Output 2 Input 3 ab bc abc Output 1 Input 1 codeforces Output 1 Note In the second example hacker need to use any of the passwords to access the system. Submitted Solution: ``` n = int(input()) a = ['']*26 b = [i for i in range(26)] k=0 for i in range(n): s = input() # print (''.join(s)) ind=ord(s[0])-97 a[ind]+=s a[ind] = ''.join(set(a[ind])) for i in range(len(a)-1): for j in range(i+1, len(a)): for ch in a[j]: if ch in a[i]: a[i]+=a[j] a[j]='' cnt=0 for i in a: if i!='': cnt+=1 print (cnt) ``` No
10,892
Provide tags and a correct Python 3 solution for this coding contest problem. Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome. Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one. Input The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 50) — the number of strings and the length of each string. Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct. Output In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all. Examples Input 3 3 tab one bat Output 6 tabbat Input 4 2 oo ox xo xx Output 6 oxxxxo Input 3 5 hello codef orces Output 0 Input 9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji Output 20 ababwxyzijjizyxwbaba Note In the first example, "battab" is also a valid answer. In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are. In the third example, the empty string is the only valid palindrome string. Tags: brute force, constructive algorithms, greedy, implementation, strings Correct Solution: ``` import sys import math import heapq import collections def inputnum(): return(int(input())) def inputnums(): return(map(int,input().split())) def inputlist(): return(list(map(int,input().split()))) def inputstring(): return([x for x in input()]) def inputstringnum(): return([ord(x)-ord('a') for x in input()]) def inputmatrixchar(rows): arr2d = [[j for j in input().strip()] for i in range(rows)] return arr2d def inputmatrixint(rows): arr2d = [] for _ in range(rows): arr2d.append([int(i) for i in input().split()]) return arr2d def isPalindrome(s): return s == s[::-1] def check(s1, s2): return s1 == s2[::-1] n, m = inputnums() a = [] for i in range(n): s = input() a.append(s) front = "" back = "" for i in range(len(a)): for j in range(i+1, len(a)): if check(a[i], a[j]): front = a[i]+front back = back+a[j] a[i] = ".," a[j] = ".," break mid = "" for i in range(len(a)): if isPalindrome(a[i]): mid = a[i] break rtn = front+mid+back print(len(rtn)) print(rtn) ```
10,893
Provide tags and a correct Python 3 solution for this coding contest problem. Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome. Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one. Input The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 50) — the number of strings and the length of each string. Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct. Output In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all. Examples Input 3 3 tab one bat Output 6 tabbat Input 4 2 oo ox xo xx Output 6 oxxxxo Input 3 5 hello codef orces Output 0 Input 9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji Output 20 ababwxyzijjizyxwbaba Note In the first example, "battab" is also a valid answer. In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are. In the third example, the empty string is the only valid palindrome string. Tags: brute force, constructive algorithms, greedy, implementation, strings Correct Solution: ``` n, m = map(int, input().split()) a = [] for _ in range(n): s = input() a.append(s) def is_palindrome(s1, s2): eh = True for i in range(len(s1)): if s1[i] != s2[m-i-1]: eh = False break return eh def is_palindrome_alone(s1): eh = True for i in range(len(s1)): if s1[i] != s1[m-i-1]: eh = False break return eh together = [] for i in range(len(a)): for j in range(i+1, len(a)): if a[i] != -1 and a[j] != -1 and is_palindrome(a[i], a[j]): together.append([a[i], a[j]]) a[i] = -1 a[j] = -1 alone = [] for i, s in enumerate(a): if s != -1 and is_palindrome_alone(s): alone.append(s) a[i] = -1 break stack = [] ans = [] for i in together: ans.append(i[0]) stack.append(i[1]) for i in alone: ans.append(i) while len(stack): ans.append(stack.pop()) ans = "".join(ans) print(len(ans)) print(ans) ```
10,894
Provide tags and a correct Python 3 solution for this coding contest problem. Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome. Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one. Input The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 50) — the number of strings and the length of each string. Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct. Output In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all. Examples Input 3 3 tab one bat Output 6 tabbat Input 4 2 oo ox xo xx Output 6 oxxxxo Input 3 5 hello codef orces Output 0 Input 9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji Output 20 ababwxyzijjizyxwbaba Note In the first example, "battab" is also a valid answer. In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are. In the third example, the empty string is the only valid palindrome string. Tags: brute force, constructive algorithms, greedy, implementation, strings Correct Solution: ``` n,m=map(int,input().split()) s=[""]*n kouho=[] result_mid="" result_left="" result_right="" for i in range(n): s[i]=input() for i in range(n): s_i_rev=s[i][::-1] if s[i] not in kouho: kouho.append(s_i_rev) else: result_left=s[i]+result_left result_right=result_right+s_i_rev kouho.remove(s[i]) for j in range(len(kouho)): if kouho[j]==kouho[j][::-1]: if len(result_mid)<len(kouho[j]): result_mid=kouho[j] result=result_left+result_mid+result_right print(len(result)) print(result) ```
10,895
Provide tags and a correct Python 3 solution for this coding contest problem. Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome. Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one. Input The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 50) — the number of strings and the length of each string. Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct. Output In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all. Examples Input 3 3 tab one bat Output 6 tabbat Input 4 2 oo ox xo xx Output 6 oxxxxo Input 3 5 hello codef orces Output 0 Input 9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji Output 20 ababwxyzijjizyxwbaba Note In the first example, "battab" is also a valid answer. In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are. In the third example, the empty string is the only valid palindrome string. Tags: brute force, constructive algorithms, greedy, implementation, strings Correct Solution: ``` n,m=map(int,input().split()) s=[] z="" for i in range(n): s.append(input()) count=0 x="" for i in range(int(n)): j=i+1 if(s[i]==s[i][::-1]): z=s[i] continue while(j<n): if(s[i]==s[j][::-1]): count+=1 x=s[i]+x+s[j] break j+=1 x=x[:int(len(x)/2)]+z+x[int(len(x)/2):] print(len(x)) print(x) ```
10,896
Provide tags and a correct Python 3 solution for this coding contest problem. Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome. Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one. Input The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 50) — the number of strings and the length of each string. Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct. Output In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all. Examples Input 3 3 tab one bat Output 6 tabbat Input 4 2 oo ox xo xx Output 6 oxxxxo Input 3 5 hello codef orces Output 0 Input 9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji Output 20 ababwxyzijjizyxwbaba Note In the first example, "battab" is also a valid answer. In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are. In the third example, the empty string is the only valid palindrome string. Tags: brute force, constructive algorithms, greedy, implementation, strings Correct Solution: ``` from sys import stdin, stdout from math import * from heapq import * from collections import * def is_palind(s): ln=len(s) for i in range(ln): if (s[i] != s[ln-1-i]): return False return True def main(): n,m=[int(x)for x in stdin.readline().split()] npalinds=[] palinds=[] alls=[] for i in range(n): s=stdin.readline().strip() if (is_palind(s)==True): palinds.append(s) else: npalinds.append(s) alls.append(s) res='' used=[False]*(n+1) for ind,s in enumerate(palinds): if (palinds.count(s)%2==1): if (len(s)>len(res)): res=s if (res in palinds): used[alls.index(res)]=True reslist=deque() reslist.append(res) for i in range(len(alls)): if (used[i]==False): p=alls[i] for j in range(len(alls)): if (used[j]==False) and (i!=j): q=alls[j] if is_palind(p+q): reslist.appendleft(p) reslist.append(q) used[i]=True used[j]=True res="".join(reslist) stdout.write("%d\n%s"%(len(res),res)) return 0 if __name__ == "__main__": main() ```
10,897
Provide tags and a correct Python 3 solution for this coding contest problem. Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome. Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one. Input The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 50) — the number of strings and the length of each string. Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct. Output In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all. Examples Input 3 3 tab one bat Output 6 tabbat Input 4 2 oo ox xo xx Output 6 oxxxxo Input 3 5 hello codef orces Output 0 Input 9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji Output 20 ababwxyzijjizyxwbaba Note In the first example, "battab" is also a valid answer. In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are. In the third example, the empty string is the only valid palindrome string. Tags: brute force, constructive algorithms, greedy, implementation, strings Correct Solution: ``` n, m = map(int, input().split()) s1 = "" s2 = "" sc = "" dat = [] for _ in range(n): dat.append(input()) while 0 < len(dat): s = dat[0] del dat[0] if sc == "": if s == "".join(reversed(s)): sc = s continue for j in range(0, len(dat)): ss = "".join(reversed(dat[j])) if s == ss: s1 = s1 + s s2 = dat[j] + s2 del dat[j] break res = s1 + sc + s2 #print("---") #print(s1) #print(sc) #print(s2) #print("---") print(len(res)) print(res) ```
10,898
Provide tags and a correct Python 3 solution for this coding contest problem. Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome. Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one. Input The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 50) — the number of strings and the length of each string. Next n lines contain a string of length m each, consisting of lowercase Latin letters only. All strings are distinct. Output In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all. Examples Input 3 3 tab one bat Output 6 tabbat Input 4 2 oo ox xo xx Output 6 oxxxxo Input 3 5 hello codef orces Output 0 Input 9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji Output 20 ababwxyzijjizyxwbaba Note In the first example, "battab" is also a valid answer. In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are. In the third example, the empty string is the only valid palindrome string. Tags: brute force, constructive algorithms, greedy, implementation, strings Correct Solution: ``` n, m = map(int, input().split()) d = {} f = [] a = [] used = [False] * n for i in range(n): s = input() if s[::-1] in d: used[i] = True used[d[s[::-1]]] = True f = [s] + f + [s[::-1]] del d[s[::-1]] else: d[s] = i a.append(s) if len(f) % 2: print(len(f) * m) print(''.join(f)) else: for i in range(n): if not used[i] and a[i] == a[i][::-1]: f = f[:len(f) // 2] + [a[i]] + f[len(f) // 2:] break print(len(f) * m) print(''.join(f)) ```
10,899