text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2) β€” the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≀ v_i, u_i ≀ n, v_i β‰  u_i) β€” the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer β€” the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from collections import defaultdict, deque, Counter, OrderedDict import threading def main(): n = int(input()) a = [0] + [*map(int, input().split())] adj = [[] for _ in range(n + 1)] for i in range(n - 1): x, y = map(int, input().split()) adj[x].append(y) adj[y].append(x) num = [[0, 0] for _ in range(n + 1)] q = deque([1]) visit = [0]*(n+1);visit[1] = 1 for i in range(n-1): x = q[i] for nx in adj[x]: if visit[nx]: continue q.append(nx) visit[nx] = 1 while q: x = q.pop() if a[x] == 1: num[x][0] += 1 if a[x] == 2: num[x][1] += 1 for nx in adj[x]: num[x][0] += num[nx][0] num[x][1] += num[nx][1] ans = 0 for i in range(2, n + 1): if num[i][0] == num[1][0] and num[i][1] == 0: ans += 1 if num[i][0] == 0 and num[i][1] == num[1][1]: ans += 1 print(ans) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": """threading.stack_size(40960000) thread = threading.Thread(target=main) thread.start()""" main() ``` Yes
4,200
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2) β€” the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≀ v_i, u_i ≀ n, v_i β‰  u_i) β€” the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer β€” the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` 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") ####################################### import sys,threading sys.setrecursionlimit(600000) threading.stack_size(10**8) def dfs(x): global v,l,l1,l2,adj,a,b,ans v[x]=1 if l[x-1]==1: l1[x]+=1 elif l[x-1]==2: l2[x]+=1 for i in adj[x]: if not v[i]: dfs(i) l1[x]+=l1[i] l2[x]+=l2[i] if l1[x]*l2[x]==0: if l1[x]: if l1[x]==a: ans+=1 elif l2[x]: if l2[x]==b: ans+=1 def main(): global v,l,l1,l2,adj,a,b,ans n=int(input()) l=list(map(int,input().split())) v=[0]*(n+1) l1=[0]*(n+1) l2=[0]*(n+1) ans,a,b=0,l.count(1),l.count(2) adj=[[] for i in range(n+1)] for i in range(n-1): x,y=map(int,input().split()) adj[x].append(y) adj[y].append(x) dfs(1) print(ans) t=threading.Thread(target=main) t.start() t.join() ``` Yes
4,201
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2) β€” the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≀ v_i, u_i ≀ n, v_i β‰  u_i) β€” the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer β€” the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` import sys red = 0 blue = 0 N = int(sys.stdin.readline().split()[0]) line = sys.stdin.readline().split() colored = [] tree = [] for i in range(N): item = int(line[i]) if item == 1: red += 1 elif item == 2: blue += 1 colored.append(item) tree.append([]) for _ in range(N - 1): line = sys.stdin.readline().split() u, v = int(line[0]) - 1, int(line[1]) - 1 tree[u].append(v) tree[v].append(u) answer = 0 def dfs(v: int , pi_v : int): global answer r = colored[v] == 1 if 1 else 0 b = colored[v] == 2 if 1 else 0 for u in tree[v]: if not u == pi_v: dfs_rec = dfs(u, v) answer += dfs_rec[0] == red and dfs_rec[1] == 0 if 1 else 0 answer += dfs_rec[1] == blue and dfs_rec[0] == 1 if 1 else 0 r += dfs_rec[0] b += dfs_rec[1] return [r, b] dfs(0, -1) sys.stdout.write(str(answer) + "\n") ``` No
4,202
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2) β€” the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≀ v_i, u_i ≀ n, v_i β‰  u_i) β€” the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer β€” the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` n = int(input()) nc = list(map(int,input().split())) edges = [list(map(int,input().split())) for x in range(n-1)] a = 0 for x in range(len(edges)): c1 =[edges[x][0]] c2 = [edges[x][1]] rg = True for y in range(len(edges)): if y == x: continue e = edges[y] if e[0] in c1: c1.append(e[1]) continue if e[1] in c1: c1.append(e[0]) continue if e[1] in c2: c2.append(e[0]) continue if e[0] in c2: c2.append(e[1]) continue pcol = 0 rg1 = True for x in c1: if pcol == 0: if nc[x-1] != 0: pcol = nc[x-1] elif nc[x-1] != 0: if pcol != nc[x-1]: rg1=False pcol = 0 for x in c2: if pcol == 0: if nc[x-1] != 0: pcol = nc[x-1] elif nc[x-1] != 0: if pcol != nc[x-1]: rg=False if rg and rg1: a += 1 print(a) ``` No
4,203
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2) β€” the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≀ v_i, u_i ≀ n, v_i β‰  u_i) β€” the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer β€” the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` n = int(input()) lst = list(map(int, input().split())) lst2 = [] for i in range(n-1): tupl = tuple(map(int, input().split())) lst2.append(tupl) def cut_tree(n, lst, lst2): my_dict = dict() for i in range(len(lst)): my_dict[i+1] = lst[i] output = len(lst2) for i in range(len(lst2)): a = lst2[i][0] b = lst2[i][1] red_a = 0 blue_a = 0 red_b = 0 blue_b = 0 if my_dict[a] == 1: red_a += 1 elif my_dict[a] == 2: blue_a += 1 if my_dict[b] == 1: red_b += 1 elif my_dict[b] == 2: blue_b += 1 #from the beginning to the point; left for k in range(0, i): if a in lst2[k]: if (lst2[k][0] != a and my_dict[lst2[k][0]] == 1) or (lst2[k][1] != a and my_dict[lst2[k][1]] == 1): red_a += 1 elif (lst2[k][0] != a and my_dict[lst2[k][0]] == 2) or (lst2[k][1] != a and my_dict[lst2[k][1]] == 2): blue_a += 1 elif b in lst2[k]: if (lst2[k][0] != b and my_dict[lst2[k][0]] == 1) or (lst2[k][1] != b and my_dict[lst2[k][1]] == 1): red_b += 1 elif (lst2[k][0] != b and my_dict[lst2[k][0]] == 2) or (lst2[k][1] != b and my_dict[lst2[k][1]] == 2): red_b += 1 if red_a > 0 and blue_a > 0: output -= 1 break elif red_b > 0 and blue_b > 0: output -= 1 break #from the point to the end; right for j in range(i+1, len(lst2)): if a in lst2[j]: if (lst2[j][0] != a and my_dict[lst2[j][0]] == 1) or (lst2[j][1] != a and my_dict[lst2[j][1]] == 1): red_a += 1 elif (lst2[j][0] != a and my_dict[lst2[j][0]] == 2) or (lst2[j][1] != a and my_dict[lst2[j][1]] == 2): blue_a += 1 elif b in lst2[j]: if (lst2[j][0] != b and my_dict[lst2[j][0]] == 1) or (lst2[j][1] != b and my_dict[lst2[j][1]] == 1): red_b += 1 elif (lst2[j][0] != b and my_dict[lst2[j][0]] == 2) or (lst2[j][1] != b and my_dict[lst2[j][1]] == 2): red_b += 1 if red_a > 0 and blue_a > 0: output -= 1 break elif red_b > 0 and blue_b > 0: output -= 1 break return output print(cut_tree(n, lst, lst2)) ``` No
4,204
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2) β€” the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≀ v_i, u_i ≀ n, v_i β‰  u_i) β€” the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer β€” the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` def dfs(graph, visited, vertexes_colors, vertex, common_red, common_blue): visited[vertex] = True good_edges_count = 0 red = 0 blue = 0 if vertexes_colors[vertex] == 1: red += 1 elif vertexes_colors[vertex] == 2: blue += 1 for new_vertex in graph[vertex]: if visited[new_vertex]: continue new_red, new_blue, new_good_edges_count = dfs(graph, visited, vertexes_colors, new_vertex, common_red, common_blue) red += new_red blue += new_blue good_edges_count += new_good_edges_count if (not new_red and new_blue == common_blue) or (not new_blue and new_red == common_red): good_edges_count += 1 return red, blue, good_edges_count def main(): n = int(input()) vertexes_colors = list(map(int, input().split())) edges = [list(map(lambda v_: int(v_) - 1, input().split())) for _ in range(n - 1)] common_color_count = [0, 0, 0] _, common_red, common_blue = common_color_count for color in vertexes_colors: common_color_count[color] += 1 graph = [[] for _ in range(n)] for edge in edges: v, u = edge graph[v].append(u) graph[u].append(v) visited = [False] * n _, _, good_edges_count = dfs(graph, visited, vertexes_colors, 0, common_red, common_blue) print(good_edges_count) main() ``` No
4,205
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected tree of n vertices. Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors. How many nice edges are there in the given tree? Input The first line contains a single integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2) β€” the colors of the vertices. a_i = 1 means that vertex i is colored red, a_i = 2 means that vertex i is colored blue and a_i = 0 means that vertex i is uncolored. The i-th of the next n - 1 lines contains two integers v_i and u_i (1 ≀ v_i, u_i ≀ n, v_i β‰  u_i) β€” the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex. Output Print a single integer β€” the number of nice edges in the given tree. Examples Input 5 2 0 0 1 2 1 2 2 3 2 4 2 5 Output 1 Input 5 1 0 0 0 2 1 2 2 3 3 4 4 5 Output 4 Input 3 1 1 2 2 3 1 3 Output 0 Note Here is the tree from the first example: <image> The only nice edge is edge (2, 4). Removing it makes the tree fall apart into components \{4\} and \{1, 2, 3, 5\}. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices. Here is the tree from the second example: <image> Every edge is nice in it. Here is the tree from the third example: <image> Edge (1, 3) splits the into components \{1\} and \{3, 2\}, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge (2, 3) splits the into components \{1, 3\} and \{2\}, the former one includes both red and blue vertex, thus the edge also isn't nice. So the answer is 0. Submitted Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict from itertools import permutations, combinations raw_input = stdin.readline pr = stdout.write def in_arr(): return map(int,raw_input().split()) def pr_num(n): stdout.write(str(n)+'\n') def pr_arr(arr): for i in arr: stdout.write(str(i)+' ') stdout.write('\n') range = xrange # not for python 3.0+ n=input() l=in_arr() d=defaultdict(list) b=l.count(2) r=l.count(1) for i in range(n-1): u,v=in_arr() d[u].append(v) d[v].append(u) q=[1] vis=[0]*(n+1) pos=0 vis[1]=1 while pos<n: x=q[pos] pos+=1 for i in d[x]: if not vis[i]: vis[i]=1 q.append(i) dp=[[0,0] for i in range(n+1)] while q: x=q.pop() vis[x]=0 if l[x-1]==1: dp[x][0]=1 elif l[x-1]==2: dp[x][1]=1 for i in d[x]: if not vis[i]: dp[x][0]+=dp[i][0] dp[x][1]+=dp[i][1] q=[1] vis[1]=1 ans=0 while q: x=q.pop(0) for i in d[x]: if not vis[i]: vis[i]=1 q.append(i) if ((dp[i][1]==b) and (dp[i][0]==0)) or (dp[i][1]==0 and r-dp[i][0]==r): #print x,i,b-dp[i][1],r-dp[i][0] ans+=1 pr_num(ans) ``` No
4,206
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Tags: bitmasks, brute force Correct Solution: ``` n = int(input()) a = n & 1 b = n >> 1 & 1 c = n >> 2 & 1 d = n >> 3 & 1 d = 1 - d if d: c = 1 - c if c and d: b = 1 - b if b and c and d: a = 1 - a ans = d << 3 | c << 2 | b << 1 | a print(ans) ```
4,207
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Tags: bitmasks, brute force Correct Solution: ``` Ans=[15,14,12,13,8,9,10,11,0,1,2,3,4,5,6,7] n=int(input()) print(Ans[n]) ```
4,208
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Tags: bitmasks, brute force Correct Solution: ``` print([15, 14, 12, 13, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7][int(input())]) ```
4,209
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Tags: bitmasks, brute force Correct Solution: ``` n = int(input()) d = [] for i in range(4): d.append(n % 2) n //= 2 x = 1 for i in range(3,-1,-1): d[i] ^= x x &= d[i] r = 0 for v in d[::-1]: r = 2*r + v print(r) ```
4,210
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Tags: bitmasks, brute force Correct Solution: ``` a = int(input()) if a == 3: print(13) elif a == 0: print(15) elif a == 1: print(14) elif a == 2: print(12) elif a == 4: print(8) elif a == 5: print(9) elif a == 6: print(10) elif a == 7: print(11) elif a == 8: print(0) elif a == 9: print(1) elif a == 10: print(2) elif a == 11: print(3) elif a == 12: print(4) elif a == 13: print(5) elif a == 14: print(6) elif a == 15: print(7) ```
4,211
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Tags: bitmasks, brute force Correct Solution: ``` a=int(input()) if a==0 or a==6 or a==9 or a==15: c=a if a==2 or a==5 or a==7: c=a*2 if a==4 or a==10 or a==14: c=a//2 if a==1: c=8 if a==8: c=1 if a==3: c=12 if a==12: c=3 if a==11: c=13 if a==13: c=11 if a!=0: e=c-1 else: e=15 if e==0 or e==6 or e==9 or e==15: f=e if e==2 or e==5 or e==7: f=e*2 if e==4 or e==10 or e==14: f=e//2 if e==1: f=8 if e==8: f=1 if e==3: f=12 if e==12: f=3 if e==11: f=13 if e==13: f=11 #reverse print(f) ```
4,212
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Tags: bitmasks, brute force Correct Solution: ``` n = int(input()) a, b, c, d = n%2, n//2%2, n//4%2, n//8 d ^= 1 if d == 1: c ^= 1 if d == 1 and c == 1: b ^= 1 if d == 1 and c == 1 and b == 1: a ^= 1 print(a+b*2+c*4+d*8) ```
4,213
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Tags: bitmasks, brute force Correct Solution: ``` n=int(input("")) a=[0,0,0,0] a[0]=n%2 n=n//2 a[1]=n%2 n=n//2 a[2]=n%2 n=n//2 a[3]=n%2 def intnot(x): return 0 if x==1 else 1 a[3]=intnot(a[3]) if(a[3]==1): a[2]=intnot(a[2]) if(a[3]+a[2]==2): a[1]=intnot(a[1]) if(a[3]+a[2]+a[1]==3): a[0]=intnot(a[0]) n=8*a[3]+4*a[2]+2*a[1]+a[0] print(n) ```
4,214
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Submitted Solution: ``` n = int(input()) b = list(bin(n).split('b')[1]) l1 = list(['0']*(4-len(b))+b) x = int(''.join(reversed(l1)),2)-1 if x < 0: x = 15 y = list(bin(x).split('b')[1]) l2 = list(['0']*(4-len(y))+y) print(int(''.join(reversed(l2)), 2)) ``` Yes
4,215
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Submitted Solution: ``` import io, sys, atexit, os import math as ma from sys import exit from decimal import Decimal as dec from itertools import permutations from itertools import combinations def li (): return list (map (int, input ().split ())) def num (): return map (int, input ().split ()) def nu (): return int (input ()) def find_gcd ( x, y ): while (y): x, y = y, x % y return x def prod(n): s=1 while(n!=0): s=s*(n%10) n=n//10 return s def check(xp): op=sorted(xp) if(op==xp): return True mm = 1000000007 def solve (): t = 1 for it in range (t): n=nu() xp=[ 15, 14, 12, 13, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 16, 17] print (xp [ n ]) continue if(n<=7): print(xp[n]) else: if(n==8): print(30) if __name__ == "__main__": solve () ``` Yes
4,216
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Submitted Solution: ``` a=int(input()); if (a==0): print(15) elif (a==1):print(14) elif (a==4): print(8) elif (a==5): print(9) elif (a==7): print(11) elif (a==6): print(10) elif (a==8):print(0) elif (a==9):print(1) elif (a==10):print(2) elif (a==11):print(3) elif (a==12): print(4) elif (a==13): print(5) elif (a==14): print(6) elif (a==15): print(7) else: print('1'+str(a)) ``` Yes
4,217
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Submitted Solution: ``` N = int(input()) if N: S = bin(N)[2:] S = '0' * (4-len(S)) + S Z = 0 for I in range(4): if S[I] == '1': Z += 2**I S = bin(Z-1)[2:] S = '0' * (4 - len(S)) + S Z = 0 for I in range(4): if S[I] == '1': Z += 2**I print(Z) else: print(15) ``` Yes
4,218
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Submitted Solution: ``` k=int(input()) y=0 for i in range(k): y+=k print(y+k+1) ``` No
4,219
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Submitted Solution: ``` N = int(input()) if N == 3: print(13) elif N == 0: print(15) elif N == 1: print(14) elif N == 2: print(12) elif N == 4: print(9) ``` No
4,220
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Submitted Solution: ``` N = int(input()) def calc(n): if n == 3: return 13 if n == 0: return 15 if n == 1: return 14 if n == 2: return 12 if n == 4: return 8 if n == 5: return 7 return 1/0 print(calc(N)) ``` No
4,221
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Input The input contains a single integer a (0 ≀ a ≀ 15). Output Output a single integer. Example Input 3 Output 13 Submitted Solution: ``` mas = [2] * 16 mas[4] = 8 mas[2] = 12 mas[3] = 13 mas[1] = 14 mas[0] = 15 print(mas[int(input())]) ``` No
4,222
Provide tags and a correct Python 3 solution for this coding contest problem. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Tags: constructive algorithms, math, number theory Correct Solution: ``` import math import sys k=int(input()) t=int(math.sqrt(k)) n=m=0 s="" vow="aeiou" for i in range(5,t+1): if k%i==0: n=i m=k//i if n==0: print(-1) sys.exit(0) for i in range(n): for j in range(m): s+=vow[(i+j)%5] print(s) ```
4,223
Provide tags and a correct Python 3 solution for this coding contest problem. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Tags: constructive algorithms, math, number theory Correct Solution: ``` # import random def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: # print (" ",f) if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True def main(): # *****************Input******************** n=int(input()) # *****************Algo********************* # Check whether n is greater that >25 if is_prime(n): print(-1) return if n>=25: # Algo !! # Find j such that i>5 j=-1 for i in range(5,n): if n%i==0 and n//i >= 5: j=n//i break # Construct the word now # print(i,j) if j==-1: print(-1) return # word='' # vow="aeiou".split() r=i c=j vowels=['a','e','i','o','u'] # print(vowels) word='' k=0 for i in range(r): t=k for j in range(c): word+=vowels[(j+t)%5] # print(word) # if j==4: # t+=1 k+=1 else: print(-1) return # *****************Output******************* # print(is_prime(n)) print(word) main() ```
4,224
Provide tags and a correct Python 3 solution for this coding contest problem. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Tags: constructive algorithms, math, number theory Correct Solution: ``` k = int(input()) if k < 25: print(-1) else: a = 'aeiou' max1 = min1 = 0 for q in range(round(k**(1/2))+1, 0, -1): if k % q == 0: max1, min1 = k//q, q break if min1 < 5: print(-1) else: ans = [a[q:]+a[:q] for q in range(min1)] for q in range(min1): ans[q] += (a[q % 5]*(max1-5)) print(''.join(ans)) ```
4,225
Provide tags and a correct Python 3 solution for this coding contest problem. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Tags: constructive algorithms, math, number theory Correct Solution: ``` k=int(input()) v='aeiou'*k n=5 while n*n<k and k%n:n+=1 print(((''.join(v[i:i+n]for i in range(n))*k)[:k],-1)[n*n>k]) ```
4,226
Provide tags and a correct Python 3 solution for this coding contest problem. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Tags: constructive algorithms, math, number theory Correct Solution: ``` num = int(input()) ans = "-1" v = "aeiou" for i in range(5, int(num**0.5)+1): if num % i == 0: ans = "" for j in range(num//i): ind = j % 5 for k in range(i): ans += v[ind] ind = (ind + 1)%5 break print(ans) ```
4,227
Provide tags and a correct Python 3 solution for this coding contest problem. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Tags: constructive algorithms, math, number theory Correct Solution: ``` string = [ "aeiou", "eioua", "iouae", "ouaei", "uaeio" ] def find_n(fact, MAX): n = MAX size = len(fact) break_now = False for i in range(0, size): if fact[i]>=5: break_now, n = True, fact[i] for j in range(i+1, size): val = fact[i]*fact[j] if val >= 5: break_now, n = True, min(n, val) for k in range(j+1, size): break_now, val = True, fact[i]*fact[j]*fact[k] if val >= 5: n = min(n, val) return n def find_n_m(num): copy_num = num fact = [] while num > 1 and num % 2 == 0: num //= 2 fact.append(2) for i in range(3, num, 2): if i*i > num: break while num % i == 0: num //= i fact.append(i) if num > 1: fact.append(num) n = find_n(fact, 100000) # print(n, end=", ") fact.reverse() n = min(find_n(fact, n), n) # print(n, end=", ") return n, copy_num//n def solve(k): n, m = find_n_m(k) if n<5 or m<5: return -1 ans = list(string) m-=5 n-=5 while m>=5: for i in range(5): ans[i]+=string[i] m-=5 while m>0: for i in range(5): ans[i]+=string[i][0] m-=1 demo = ans[0] for _ in range(n): ans.append(demo) final_ans = "" for value in ans: final_ans += value return final_ans k = int(input()) print(solve(k)) ```
4,228
Provide tags and a correct Python 3 solution for this coding contest problem. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Tags: constructive algorithms, math, number theory Correct Solution: ``` n = int(input()) i = 5 if n < 25: print(-1) exit() while n % i != 0: i += 1 if i == n or n//i < 5: print(-1) exit() vowel = 'aeiou' final = '' for j in range(n//i): temp = vowel*(i//5) + vowel[:i%5] vowel = vowel[1:] + vowel[0] final += temp print(final) ```
4,229
Provide tags and a correct Python 3 solution for this coding contest problem. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Tags: constructive algorithms, math, number theory Correct Solution: ``` k=int(input()) for i in range(5,k): if k%i==0 and k//i>=5: tot='' pre='a' for lit in range(k//i): if pre=='a': prev='e' elif pre=='e': prev='i' elif pre=='i': prev='o' elif pre=='o': prev='u' else: prev='a' pre=prev for j in range(i): if prev=='a': tot+='e' elif prev=='e': tot+='i' elif prev=='i': tot+='o' elif prev=='o': tot+='u' else: tot+='a' prev=tot[-1] print(tot) break else: print(-1) ```
4,230
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Submitted Solution: ``` v='aeiou' a=[v[i:]+v[:i]for i in range(5)] k=int(input()) n=5 while n*n<k and k%n:n+=1 print(((''.join((x*n)[:n]for x in a)*k)[:k],-1)[n*n>k]) ``` Yes
4,231
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Submitted Solution: ``` voyels = 'aeiou' m, n = -1, -1 def next_permutation(i=1): global voyels if i: voyels = voyels[-1] + voyels[:-1] return voyels def solve(k): if k < 25: return -1 divisors = sorted(list({(x, k//x) for x in range(1, (k + 1) // 2 + 1) if k % x == 0}), key=lambda a: (a[0]+a[1], a[0])) global voyels global m,n for divs in divisors: if divs[0] >= 5 and divs[1] >= 5: m, n = divs break else: return -1 voyels = (m//5)*voyels + voyels[:m%5] return ''.join([next_permutation(i) for i in range(n)]) if __name__ == '__main__': print(solve(int(input()))) ``` Yes
4,232
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Submitted Solution: ``` # from sys import stdin ii = lambda: int(input()) mi = lambda: map(int, input().split()) li = lambda: list(mi()) si = lambda: input() msi = lambda: map(int, stdin.readline().split()) lsi = lambda: list(msi()) n=ii() if n<25: print(-1) exit(0) else: for i in range(5,n//2+1): if n%i==0: n1=n/i n2=i break; else: print(-1) exit(0) if n%25==0: s = "aeioueiouaiouaeouaeiuaeio"*(n//25) print(s) exit(0) if n1<5: print(-1) exit(0) else: s="aeiou"*(n//5) i = n-len(s) if i==1: s+="a" elif i==2: s+="ae" elif i==3: s+="aei" elif i==4: s+="aeio" print(s) ``` Yes
4,233
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Submitted Solution: ``` n = int(input()) k = 5 while k * k <= n and n % k != 0: k += 1 s = 'aeiou' if k * k <= n and n % k == 0: for i in range(n//k): for j in range(k): print(s[(i+j)%5], end='') else: print("-1") ``` Yes
4,234
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Submitted Solution: ``` def Fact(n): for i in range(5, n//2 + 1): if n%i == 0 and n//i > 5: return (i, n//i) return (1, 1) p = int(input()) l = 'aeiou' if p == 1: print(-1) else: n, m = Fact(p) if n==1: print(-1) else: for i in range(n): for j in range(m): print(l[(j+i)%5], end="") ``` No
4,235
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Submitted Solution: ``` '''n=int(input()) l=[] S=0; for i in range(0,n): s=input().rstrip() x=list(s) l.append(x[0]) t=list(set(l)) for i in range(0,len(t)): g=t[i] if l.count(g)==0: continue; elif g in l and l.count(g)%2==0: if l.count(g)==2: continue; elif l.count(g)==4: S+=2; else: S=S+(l.count(g)-1) elif g in l and l.count(g)%2!=0: if l.count(g)==3: S=S+1; else: S=S+(l.count(g)-1) print(S)''' n=int(input()) import math if n==1 or n==0: print(-1) else: U=0; for i in range(2,math.floor(math.sqrt(n))+1): if n%i==0: U=1; break; if U==1: l=['a','e','i','o','u'] for i in range(5,1000000): if n%i==0: a=i; b=n//i; if b>=5: break for i in range(0,a): D=0+i; for j in range(0,b): if D<len(l): print(l[D],end='') D+=1; else: print(l[0],end='') D=1; else: print(-1) ``` No
4,236
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Submitted Solution: ``` import math n = int(input()) f = 1 for i in range(2, math.ceil(n**(1/2))+1): if n%i == 0 and i>=5 and n//i >= 5: f = 0 k, m = i, n//i break if f: print(-1) else: s = '' t = 'aeiou'*100 for i in range(k): s += t[i:m]+t[:i] print(s) ``` No
4,237
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that nβ‹… m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column. You are given an integer k and you must either print a vowelly word of length k or print -1 if no such word exists. In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'. Input Input consists of a single line containing the integer k (1≀ k ≀ 10^4) β€” the required length. Output The output must consist of a single line, consisting of a vowelly word of length k consisting of lowercase English letters if it exists or -1 if it does not. If there are multiple possible words, you may output any of them. Examples Input 7 Output -1 Input 36 Output agoeuioaeiruuimaeoieauoweouoiaouimae Note In the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following 6 Γ— 6 grid: <image> It is easy to verify that every row and every column contain all the vowels. Submitted Solution: ``` k = int(input()) rs = [ 'aeiou', 'eioua', 'iouae', 'ouaei', 'uaeio', ] if k < 25: print(-1) else: for r in range(5, k + 1): if k % r == 0: c = k // r if c < 5: continue a = c - 5 for i in range(r): print((rs[i % 5] * ((c + 4) // 5))[:c]) break else: print(-1) ``` No
4,238
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Tags: binary search, greedy, implementation, two pointers Correct Solution: ``` from sys import stdin from sys import setrecursionlimit as SRL; SRL(10**7) rd = stdin.readline rrd = lambda: map(int, rd().strip().split()) s = str(rd().strip()) t = str(rd().strip()) s = '0' + s canl = [0] * (len(s) + 10) canr = [0] * (len(s) + 10) j = 0 for i,v in enumerate(s): if j<len(t) and v == t[j]: j += 1 canl[i] = j j = len(t) - 1 for i in range(len(s)-1,-1,-1): if j>=0 and s[i] == t[j]: j -= 1 canr[i] = len(t)-j-1 def check(x): if x > len(s): return False for i in range(1,len(s) - x+1): l = i - 1 r = i + x if canl[l] + canr[r] >= len(t): return True return False l = 0 r = len(s) while l<r: mid = (l+r)//2 if check(mid): l = mid + 1 else: r = mid print(r-1) ```
4,239
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Tags: binary search, greedy, implementation, two pointers Correct Solution: ``` s = input() t = input() n = len(s) m = len(t) dp1 = [0] * (n + 1) for i in range(n): dp1[i + 1] = dp1[i] if (dp1[i] < m and s[i] == t[dp1[i]]): dp1[i + 1] += 1 dp2 = [0] * (n + 1) for i in range(n - 1, -1, -1): dp2[i] = dp2[i + 1] if (dp2[i + 1] < m and s[i] == t[-1 - dp2[i + 1]]): dp2[i] += 1 def check(ln): for i in range(n - ln + 1): if ((dp1[i] + dp2[i + ln]) >= m): return True return False l, r = 0, n while (r - l > 1): mid = (l + r) // 2 if (check(mid)): l = mid else: r = mid print(l) ```
4,240
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Tags: binary search, greedy, implementation, two pointers Correct Solution: ``` def naiveSolve(n): return def main(): # s --> t s = '$' + input() + '$' t = '$' + input() + '$' n = len(t) left = [-1] * n right = [-1] * n m = len(s) j = 0 for i in range(m): if s[i] == t[j]: left[j] = i j += 1 if j == n: break j = n - 1 for i in range(m-1, -1, -1): if s[i] == t[j]: right[j] = i j -= 1 if j == -1: break ans = 0 for i in range(n - 1): ans = max(ans, right[i+1] - left[i] - 1) print(ans) return import sys # input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(l,r): print('? {} {}'.format(l,r)) sys.stdout.flush() return int(input()) def answerInteractive(x): print('! {}'.format(x)) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil for _abc in range(1): main() ```
4,241
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Tags: binary search, greedy, implementation, two pointers Correct Solution: ``` s = input() t = input() pos = [[-1, -1] for i in range(len(t))] ptr = 0 for i,c in enumerate(t): while s[ptr] != c: ptr += 1 pos[i][0] = ptr ptr += 1 ptr = len(s) - 1 for i in range(len(t)-1, -1, -1): c = t[i] while s[ptr] != c: ptr -= 1 pos[i][1] = ptr ptr -= 1 best = max(pos[0][1], len(s)-pos[-1][0]-1) for i in range(1, len(pos)): best = max(best, pos[i][1] - pos[i-1][0] - 1) print(best) ```
4,242
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Tags: binary search, greedy, implementation, two pointers Correct Solution: ``` def f(n): for i in range(-1,lt): if right[i+1]-left[i]>n: return True return False s=input() t=input() ls=len(s) lt=len(t) right=dict() left=dict() i=0 j=0 ls=len(s) left[-1]=-1 while i<lt: if s[j]==t[i]: left[i]=j i+=1 j+=1 j=ls-1 i=lt-1 right[lt]=ls while i>=0: if s[j]==t[i]: right[i]=j i-=1 j-=1 low=0 high=ls-1 #print(right,"\n",left) while low<=high: mid=(high+low)//2 # print(mid,f(mid)) if f(mid): low=mid+1 else: high=mid-1 print(high) ```
4,243
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Tags: binary search, greedy, implementation, two pointers Correct Solution: ``` s=input() t=input() s_pos=[len(s) for i in range(len(t))] i,j=len(s)-1,len(t)-1 while i>-1 and j>-1: if s[i]==t[j]: s_pos[j]=i j-=1 i-=1 p,q=0,0 ans=0 while p<len(s): if q==len(t): ans=max(ans,len(s)-p) break remove=s_pos[q]-p ans=max(ans,remove) if s[p]==t[q]: q+=1 p+=1 print(ans) ```
4,244
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Tags: binary search, greedy, implementation, two pointers Correct Solution: ``` import os import sys from io import BytesIO, IOBase import heapq def main(): s = input() t = input() n, m = len(s), len(t) i, j = 0, 0 first = [] last = [] while j < m: if s[i] == t[j]: first.append(i) i += 1 j += 1 else: i += 1 i, j = n-1, m-1 while j >= 0: if s[i] == t[j]: last.append(i) j -= 1 i -= 1 last = last[::-1] ans = max(last[0], n-first[-1]-1) for i in range(m-1): ans = max(ans, last[i+1]-first[i]-1) print (ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
4,245
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Tags: binary search, greedy, implementation, two pointers Correct Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): s=list(input()) t=list(input()) n=len(s) m=len(t) pre=[] post=[] r=0 for i in range(n): if s[i]==t[r]: r+=1 pre.append(i) if r==m: break r=m-1 for i in range(n-1,-1,-1): if s[i]==t[r]: r-=1 post.append(i) if r==-1: break post.reverse() # print(pre) # print(post) ans=0 for i in range(m-1): ans=max(ans,post[i+1]-pre[i]-1) print(max(ans,n-pre[-1]-1,post[0])) #---------------------------------------------------------------------------------------- # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ```
4,246
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Submitted Solution: ``` # s = "tessts" # t = "tet" s = input() t = input() ns = len(s) nt = len(t) ans = 0 found = 0 DP_left = [0]*ns DP_left[0] = int(s[0] == t[0]) for i in range(1, ns): if DP_left[i-1] < nt: DP_left[i] = DP_left[i-1] + (s[i] == t[DP_left[i-1]]) DP_right = [0]*ns DP_right[-1] = int(s[-1] == t[-1]) for i in reversed(range(ns-1)): if 0 <= nt - DP_right[i+1] - 1 < nt : DP_right[i] = DP_right[i+1] + (s[i] == t[nt - 1 - DP_right[i+1]]) from collections import defaultdict d_r = defaultdict(int) d_l = defaultdict(int) old = 1 for index, i in enumerate(DP_left): if i == old: d_l[i] = index old += 1 for index, i in enumerate(DP_right): d_r[i] = max(d_r[i], index) for i in range(nt + 1): if i == 0: ans = max(ans, d_r[nt]) elif i == nt: ans = max(ans, ns - d_l[nt] - 1) else: ans = max(ans, d_r[nt-i] - d_l[i] - 1) print(ans) ``` Yes
4,247
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Submitted Solution: ``` '''input asdfasdf fasd ''' import sys from collections import defaultdict as dd mod=10**9+7 def ri(flag=0): if flag==0: return [int(i) for i in sys.stdin.readline().split()] else: return int(sys.stdin.readline()) st = input() pat = input() n= len(st) forward = [0 for i in range(n)] idx =0 for i in range(n): if idx < len(pat) and st[i] == pat[idx]: idx+=1 forward[i] = idx backward = [0 for x in range(n)] idx =len(pat)-1 for i in range(n-1,-1,-1): if idx>=0 and st[i] == pat[idx]: idx-=1 backward[i]= idx+2 # print(forward) # print(backward) c1 =dd(int) c2 = dd(int) for i in range(n): c1[forward[i]] = i+1 c2[backward[i]] = i+1 ans = max(c2[1]-1 , n-c1[len(pat)]) #print(c1,c2) for i in range(1,len(pat)): ans = max(ans , abs(c1[i] - c2[i+1])-1) print(ans) ``` Yes
4,248
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Submitted Solution: ``` from collections import deque def substr_idx(s, t, reverse=False): idx = deque() i = 0 rng = range(len(s)) if reverse: rng = reversed(rng) for k in rng: if i >= len(t): break if reverse and s[k] == t[-i-1]: idx.appendleft(k) i += 1 elif not reverse and s[k] == t[i]: idx.append(k) i += 1 return idx s = input() t = input() idleft = substr_idx(s, t) idright = substr_idx(s, t, reverse=True) m = max(idright[0], len(s) - idleft[-1] - 1) for i in range(1, len(idleft)): m = max(m, idright[i]-idleft[i-1]-1) print(m) ``` Yes
4,249
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Submitted Solution: ``` from collections import defaultdict as DD from bisect import bisect_left as BL from bisect import bisect_right as BR from itertools import combinations as IC from itertools import permutations as IP from random import randint as RI import sys import math MOD=pow(10,9)+7 from math import gcd def IN(f=0): if f==0: return ( [int(i) for i in sys.stdin.readline().split()] ) else: return ( int(sys.stdin.readline()) ) a=input() b=input() n=len(a) m=len(b) q=[] w=[] j=0 d1=DD(int) d2=DD(int) for i in range(len(a)): if j>=len(b): q.append(0) elif a[i]==b[j]: q.append(j+1) j+=1 else: q.append(0) j=len(b)-1 for i in range(len(a)-1,-1,-1): if j<0: w.append(0) elif a[i]==b[j]: w.append(j+1) j-=1 else: w.append(0) w.reverse() for i in range(len(a)): d1[q[i]]=i+1 for i in range(len(a)): d2[w[i]]=i+1 ans = max(d2[1]-1,len(a)-d1[len(b)]) for i in range(1,m): tr = abs(d1[i]- d2[i+1])-1 if ans<tr: ans=tr #print(tr) print(ans) ``` Yes
4,250
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Submitted Solution: ``` def process(s, t): l=[] r=[0]*len(t) j=0 for i in range(len(t)): while s[j]!=t[i]: j+=1 l.append(j) j+=1 j=len(s)-1 for i in reversed(range(len(t))): while s[j]!=t[i]: j-=1 r[i]=j j-=1 res=max(r[0], len(s)-1-l[-1]) for i in range(len(t)): res=max(res, r[i]-l[i]) return res s=input() t=input() print(process(s,t)) ``` No
4,251
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Submitted Solution: ``` z,zz=input,lambda:list(map(int,z().split())) zzz=lambda:[int(i) for i in stdin.readline().split()] szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz()) from string import * from re import * from collections import * from queue import * from sys import * from collections import * from math import * from heapq import * from itertools import * from bisect import * from collections import Counter as cc from math import factorial as f from bisect import bisect as bs from bisect import bisect_left as bsl from itertools import accumulate as ac def lcd(xnum1,xnum2):return (xnum1*xnum2//gcd(xnum1,xnum2)) def prime(x): p=ceil(x**.5)+1 for i in range(2,p): if (x%i==0 and x!=2) or x==0:return 0 return 1 def dfs(u,visit,graph): visit[u]=True for i in graph[u]: if not visit[i]: dfs(i,visit,graph) ###########################---Test-Case---################################# """ """ ###########################---START-CODING---############################## s=z() t=z() ans=0 lst=[0]*len(t) for i in range(len(t)-1,-1,-1): pos=len(s)-1 if (i+1<len(t)): pos=lst[i+1]-1 while s[pos]!=t[i]: pos-=1 lst[i]=pos ans=0 pos=0 for i in range(len(s)): rpos=len(s)-1 if pos<len(t): rpos-=1 ans=max(ans,rpos-i+1) if pos<len(t) and t[pos]==s[i]: pos+=1 print(ans) exit() for i in range(len(s)): for j in range(i,len(s)): pos=0 for p in range(len(s)): if i<=p and p<=j:continue if pos<len(t) and t[pos]==s[p]: pos+=1 if pos==len(t) : ans=max(ans,j-i+1) print(ans) ``` No
4,252
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Submitted Solution: ``` s=input() t=input() sl,tl=len(s),len(t) left=[] right=[] x=0 for i in range(sl): if x<tl and s[i]==t[x]: left.append(i) x+=1 x=tl-1 for i in range(sl-1,-1,-1): if x>=0 and s[i]==t[x]: right.append(i) x-=1 right.reverse() if(tl==1): print(max(max(left[0],sl-left[0]-1),max(right[0],sl-right[0]-1))) else: ans=max(left[-1],right[0]) for i in range(1,tl): ans=max(ans,right[i]-left[i-1]-1) print(ans) ``` No
4,253
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without changing order of remaining characters (in other words, it is guaranteed that t is a subsequence of s). For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test". You want to remove some substring (contiguous subsequence) from s of maximum possible length such that after removing this substring t will remain a subsequence of s. If you want to remove the substring s[l;r] then the string s will be transformed to s_1 s_2 ... s_{l-1} s_{r+1} s_{r+2} ... s_{|s|-1} s_{|s|} (where |s| is the length of s). Your task is to find the maximum possible length of the substring you can remove so that t is still a subsequence of s. Input The first line of the input contains one string s consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. The second line of the input contains one string t consisting of at least 1 and at most 2 β‹… 10^5 lowercase Latin letters. It is guaranteed that t is a subsequence of s. Output Print one integer β€” the maximum possible length of the substring you can remove so that t is still a subsequence of s. Examples Input bbaba bb Output 3 Input baaba ab Output 2 Input abcde abcde Output 0 Input asdfasdf fasd Output 3 Submitted Solution: ``` from sys import stdin,stdout s=stdin.readline().strip() t=stdin.readline().strip() leftmost=[-1] ptr1=ptr2=0 while ptr2<len(t): if s[ptr1]==t[ptr2]: leftmost.append(ptr1) ptr1+=1;ptr2+=1 else: ptr1+=1 rightmost=[] ptr1=len(s)-1 ptr2=len(t)-1 while ptr2>=0: if s[ptr1]==t[ptr2]: rightmost.append(ptr1) ptr1-=1;ptr2-=1 else: ptr1-=1 rightmost.reverse();rightmost.append(len(s)) ans=1<<64 for i in range(len(leftmost)-1): ans=max(ans,leftmost[i]+rightmost[i+1]-1) stdout.write(str(ans)+"\n") #print(leftmost) #print(rightmost) ``` No
4,254
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Tags: math, number theory Correct Solution: ``` mod=10**9+7 from sys import stdin, stdout import bisect from bisect import bisect_left as bl #c++ lowerbound bl(array,element) from bisect import bisect_right as br #c++ upperbound import itertools import collections import math import heapq from random import randint as rn def modinv(n,p): return pow(n,p-2,p) def ncr(n,r,p): #for using this uncomment the lines calculating fact and ifact t=((fact[n])*((ifact[r]*ifact[n-r])%p))%p return t def ain(): #takes array as input return list(map(int,sin().split())) def sin(): return input() def inin(): return int(input()) def GCD(x,y): while(y): x, y = y, x % y return x """*******************************************************""" def main(): n=int(input()) a=[] for i in range(n): l=ain() a.append(l) x=1 l=1 r=1000000001 while l <= r: mid = l + (r - l)//2; midd= a[0][1]//mid if (a[1][2]*mid==a[0][2]*midd): break # If x is greater, ignore left half elif (a[1][2]*mid<a[0][2]*midd): l = mid + 1 # If x is smaller, ignore right half else: r = mid - 1 # If we reach here, then the element # was not present z=int(mid) print(z,end=" ") for i in range(1,n): print(a[0][i]//z,end=" ") ######## Python 2 and 3 footer by Pajenegod and c1729 py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: self.write = lambda s:self.buffer.write(s.encode('ascii')) self.read = lambda:self.buffer.read().decode('ascii') self.readline = lambda:self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') if __name__ == '__main__': main() #threading.Thread(target=main).start() ```
4,255
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Tags: math, number theory Correct Solution: ``` from sys import stdin,stdout from math import sqrt from functools import reduce input=stdin.readline n=int(input()) a=list(map(int,input().split()))[1:] p=a[0]*a[1] p=int(sqrt(p//(list(map(int,input().split())))[2])) for i in range(n-2):input().rstrip('\n') print(p,*[i//p for i in a]) ```
4,256
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Tags: math, number theory Correct Solution: ``` #!/usr/bin/env python3 import atexit import io import sys _I_B = sys.stdin.read().splitlines() input = iter(_I_B).__next__ _O_B = io.StringIO() sys.stdout = _O_B @atexit.register def write(): sys.__stdout__.write(_O_B.getvalue()) def main(): n=int(input()) m=[] for i in range(n): m.append(list(map(int,input().split()))) a1=int(((m[0][2]*m[0][1])//m[1][2])**0.5) print(a1,end=" ") for i in range(1,n): print(m[0][i]//a1,end=" ") if __name__=='__main__': main() ```
4,257
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Tags: math, number theory Correct Solution: ``` n = int(input()) M = [] for i in range(n): M += [list(map(int,input().split()))] arr = [] for k in range(n//2) : arr += [int((M[k][k+1]*M[k][k+2] / M[k+1][k+2])**0.5)] for k in range(n//2,n) : arr += [int((M[k][k-1]*M[k][k-2] / M[k-1][k-2])**0.5)] print(*arr) ```
4,258
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Tags: math, number theory Correct Solution: ``` import math n = int(input()) arr = [] for _ in range(n): arr.append(list(map(int,input().split()))) # x/y = arr[1][2] / arr[0][2] # x*y = arr[0][1] s = int(math.sqrt(arr[0][1]*arr[0][2]//arr[1][2])) print(s,end=" ") for i in range(1,n): print(arr[0][i]//s,end=" ") ```
4,259
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Tags: math, number theory Correct Solution: ``` import math n = int(input()) arr2 = [] arr = [] for _ in range(n): arr2.append(list(map(int, input().split()))) x = arr2[1][0] y = arr2[2][0] z = arr2[2][1] a1 = int(math.sqrt((x*y) // z)) arr.append(a1) for h in range(1, n): arr.append(arr2[h][0] // arr[0]) print(*arr) ```
4,260
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Tags: math, number theory Correct Solution: ``` from math import * n=int(input()) l=[[int(j) for j in input().split()] for i in range(n)] g=[] for x in range(n): flag=0 d=0 for y in range(n): if flag: break for z in range(n): a=l[x][y] b=l[x][z] c=l[y][z] if a and b and c: flag=1 d=a*b//c break g.append(int(sqrt(d))) print(*g) ```
4,261
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Tags: math, number theory Correct Solution: ``` n = int(input()) a = [[int(i) for i in input().split()] for j in range(n)] ans = [] a[0][0] = (a[2][0] * a[0][1]) // a[2][1] ans.append(int(a[0][0] ** 0.5)) for i in range(1, n): a[i][i] = (a[i - 1][i] * a[i][i - 1]) // a[i - 1][i - 1] ans.append(int(a[i][i] ** 0.5)) print(*ans) ```
4,262
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Submitted Solution: ``` # for t in range(int(input())): n = int(input()) from math import gcd, sqrt m = [1 for i in range(n)] l = [[] for i in range(n)] for i in range(n): l[i] = [int(j) for ct,j in enumerate(input().split())] val = l[n-2][-1] # ls = [[]] prod = 1 for i in range(1,3): prod *= l[n-3][n-3+i] m[n-3] = int((prod/val)**0.5) for i in range(1,3): m[n-3+i] = l[n-3][n-3+i]//m[n-3] for i in range(n-3, -1, -1): m[i] = l[i][i+1]//m[i+1] for i in range(n): print(m[i], end = " ") print() ``` Yes
4,263
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Submitted Solution: ``` n=int(input()) p=[] for i in range(n): q=[] q=list(map(int,input().split())) p.append(q) a=0 r=[] a2=int(((p[0][2]*p[1][2])/p[0][1])**(1/2)) for j in range(1,n): if(j!=2): a=int((p[0][j]*a2)/p[0][2]) r.append(a) a0=int(p[0][1]/r[0]) print(a0,end=" ") print(r[0],end=" ") print(a2,end=" ") for i in range(0,n-3): print(r[i+1],end=" ") ``` Yes
4,264
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Submitted Solution: ``` import math n=int(input()) lst=[] a=[] for i in range(n): d=input() d=d.split(" ") d=[int(x) for x in d] lst.append(d) a.append(0) a[0]=math.sqrt(lst[0][1]*lst[0][2]/lst[1][2]) for i in range(1,n): a[i]=lst[0][i]/a[0] for i in range(n): a[i]=int(a[i]) print(*a) ``` Yes
4,265
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Submitted Solution: ``` __author__ = 'Esfandiar' from math import ceil,sqrt #from collections import* #from heapq import* #n = int(input()) #a = list(map(int,input().split())) n = int(input()) a = list() res = [0]*n for i in range(n): a.append(list(map(int,input().split()))) a1 = int(sqrt(a[0][1]*a[0][2]//a[1][2])) res[0] = a1 for i in range(1,n): res[i] = a[0][i]//a1 print(*res) ''' a1*a2 = a[0][1] a1*a3 = a[0][2] a2*a3 = a[1][2] a3 = a[1][2]//a2 a1*a2 = a[0][1] a1*(a[1][2]//a2) = a[0][2] a2-(a[1][2]//a2) == a[0][1]-a[0][2] ''' ``` Yes
4,266
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Submitted Solution: ``` import math def solve(arr,n): a1=int(math.sqrt(arr[0][1]*arr[0][2]//arr[1][2])) print(a1) ans=[a1] for i in arr[0][1:]: ans.append(i//a1) for i in ans: print(i,end=' ') test=1 # test=int(input()) for t in range(0,test): n = int(input()) rows, cols = (n, n) arr = [[int(i) for i in input().split()] for j in range(rows)] # n,k = [int(x) for x in input().split()] # arr = [int(x) for x in input().split()] solve(arr,n) ``` No
4,267
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Submitted Solution: ``` def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) n = int(input()) arr = [] for i in range(n): q = list(map(int, input().split())) arr.append(q) a2 = gcd(arr[0][1], arr[1][2]) a1a2 = arr[0][1] a1 = a1a2//a2 ans = [a1, a2] for i in range(1, n-1): ans.append(arr[i][i+1] // ans[-1]) print(*ans) ``` No
4,268
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Submitted Solution: ``` def find_gcd(x, y): while(y): x,y = y, x % y return x import math n=int(input()) a=[] x=[] for i in range(0,n): x=list(map(int,input().split())) a.append(x) f=0 ind=0 for i in range(0,n): for j in range(0,n-1): if(a[i][j]!=a[i][j+1] and a[i][j]!=0 and a[i][j+1]!=0): f=1 ind=i break if(f==1): break if(f==0): temp=int(math.sqrt(a[0][1])) ans=[temp]*n print(*ans) else: f=a[ind][0] s=a[ind][1] temp=find_gcd(f,s) for i in range(2,n): temp=find_gcd(temp,a[ind][i]) ans=[0]*n for i in range(0,n): if(i==ind): ans[i]=temp else: ans[i]=int(a[ind][i]/temp) print(*ans) ``` No
4,269
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i β‹… a_j where a_1, ..., a_n is some sequence of positive integers. Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, ..., a_n. Help Sasha restore the array! Input The first line contains a single integer n (3 β©½ n β©½ 10^3), the size of the table. The next n lines contain n integers each. The j-th number of the i-th line contains the number M_{ij} (1 ≀ M_{ij} ≀ 10^9). The table has zeroes on the main diagonal, that is, M_{ii}=0. Output In a single line print n integers, the original array a_1, ..., a_n (1 ≀ a_i ≀ 10^9). It is guaranteed that an answer exists. If there are multiple answers, print any. Examples Input 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 Output 2 2 3 1 2 Input 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 Output 9999 10000 9998 Submitted Solution: ``` import math n = int(input("")) a = list(map(int, input("").split())) g = a[1] for i in range(2,n): g = math.gcd(g,a[i]) for i in range(n-1): b = list(map(int, input("").split())) print(g,end=' ') for i in range(1,n): print(a[i]//g, end = ' ') ``` No
4,270
Provide tags and a correct Python 3 solution for this coding contest problem. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Tags: dsu, graphs, greedy, shortest paths, trees Correct Solution: ``` import bisect import functools import math import sys from collections import defaultdict # input = sys.stdin.readline rt = lambda: map(int, input().split()) ri = lambda: int(input()) rl = lambda: list(map(int, input().split())) def dist(x1, y1, x2, y2): return abs(x1-x2)+abs(y1-y2) def main(): n = ri() x, y = [0] * n, [0] * n for i in range(n): x[i], y[i] = rt() c = rl() k = rl() val = c.copy() used = [False] * n link = [-1] * n to_build = [] for _ in range(n): # each step removes 1 city # find min min_index = -1 min_val = math.inf for i in range(n): if not used[i] and val[i] < min_val: min_index = i min_val = val[i] used[min_index] = True if link[min_index] == -1: to_build.append(min_index+1) for i in range(n): if not used[i]: to_link = (k[i]+k[min_index])*dist(x[i], y[i], x[min_index], y[min_index]) if to_link < val[i]: val[i] = to_link link[i] = min_index print(sum(val)) print(len(to_build)) print(*to_build) print(len([x for x in link if x > -1])) for i in range(n): if link[i] > -1: print(i+1, link[i]+1) if __name__ == '__main__': main() ```
4,271
Provide tags and a correct Python 3 solution for this coding contest problem. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Tags: dsu, graphs, greedy, shortest paths, trees Correct Solution: ``` def prim(matrix, inf=10**18): n = len(matrix) costs = [inf] + [inf-1]*(n-1) nearest = [-1]*n current = 0 total_cost = 0 build, connect = [], [] for _ in range(n-1): min_cost = inf src, dest = -1, -1 for i in range(n): if costs[i] == inf: continue if matrix[current][i] < costs[i]: costs[i] = matrix[current][i] nearest[i] = current if min_cost > costs[i]: min_cost = costs[i] src, dest = nearest[i], i total_cost += min_cost costs[dest] = inf if src == 0: build.append(dest) else: connect.append('%d %d' % (src, dest)) current = dest return build, connect, total_cost if __name__ == '__main__': import sys n = int(input()) pos = [list(map(int, sys.stdin.readline().split())) for _ in range(n)] c_costs = list(map(int, input().split())) k_costs = list(map(int, input().split())) inf = 10**18 matrix = [[inf]*(n+1) for _ in range(n+1)] for i in range(n): for j in range(i+1, n): matrix[i+1][j+1] = matrix[j+1][i+1] = \ (abs(pos[i][0]-pos[j][0]) + abs(pos[i][1]-pos[j][1])) * (k_costs[i]+k_costs[j]) matrix[i+1][0] = matrix[0][i+1] = c_costs[i] build, connect, cost = prim(matrix) print(cost) print(len(build)) print(*build) print(len(connect)) if connect: print(*connect, sep='\n') ```
4,272
Provide tags and a correct Python 3 solution for this coding contest problem. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Tags: dsu, graphs, greedy, shortest paths, trees Correct Solution: ``` import sys reader = (map(int, s.split()) for s in sys.stdin) n, = next(reader) xy = [] for _ in range(n): x, y = next(reader) xy.append([x, y]) c = list(next(reader)) k = list(next(reader)) # n = int(input()) # xy = [[]]*n # for i in range(n): # xy[i] = list(map(int,input().split())) # c = list(map(int,input().split())) # k = list(map(int,input().split())) graph = [[0 for _ in range(n+1)] for _i in range(n+1)] for i in range(n): for j in range(i+1,n): cost = (abs(xy[i][0]-xy[j][0])+abs(xy[i][1]-xy[j][1]))*(k[i]+k[j]) graph[i][j] = graph[j][i] = cost graph[n][i] = graph[i][n] = c[i] # def output(parent): # es = [] # vs = [] # cost = 0 # for i in range(1,(n+1)): # if parent[i]==n: # vs.append(i+1) # elif i==n: # vs.append(parent[i]+1) # else: # es.append([i+1,parent[i]+1]) # cost+= graph[i][parent[i]] # print(cost) # print(len(vs)) # print(*vs) # print(len(es)) # for i in es: # print(i[0],i[1]) # def minKey(key, mstSet): # # Initilaize min value # min = 1000000000000 # for v in range((n+1)): # if key[v] < min and mstSet[v] == False: # min = key[v] # min_index = v # return min_index def primMST(): # Key values used to pick minimum weight edge in cut key = [1000000000000] * (n+1) parent = [None] * (n+1) # Array to store constructed MST # Make key 0 so that this vertex is picked as first vertex key[0] = 0 mstSet = [False] * (n+1) parent[0] = -1 # First node is always the root of for cout in range((n+1)): # Pick the minimum distance vertex from # the set of vertices not yet processed. # u is always equal to src in first iteration mn = 1000000000000 for v in range((n+1)): if key[v] < mn and mstSet[v] == False: mn = key[v] min_index = v u = min_index # Put the minimum distance vertex in # the shortest path tree mstSet[u] = True # Update dist value of the adjacent vertices # of the picked vertex only if the current # distance is greater than new distance and # the vertex in not in the shotest path tree for v in range((n+1)): # graph[u][v] is non zero only for adjacent vertices of m # mstSet[v] is false for vertices not yet included in MST # Update the key only if graph[u][v] is smaller than key[v] if graph[u][v] > 0 and mstSet[v] == False and key[v] > graph[u][v]: key[v] = graph[u][v] parent[v] = u # es = [] vss = 0 # vs = [] cost = 0 for i in range(1,(n+1)): if parent[i]==n or i==n: vss += 1 # vs.append(i+1) # elif i==n: # vs.append(parent[i]+1) # else: # es.append([i+1,parent[i]+1]) cost+= graph[i][parent[i]] myprint = sys.stdout.write myprint(str(cost) + '\n') # print(cost) # print(vss) myprint(str(vss)+'\n') vs = [0]*(vss) es = [[]]*(n-vss) k1,k2 = 0,0 for i in range(1,(n+1)): if parent[i]==n: vs[k1] = i+1 k1+=1 elif i==n: vs[k1] = parent[i]+1 k1+=1 else: es[k2] = [i+1,parent[i]+1] k2+=1 # cost+= graph[i][parent[i]] # print(*vs) [myprint(str(st) + ' ') for st in vs] myprint('\n') myprint(str(len(es))+'\n') [myprint(str(i[0]) + ' ' + str(i[1]) + '\n') for i in es] # print(len(es)) # for i in es: # print(i[0],i[1]) # myprint(str(totalCost) + '\n') # myprint(str(len(stations)) + '\n') # [myprint(str(st) + ' ') for st in stations]; # myprint(str(len(connections)) + '\n') # [myprint(str(c1) + ' ' + str(c2) + '\n') for c1, c2 in connections]; primMST() # e = 0 # i=0 # ans = [] # ret = 0 # while e<n: # edge = edges[i] # i+=1 # cost,a,b = edge # if find(a)!=find(b): # e+=1 # ans.append([cost,a,b]) # union(a,b) # ret += cost # vs = [] # es = [] # for i in ans: # if i[1]==n: # vs.append(i[2]+1) # else: # es.append(i) # print(ret) # print(len(vs)) # print(*vs) # print(len(es)) # for i in es: # print(i[1]+1,i[2]+1) ```
4,273
Provide tags and a correct Python 3 solution for this coding contest problem. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Tags: dsu, graphs, greedy, shortest paths, trees Correct Solution: ``` from collections import deque from math import inf def run_testcase(): n = int(input()) coords = [None] * (n + 1) for i in range(1, n + 1): coords[i] = [int(x) for x in input().split()] ci = [0] + [int(x) for x in input().split()] ki = [0] + [int(x) for x in input().split()] def cost(i, j): if i == j: return 0 if i > j: i, j = j, i if i == 0: return ci[j] return (abs(coords[i][0] - coords[j][0]) + abs(coords[i][1] - coords[j][1])) * (ki[i] + ki[j]) current_cost = 0 tree = set([0]) rest = set(range(1, n + 1)) included = [True] + [False] * n connections = deque() connections_to_station = 0 # min_attach_cost = [0] + [inf] * n # min_attach_cost = [0] + [cost(0, j) for j in range(1, n + 1)] min_attach_cost = [(0, 0)] + [(cost(0, j), 0) for j in range(1, n + 1)] while len(tree) < n + 1: min_pair = (0, 0) min_cost = inf # for tree_node in tree: # for i in range(1, n + 1): # if included[i]: # continue # curr_cost = cost(tree_node, i) # if curr_cost < min_cost: # min_pair = (tree_node, i) # min_cost = curr_cost for node in rest: if min_attach_cost[node][0] < min_cost: min_pair = (min_attach_cost[node][1], node) min_cost = min_attach_cost[node][0] tree.add(min_pair[1]) included[min_pair[1]] = True current_cost += min_cost rest.remove(min_pair[1]) for node in rest: if cost(min_pair[1], node) < min_attach_cost[node][0]: min_attach_cost[node] = (cost(min_pair[1], node), min_pair[1]) min_pair = tuple(sorted(min_pair)) if min_pair[0] == 0: connections.appendleft(min_pair) connections_to_station += 1 else: connections.append(min_pair) connections_list = list(connections) print(current_cost) print(connections_to_station) print(' '.join(map(lambda x: str(x[1]), connections_list[:connections_to_station]))) print(len(connections_list) - connections_to_station) for i in range(connections_to_station, len(connections_list)): print(connections_list[i][0], connections_list[i][1]) # testcase_count = int(input()) # for i in range(testcase_count): # print(str(run_testcase())) run_testcase() ```
4,274
Provide tags and a correct Python 3 solution for this coding contest problem. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Tags: dsu, graphs, greedy, shortest paths, trees Correct Solution: ``` import sys input = sys.stdin.readline n=int(input()) T=[tuple(map(int,input().split())) for i in range(n)] C=list(map(int,input().split())) K=list(map(int,input().split())) import heapq H=[] for i,c in enumerate(C): H.append((c,i+1)) heapq.heapify(H) ANS=0 USE=[0]*(n+1) ANS1=[] ANS2=[] while H: x=heapq.heappop(H) #print(x) #print(H) if len(x)==2: cost,town=x if USE[town]==1: continue ANS+=cost USE[town]=1 ANS1.append(town) xt,yt=T[town-1] for i in range(n): if USE[i+1]==1: continue costp=(abs(T[i][0]-xt)+abs(T[i][1]-yt))*(K[i]+K[town-1]) #print(costp,xt,yt,i) if costp<C[i]: C[i]=costp heapq.heappush(H,(costp,town,i+1)) else: cost,town1,town2=x if USE[town1]==1 and USE[town2]==1: continue ANS+=cost USE[town2]=1 ANS2.append((town1,town2)) xt,yt=T[town2-1] for i in range(n): if USE[i+1]==1: continue costp=(abs(T[i][0]-xt)+abs(T[i][1]-yt))*(K[i]+K[town2-1]) if costp<C[i]: C[i]=costp heapq.heappush(H,(costp,town2,i+1)) sys.stdout.write(str(ANS)+"\n") sys.stdout.write(str(len(ANS1))+"\n") print(*ANS1) sys.stdout.write(str(len(ANS2))+"\n") for x,y in ANS2: sys.stdout.write(str(x)+" "+str(y)+"\n") ```
4,275
Provide tags and a correct Python 3 solution for this coding contest problem. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Tags: dsu, graphs, greedy, shortest paths, trees Correct Solution: ``` from math import * c=int(input()) x=[0]*c y=[0]*c vu=[False]*c for i in range(c): x[i],y[i]=[int(s) for s in input().split()] prix=[int(s) for s in input().split()] fil=[int(s) for s in input().split()] anc=[-1]*c pmin=prix.copy() v=0 pl=[] e=0 ppl=[] tot=0 for i in range(c): pmina=100000000000000000000000 for j in range(c): if (not vu[j]) and pmin[j]<pmina: pmini=j pmina=pmin[j] vu[pmini]=True tot+=pmina if anc[pmini]==-1: v+=1 pl.append(str(pmini+1)) else: e+=1 ppl.append([str(pmini+1),str(anc[pmini]+1)]) for j in range(c): if (abs(x[pmini]-x[j])+abs(y[pmini]-y[j]))*(fil[pmini]+fil[j])<pmin[j]: pmin[j]=(abs(x[pmini]-x[j])+abs(y[pmini]-y[j]))*(fil[pmini]+fil[j]) anc[j]=pmini print(tot) print(v) print(" ".join(pl)) print(e) for i in ppl: print(" ".join(i)) ```
4,276
Provide tags and a correct Python 3 solution for this coding contest problem. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Tags: dsu, graphs, greedy, shortest paths, trees Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def prims(n,path,st,z,c,conn): ans,where,visi = 0,[z]*n,[0]*n node = [path[j][z] for j in range(n)] visi[z] = 1 while 1: le,y,dig = float("inf"),-1,0 for j in range(n): if visi[j]: continue if node[j] < c[j] and node[j] < le: le,y,dig = node[j],j,0 elif c[j] < node[j] and c[j] < le: le,y,dig = c[j],j,1 if le == float("inf"): return ans visi[y] = 1 if not dig: conn.append((where[y]+1,y+1)) else: st.append(y+1) ans += le for j,i in enumerate(path[y]): if not visi[j] and i < node[j]: node[j],where[j] = i,y def main(): n = int(input()) x,y = [],[] for a1,b1 in iter([map(int,input().split()) for _ in range(n)]): x.append(a1) y.append(b1) c = list(map(float,input().split())) k = list(map(float,input().split())) path = [[0]*n for _ in range(n)] for i in range(n): for j in range(i+1,n): z = (k[i]+k[j])*(abs(x[i]-x[j])+abs(y[i]-y[j])) path[i][j],path[j][i] = z,z z,ans,st,conn = c.index(min(c)),min(c),[],[] st.append(z+1) ans += prims(n,path,st,z,c,conn) print(int(ans)) print(len(st)) print(*st) print(len(conn)) for i in conn: print(*i) # Fast IO Region 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") if __name__ == "__main__": main() ```
4,277
Provide tags and a correct Python 3 solution for this coding contest problem. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Tags: dsu, graphs, greedy, shortest paths, trees Correct Solution: ``` import sys input=sys.stdin.readline n=int(input()) X=[[0]*7 for _ in range(n)] for i in range(n): x,y=map(int,input().split()) X[i][0],X[i][1],X[i][2]=i+1,x,y C=[int(i) for i in input().split()] K=[int(i) for i in input().split()] for i in range(n): X[i][3],X[i][4]=C[i],K[i] ans_am=0 ans_ps=0 Ans=[] ans_con=0 Con=[] def m(X): ret=0 cur=X[0][3] for i in range(1,len(X)): if X[i][3]<cur: ret=i cur=X[i][3] return ret while X: r=m(X) ind,x,y,c,k,flag,source=X.pop(r) ans_am+=c if flag==0: ans_ps+=1 Ans.append(ind) else: ans_con+=1 Con.append((ind,source)) for i in range(len(X)): indi,xi,yi,ci,ki,flagi,sourcei=X[i] cost=(k+ki)*(abs(x-xi)+abs(y-yi)) if cost<ci: X[i][3],X[i][5],X[i][6]=cost,1,ind print(ans_am) print(ans_ps) print(*Ans) print(ans_con) for i,j in Con: print(i,j) ```
4,278
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Submitted Solution: ``` n=int(input()) X=[[0]*7 for _ in range(n)] for i in range(n): x,y=map(int,input().split()) X[i][0]=i+1 X[i][1]=x X[i][2]=y C=[int(i) for i in input().split()] K=[int(i) for i in input().split()] for i in range(n): X[i][3]=C[i] X[i][4]=K[i] ans_am=0 ans_ps=0 Ans=[] ans_con=0 Con=[] def m(X): ret=0 cur=X[0][3] for i in range(1,len(X)): if X[i][3]<cur: ret=i cur=X[i][3] return ret while X: r=m(X) ind,x,y,c,k,flag,source=X.pop(r) ans_am+=c if flag==0: ans_ps+=1 Ans.append(ind) else: ans_con+=1 Con.append([ind,source]) for i in range(len(X)): indi,xi,yi,ci,ki,flagi,sourcei=X[i] if (k+ki)*(abs(x-xi)+abs(y-yi))<ci: X[i][3]=(k+ki)*(abs(x-xi)+abs(y-yi)) X[i][5]=1 X[i][6]=ind print(ans_am) print(ans_ps) print(*Ans) print(ans_con) for i,j in Con: print(i,j) ``` Yes
4,279
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Submitted Solution: ``` import sys # inf = open('input.txt', 'r') # reader = (map(int, line.split()) for line in inf) reader = (map(int, s.split()) for s in sys.stdin) n, = next(reader) cities = [None] for _ in range(n): x, y = next(reader) cities.append((x, y)) cs = [None] + list(next(reader)) ks = [None] + list(next(reader)) n += 1 # extra 0 node (dummy node); edge (0, v) <=> v-node has station g = [[None] * n for _ in range(n)] for i in range(1, n): for j in range(i + 1, n): wire = ks[i] + ks[j] dist = abs(cities[i][0] - cities[j][0]) + \ abs(cities[i][1] - cities[j][1]) g[i][j] = g[j][i] = wire * dist for i in range(1, n): g[0][i] = g[i][0] = cs[i] for i in range(n): g[i][i] = float('inf') totalCost = 0 stations = [] connections = [] used = [False] * n min_e = [float('inf')] * n sel_e = [-1] * n start = 0 # starting from 0-node (dummy node) min_e[start] = 0 for i in range(n): v = -1 for j in range(n): if (not used[j] and (v == -1 or min_e[j] < min_e[v])): v = j # if min_e[v] == float('inf'): break used[v] = True fromNode = sel_e[v] if not fromNode: # edge (0, v) <=> v-node has station totalCost += g[v][fromNode] stations.append(v) elif fromNode > 0: totalCost += g[v][fromNode] connections.append((v, fromNode)) for to in range(n): if g[v][to] < min_e[to]: min_e[to] = g[v][to] sel_e[to] = v myprint = sys.stdout.write myprint(str(totalCost) + '\n') myprint(str(len(stations)) + '\n') [myprint(str(st) + ' ') for st in stations]; myprint(str(len(connections)) + '\n') [myprint(str(c1) + ' ' + str(c2) + '\n') for c1, c2 in connections]; # print(totalCost) # print(len(stations)) # print(*stations) # print(len(connections)) # [print(c1, c2) for c1, c2 in connections]; # inf.close() ``` Yes
4,280
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Submitted Solution: ``` #for _ in range(int(input())): #n,k=map(int, input().split()) #arr = list(map(int, input().split())) #ls= list(map(int, input().split())) import math n = int(input()) coor=[] def dis(x,y): return abs(x[0]-y[0])+abs(y[1]-x[1]) for i in range(n): u,v=map(int, input().split()) coor.append((u,v)) cost=list(map(int, input().split())) k=list(map(int, input().split())) d={} power_st=[] vis=[0]*n connect=[] parent=[-1 for i in range(n)] for i in range(n): d[i]=cost[i] ans=0 for i in range(n): m=min(d,key=d.get) if vis[m]==0: power_st.append(m) else: connect.append([m,parent[m]]) ans=ans+d[m] del d[m] for j in d.keys(): t=dis(coor[m],coor[j])*(k[m]+k[j]) if t<d[j]: d[j]=t parent[j]=m vis[j]=1 print(ans) print(len(power_st)) for i in power_st: print(i+1,end=" ") print() print(len(connect)) for i in connect: print(i[0]+1 ,i[1]+1) ``` Yes
4,281
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Submitted Solution: ``` n=int(input()) pos=[[*map(int,input().split())] for i in range(n)] *c,=map(int, input().split()) *k,=map(int, input().split()) used = [False for i in range(n)] parent = [-1 for i in range(n)] plants = [] connections = [] ans = 0 _n = n while(_n): _n -= 1 mn, u = min([(ci, i) for i, ci in enumerate(c) if not used[i]]) ans += mn used[u] = True if parent[u] == -1: plants.append(u) else: connections.append((min(parent[u], u), max(parent[u], u))) for i in range(n): con_cost = (k[u] + k[i])*(abs(pos[u][0]-pos[i][0])+abs(pos[u][1]-pos[i][1])) if con_cost < c[i]: c[i] = con_cost parent[i] = u print(ans) print(len(plants)) for p in sorted(plants): print(p+1, end=' ') print('') print(len(connections)) for con in connections: print(con[0]+1, con[1]+1) ``` Yes
4,282
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Submitted Solution: ``` import math n = int(input()) cityNo=[0]*n for i in range(n): cityNo[i]=list(map(int,input().split())) cost=list(map(int,input().split())) ks =list(map(int,input().split())) powerStation=[0]*n totalCost=sum(cost) print(totalCost) req_Powerstation=[] notReq_Powerstation=[] totalCost=0 established={} updated=[-1]*n for j in range(n): city=-1 mini=9999999999999999 for i in range(n): if mini>cost[i] and i not in established: city=i mini=cost[i] if updated[city]==-1: req_Powerstation.append(city+1) else: notReq_Powerstation.append([city+1,updated[city]+1]) established[city]=1 for i in range(n): cost_From_City = (ks[i]+ks[city])*(abs(cityNo[i][0]-cityNo[city][0])+abs(cityNo[i][1]-cityNo[city][1])) if cost_From_City<cost[i]: cost[i]=cost_From_City updated[i]=city # print(updated) print(len(req_Powerstation)) print(*req_Powerstation) print(len(notReq_Powerstation)) for i in range(len(notReq_Powerstation)): print(*notReq_Powerstation[i]) ``` No
4,283
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Submitted Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def prims(n,path,visi,st,c,conn): ans,mini,where = 0,c[st],[st]*n node = [path[j][st] for j in range(n)] while 1: le,y = float("inf"),-1 for j in range(n): if node[j] > le or visi[j] or node[j] > max(mini,c[j]): continue le,y = node[j],j if y == -1: return ans,st visi[y] = 1 conn.append((where[y]+1,y+1)) ans += le-max(mini,c[y]) if c[y] < mini: mini,st = c[y],y for j,i in enumerate(path[y]): if not visi[j] and i < node[j]: node[j],where[j] = i,y def main(): n = int(input()) x,y = [],[] for _ in range(n): a1,b1 = map(int,input().split()) x.append(a1) y.append(b1) c = list(map(float,input().split())) k = list(map(float,input().split())) path = [[0]*n for _ in range(n)] for i in range(n): for j in range(i+1,n): z = (k[i]+k[j])*(abs(x[i]-x[j])+abs(y[i]-y[j])) path[i][j],path[j][i] = z,z visi,ans1,st,conn = [0]*n,sum(c),[],[] for i in range(n): if visi[i]: continue visi[i] = 1 z = prims(n,path,visi,i,c,conn) ans1 += z[0] st.append(z[1]+1) print(int(ans1)) print(len(st)) print(*st) print(len(conn)) for i in conn: print(*i) # Fast IO Region 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") if __name__ == "__main__": main() ``` No
4,284
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Submitted Solution: ``` n = int(input()) posiciones = [] padres = [] for i in range(n): x,y = map(int,input().split()) posiciones.append([x,y]) padres.append(i) costos = list(map(int,input().split())) peajes = list(map(int,input().split())) min_c = float('inf') min_pos = float('inf') for i in range(n): c = costos[i] if c < min_c: min_c = c min_pos = i x_min, y_min = posiciones[min_pos] optimos = [] construcciones = [] uniones = [] cantidad_const = 0 cant_uniones = 0 for i in range(n): if i != min_pos: x,y = posiciones[i] distancia = (abs(x_min-x)+abs(y_min-y))* (peajes[i] + peajes[min_pos]) if (distancia > costos[i]): optimos.append(costos[i]) construcciones.append(i+1) cantidad_const += 1 else: optimos.append(distancia) cant_uniones += 1 uniones.append([i,min_pos]) else: optimos.append(min_c) construcciones.append(i+1) cantidad_const += 1 print(sum(optimos)) print(cantidad_const) print(*construcciones) print(cant_uniones) if cant_uniones: for i,j in uniones: print(i+1,j+1) ``` No
4,285
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows: There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i β‰  j. Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. * Building a power station in City i will cost c_i yen; * Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help. And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Input First line of input contains a single integer n (1 ≀ n ≀ 2000) β€” the number of cities. Then, n lines follow. The i-th line contains two space-separated integers x_i (1 ≀ x_i ≀ 10^6) and y_i (1 ≀ y_i ≀ 10^6) β€” the coordinates of the i-th city. The next line contains n space-separated integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^9) β€” the cost of building a power station in the i-th city. The last line contains n space-separated integers k_1, k_2, ..., k_n (1 ≀ k_i ≀ 10^9). Output In the first line print a single integer, denoting the minimum amount of yen needed. Then, print an integer v β€” the number of power stations to be built. Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order. After that, print an integer e β€” the number of connections to be made. Finally, print e pairs of integers a and b (1 ≀ a, b ≀ n, a β‰  b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order. If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them. Examples Input 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 Note For the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red): <image> For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen. For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 β‹… (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 β‹… (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen. Submitted Solution: ``` from collections import defaultdict from math import sqrt,factorial,gcd,log2,inf,ceil # map(int,input().split()) # l = list(map(int,input().split())) mod = 10**9 + 7 import sys sys.setrecursionlimit(10**9) def find_parent(u): if par[u]!=u: par[u]=find_parent(par[u]) return par[u] n = int(input()) par = [0]+[i+1 for i in range(n)] rank = [1]*(n+1) la = [] for i in range(n): x,y = map(int,input().split()) la.append([i+1,x,y]) c = list(map(int,input().split())) k = list(map(int,input().split())) edges = [] ans = 0 for i in range(n): for j in range(i+1,n): w = abs(la[i][1]-la[j][1]) + abs(la[i][2]-la[j][2]) # edges.append([w,la[i][0],la[j][0]]) z1 = find_parent(i+1) z2 = find_parent(j+1) if z1!=z2: cost = w*(k[z1-1]+k[z2-1]) stn = c[z1-1] + c[z2-1] if cost<=stn: if c[z1-1]<c[z2-1]: z1,z2 = z2,z1 par[z1] = z2 edges.append((i+1,j+1)) ans+=cost seti = set() for i in range(n): z = find_parent(i+1) seti.add(z) # print(seti) for i in seti: ans+=c[i-1] print(ans) print(len(seti)) print(*(sorted(seti))) print(len(edges)) for a,b in edges: print(a,b) ``` No
4,286
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Tags: data structures, implementation, math, two pointers Correct Solution: ``` t=int(input()) for i in range(t): n=int(input()) b=list(map(int,input().split())) c=[0]*(n+1) d=[] for j in range(n): c[b[j]]=j q=-1 r=100000000 for j in range(1,n+1): q=max(q,c[j]) r=min(r,c[j]) if (q-r+1)==j: d.append("1") else: d.append("0") print("".join(d)) ```
4,287
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Tags: data structures, implementation, math, two pointers Correct Solution: ``` from collections import defaultdict t = int(input()) for i in range(t): n = int(input()) l = list(map(int,input().split())) pair = defaultdict(int) for j in range(n): pair[l[j]]=j minindex = pair[1] maxindex = pair[1] output = "1" for j in range(2,n+1): index = pair[j] if(index<minindex): minindex = index if(index>maxindex): maxindex = index if(maxindex-minindex<j): output+="1" else: output+="0" # print(minindex,maxindex) print(output) ```
4,288
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Tags: data structures, implementation, math, two pointers Correct Solution: ``` from __future__ import division, print_function from io import BytesIO, IOBase import os,sys,math,heapq,copy from collections import defaultdict,deque from bisect import bisect_left,bisect_right from functools import cmp_to_key from itertools import permutations,combinations,combinations_with_replacement # <fastio> if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # </fastio> # sys.setrecursionlimit(10**6) mod=1000000007 # Reading Single Input def get_int(): return int(sys.stdin.readline().strip()) def get_str(): return sys.stdin.readline().strip() def get_float(): return float(sys.stdin.readline().strip()) # Reading Multiple Inputs def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_strs(): return map(str, sys.stdin.readline().strip().split()) def get_floats(): return map(float, sys.stdin.readline().strip().split()) # Reading List Of Inputs def list_ints(): return list(map(int, sys.stdin.readline().strip().split())) def list_strs(): return list(map(str, sys.stdin.readline().strip().split())) def list_floats(): return list(map(float, sys.stdin.readline().strip().split())) # ------------------------------------------------------------------------------------- # def main(): t=int(input()) for _ in range(t): n=int(input()) l=list_ints() l=[[l[i],i] for i in range(n)] l.sort() minimum=math.inf maximum=-math.inf for i in range(n): minimum=min(minimum,l[i][1]) maximum=max(maximum,l[i][1]) if((maximum-minimum)==i): print(1,end='') else: print(0,end='') print() if __name__ == "__main__": # sys.stdin=open('Input.txt','r') # sys.stdout=open('Output.txt','w') main() ```
4,289
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Tags: data structures, implementation, math, two pointers Correct Solution: ``` for _ in range(int(input())): n=int(input()) p=list(map(int,input().split())) inv=[0]*(n+1) for i in range(n): inv[p[i]]=i out="" mx,mn = 0,n for i in range(1,n+1): mx,mn=max(inv[i],mx),min(inv[i],mn) out+="1" if mx-mn+1 == i else "0" print(out) ```
4,290
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Tags: data structures, implementation, math, two pointers Correct Solution: ``` for j in range(int(input())): n = int(input()) c = list(map(int,input().split())) index = [0]*n for i in range(n): index[c[i]-1]=i ma = 0 mi = n ans = ['0']*n # print(index) for k in range(n): ma = max(index[k],ma) mi = min(index[k],mi) #print(k,mr,index[k]-index[0]) if ma-mi<=k: ans[k]='1' print(''.join(ans)) ```
4,291
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Tags: data structures, implementation, math, two pointers Correct Solution: ``` import sys,math,heapq,copy from sys import stdin,stdout from collections import defaultdict,deque from bisect import bisect_left,bisect_right from functools import cmp_to_key from itertools import permutations,combinations,combinations_with_replacement # sys.setrecursionlimit(10**6) # sys.stdin=open('Input.txt','r') # sys.stdout=open('Output.txt','w') mod=1000000007 # Reading Single Input def get_int(): return int(sys.stdin.readline().strip()) def get_str(): return sys.stdin.readline().strip() def get_float(): return float(sys.stdin.readline().strip()) # Reading Multiple Inputs def get_ints(): return map(int, sys.stdin.readline().strip().split()) def get_strs(): return map(str, sys.stdin.readline().strip().split()) def get_floats(): return map(float, sys.stdin.readline().strip().split()) # Reading List Of Inputs def list_ints(): return list(map(int, sys.stdin.readline().strip().split())) def list_strs(): return list(map(str, sys.stdin.readline().strip().split())) def list_floats(): return list(map(float, sys.stdin.readline().strip().split())) # ------------------------------------------------------------------------------------- # def print(value='',end='\n'): stdout.write(str(value)+end) t=get_int() for _ in range(t): n=get_int() l=list_ints() l=[[l[i],i] for i in range(n)] l.sort() minimum=math.inf maximum=-math.inf for i in range(n): minimum=min(minimum,l[i][1]) maximum=max(maximum,l[i][1]) if((maximum-minimum)==i): print(1,end='') else: print(0,end='') print() ```
4,292
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Tags: data structures, implementation, math, two pointers Correct Solution: ``` for _ in range(int(input())): n = int(input()) aff = 0 positions = {} l, r = n, 0 for i in input().split(): positions[int(i)-1] = aff aff += 1 for i in range(n): l = min(l, positions[i]) r = max(r, positions[i]) if r-l == i: print("1", sep='', end='') else: print("0", sep='', end='') print(end='\n') ```
4,293
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Tags: data structures, implementation, math, two pointers Correct Solution: ``` t = int(input()) while t: t -= 1 mark = {} n = int(input()) a = list(map(int, input().split())) for i in range(n): mark[a[i]] = i l = r = mark[1] ans = "1" for i in range(2, n+1): pos = mark[i] if pos > l and pos < r and r-l+1 == i: ans += "1" elif pos < l and abs(pos-l) == 1 and r-pos+1 == i: ans += "1" l = pos elif pos > r and abs(pos-r) == 1 and pos-l+1 == i: ans += "1" r = pos elif pos < l: l = pos ans += "0" elif pos > r: r = pos ans += "0" else: ans += "0" print(ans) ```
4,294
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Submitted Solution: ``` # -*- coding: utf-8 -*- import sys 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 list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 for _ in range(INT()): N = INT() A = [a-1 for a in LIST()] atoi = {} for i, a in enumerate(A): atoi[a] = i l = INF r = 0 ans = [] for a in range(N): i = atoi[a] l = min(l, i) r = max(r, i) seg = r - l if seg == a: ans.append('1') else: ans.append('0') print(''.join(ans)) ``` Yes
4,295
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Submitted Solution: ``` def solve(): n = int(input()) num = [0] + [int(x) for x in input().split()] pos = [0] * (n+1) for i in range(1, n+1): pos[num[i]] = i can = [0] * (n+1) visit = [0] * (n+1) l, r = pos[1], pos[1] tmp = 1 visit[1] = 1 can[1] = 1 for i in range(2, n+1): while (pos[i] < l): l -= 1 visit[num[l]] = 1 while (r < pos[i]): r += 1 visit[num[r]] = 1 while (tmp < n and visit[tmp+1]): tmp += 1 if (tmp == i and r-l+1 == i): can[i] = 1 print(*can[1:], sep = "") t = int(input()) for i in range(t): solve() ``` Yes
4,296
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from collections import Counter 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) def gcd(a, b): if a == 0: return b return gcd(b % a, a) def lcm(a, b): return (a * b) / gcd(a, b) def main(): for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) done = [0] * (n + 1) d = [[-1,-1]] for i in range(n): d.append([a[i], i]) d.sort() l = d[1][1] r = d[1][1] done[1] = 1 ans = [0] * (n + 1) ans[1] = 1 now = 2 for i in range(1, n): if d[i][1] < l: for j in range(l - 1, d[i][1] - 1, -1): done[a[j]] = 1 l = d[i][1] elif d[i][1] > r: for j in range(r + 1, d[i][1] + 1): done[a[j]] = 1 r = d[i][1] #print(done) while (now < n and done[now]): now += 1 #print(l, r, now, i) if now > i and r - l+1 == i: ans[i] = 1 #print(i) ans[n] = 1 for i in range(1,n+1): print(ans[i],end='') print('') return if __name__ == "__main__": main() ``` Yes
4,297
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Submitted Solution: ``` for _ in range(int(input())): _=input() tmp=input() n=map(int,tmp.split()) n=list(n) for i,x in enumerate(n): if x==1: break a=b=i+1 MAX=1 ans=[1] n=[float('inf')]+list(n)+[float('inf')] for i in range(2,len(n)-1): if n[a-1]>n[b+1]: MAX=max(n[b+1],MAX) b+=1 else: MAX=max(n[a-1],MAX) a-=1 if MAX==i: ans.append(1) else: ans.append(0) for i,x in enumerate(ans): ans[i]=str(x) print(''.join(ans)) ``` Yes
4,298
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≀ m ≀ n) beautiful, if there exists two indices l, r (1 ≀ l ≀ r ≀ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numbers 1, 3, 5, 6 are beautiful and 2, 4 are not. It is because: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 5 we will have a permutation [1, 3, 2] for m = 3; * if l = 1 and r = 5 we will have a permutation [4, 5, 1, 3, 2] for m = 5; * if l = 1 and r = 6 we will have a permutation [4, 5, 1, 3, 2, 6] for m = 6; * it is impossible to take some l and r, such that [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m for m = 2 and for m = 4. You are given a permutation p=[p_1, p_2, …, p_n]. For all m (1 ≀ m ≀ n) determine if it is a beautiful number or not. Input The first line contains the only integer t (1 ≀ t ≀ 1000) β€” the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the given permutation p. The next line contains n integers p_1, p_2, …, p_n (1 ≀ p_i ≀ n, all p_i are different) β€” the given permutation p. It is guaranteed, that the sum of n from all test cases in the input doesn't exceed 2 β‹… 10^5. Output Print t lines β€” the answers to test cases in the order they are given in the input. The answer to a test case is the string of length n, there the i-th character is equal to 1 if i is a beautiful number and is equal to 0 if i is not a beautiful number. Example Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 Note The first test case is described in the problem statement. In the second test case all numbers from 1 to 5 are beautiful: * if l = 3 and r = 3 we will have a permutation [1] for m = 1; * if l = 3 and r = 4 we will have a permutation [1, 2] for m = 2; * if l = 2 and r = 4 we will have a permutation [3, 1, 2] for m = 3; * if l = 2 and r = 5 we will have a permutation [3, 1, 2, 4] for m = 4; * if l = 1 and r = 5 we will have a permutation [5, 3, 1, 2, 4] for m = 5. Submitted Solution: ``` I = lambda:int(input()) ID = lambda:map(int, input().split()) IL = lambda:list(ID()) t = I() for _ in range(t): n = I() a = IL() #ans = [0]*n #ans[0] = 1 #ans[n-1] = 1 #p = n-1 p = n+1 i = 0 j = n-1 ans = '1' while j>i: if a[i]>a[j]: if a[i]<p: p = a[i] i+=1 else: if a[j]<p: p = a[j] j-=1 #if j - i ==p-1: #ans[j-i] = 1 if j - i == p -2: #ans[j-i] = 1 ans+='1' else: ans+='0' print(ans) #print(ans) #for k in ans: #print(k,end='') ``` No
4,299