text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Tags: graphs, shortest paths Correct Solution: ``` n, m = map(int, input().split()) g = [[] for _ in range(n)] for i in range(m): p, q = map(int, input().split()) g[p - 1].append(q - 1) g[q - 1].append(p - 1) comp = [-1] * n def shortest(root): dist = [-1] * n q = [0] * n left, right = 0, 1 q[left] = root dist[root] = 0 good = True while left < right: x = q[left] left = left + 1 for i in g[x]: if dist[i] is -1: dist[i] = 1 + dist[x] q[right] = i right = right + 1 elif dist[i] == dist[x]: good = False far = 0 for i in dist: if i > far: far = i return good, far, dist arr = [0] * n good = True for i in range(n): _, opt, dist = shortest(i) if _ is False: good = False if comp[i] is -1: for j in range(n): if dist[j] is not -1: comp[j] = i if arr[comp[i]] < opt: arr[comp[i]] = opt if good is False: print('-1') else: print(sum(arr)) ```
6,200
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Submitted Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] edges = [] diameters = [] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 edges.append(v) graph[u].append(v) graph[v].append(u) distance = [maxValue]*n cc = [maxValue]*n for i in range(0, n): if distance[i] == maxValue: cc = bfs_2k(graph, i, distance) if(cc == None): print(-1) return diameters.append(distance[cc[-1]]) for v in range(1, len(cc)): newDistance = [maxValue]*n samecc = bfs_2k(graph, cc[v], newDistance) diameters[-1] = max(diameters[-1], newDistance[samecc[-1]]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist): queue = [] qlen = 1 queue.append(initVertex) dist[initVertex] = 0 u = None while qlen: u = queue[0] qlen-=1 for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) qlen+=1 if (dist[u] - dist[v]) % 2 == 0: return None return queue solve() ``` No
6,201
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Submitted Solution: ``` n, m = map(int, input().split()) g = [[] for _ in range(n)] for i in range(m): p, q = map(int, input().split()) g[p - 1].append(q - 1) g[q - 1].append(p - 1) comp = [-1] * n def shortest(root): dist = [-1] * n q = [0] * n left, right = 0, 1 q[left] = root dist[root] = 0 good = True while left < right: x = q[left] left = left + 1 for i in g[x]: if dist[i] is -1: dist[i] = 1 + dist[x] q[right] = i right = right + 1 elif dist[i] == dist[x]: good = False far = 0 for i in dist: if i > far: far = i return good, far, dist arr = [0] * n good = True for i in range(n): _, opt, dist = shortest(i) if _ is False: good = False if arr[comp[i]] < opt: arr[comp[i]] = opt if good is False: print('-1') else: print(sum(arr)) ``` No
6,202
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Submitted Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def solve(): n, m = input().split() n = int(n) m = int(m) global maxValue maxValue = n*2 graph = [[] for _ in range(0, n)] for _ in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 graph[u].append(v) graph[v].append(u) diameters = [] ccNum = 1 # los a lo sumo n vertices en la misma componente conexa de i cc = [maxValue]*n for v in range(0, n): if cc[v] == maxValue: distance = [maxValue]*n last = bfs_2k(graph, v, distance, cc, ccNum) cc[v] = -cc[v] if(last == None): print(-1) return diameters.append(distance[last]) ccNum += 1 for v in range(0, n): if cc[v] > 0: distance = [maxValue]*n last = bfs_2k(graph, v, distance, cc, cc[v]) diameters[cc[v]-1] = max(diameters[-1], distance[last]) print(sum(diameters)) def bfs_2k(graph, initVertex, dist, cc, ccNum): queue = deque() queue.append(initVertex) dist[initVertex] = 0 cc[initVertex] = ccNum u = None while queue: u = queue.popleft() for v in graph[u]: if(dist[v] == maxValue): dist[v] = dist[u] + 1 queue.append(v) cc[v] = ccNum if (dist[u] - dist[v]) % 2 == 0: return None return u solve() ``` No
6,203
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task. Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices. Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k β‰₯ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≀ i ≀ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. <image> The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain. Input The first line contains two integers n, m (1 ≀ n ≀ 1000, 0 ≀ m ≀ 100 000) β€” the number of vertices and the number of edges in the original graph. Next m lines contain the descriptions of edges in the format ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes. Output If it is impossible to obtain a chain from the given graph, print - 1. Otherwise, print the maximum possible number of edges in the resulting chain. Examples Input 5 4 1 2 2 3 3 4 3 5 Output 3 Input 4 6 1 2 2 3 1 3 3 4 2 4 1 4 Output -1 Input 4 2 1 3 2 4 Output 2 Note In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3. In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result. In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. Submitted Solution: ``` n, m = map(int, input().split()) g = [[] for _ in range(n)] for i in range(m): p, q = map(int, input().split()) g[p - 1].append(q - 1) g[q - 1].append(p - 1) def shortest(root): dist = [-1] * n q = [0] * n left, right = 0, 1 q[left] = root dist[root] = 0 good = True while left < right: x = q[left] left = left + 1 for i in g[x]: if dist[i] is -1: dist[i] = 1 + dist[x] q[right] = i right = right + 1 elif dist[i] == dist[x]: good = False return good, dist def getDiameter(root): good, dist = shortest(root) far = root for i in range(n): if far < dist[i]: far = i dia = 0 _, dist = shortest(far) for i in range(n): if dia < dist[i]: dia = dist[i] return good, dia, dist vis = [False] * n good = True ans = 0 for i in range(n): if vis[i] is False: _, add, dist = getDiameter(i) if _ is False: good = False ans = ans + add for j in range(n): if dist[j] is not -1: vis[j] = True if good is False: print('-1') else: print(ans) ``` No
6,204
Provide tags and a correct Python 3 solution for this coding contest problem. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Tags: implementation Correct Solution: ``` n = int(input()) alco = ["ABSINTH", "BEER", 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'] count = 0 while n>0: n-=1 s = input() if s.isdecimal(): if int(s)<18: count+=1 else: if s in alco: count+=1 print(count) ```
6,205
Provide tags and a correct Python 3 solution for this coding contest problem. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Tags: implementation Correct Solution: ``` data=['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17',] q = 0 p=int(input()) for _ in range(p): n=input() if n in data: q+=1 print(q) ```
6,206
Provide tags and a correct Python 3 solution for this coding contest problem. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Tags: implementation Correct Solution: ``` alcho = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"] t = int(input()) c = 0 for _ in range(t): n = input() if n.isdigit(): if int(n) < 18: c += 1 else: if n in alcho: c += 1 print(c) ```
6,207
Provide tags and a correct Python 3 solution for this coding contest problem. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Tags: implementation Correct Solution: ``` alc=["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"];p=0 for _ in range(int(input())): x=input() if len(x)<=2: if ord(x[0])>=65: continue else: x=int(x) if x<18: p+=1 else: if x in alc: p+=1 print(p) ```
6,208
Provide tags and a correct Python 3 solution for this coding contest problem. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Tags: implementation Correct Solution: ``` #!/usr/bin/env python3 num = int(input()) lis = ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'] cnt = 0 for i in range(num): s = input() if s in lis: cnt += 1 # continue if s.isdigit(): s = int(s) if(s<18): cnt += 1 print(cnt) ```
6,209
Provide tags and a correct Python 3 solution for this coding contest problem. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Tags: implementation Correct Solution: ``` def solve(arr): count = 0 for i in arr: if i.isnumeric(): if int(i) < 18: count += 1 elif i in ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"]: count += 1 return count def main(): # vars = list(map(int, input().split(" "))) n = int(input()) arr = [] for _ in range(n): l = input() arr.append(l) # t = input() # s = input() # a = list(map(int, input().split(" "))) # b = list(map(int, input().split(" "))) # c = list(map(int, input().split(" "))) # res = [] # for _ in range(n): # arr = list(map(int, input().split(" "))) # res.append(arr) print(solve(arr)) # i = 0 # inputpath = 'input.txt' # outPath = 'output.txt' # with open(inputpath) as fp: # line = fp.readline() # cnt = 1 # while line: # if cnt == 1: # i = int(line) # else: # arr = list(map(int, line.split(" "))) # res.append(arr) # cnt += 1 # line = fp.readline() # s = solve(res,i) # with open(outPath, 'a') as out: # out.write(str(s)) main() ```
6,210
Provide tags and a correct Python 3 solution for this coding contest problem. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Tags: implementation Correct Solution: ``` a=["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"] ans=0 for i in range(int(input())): x=input() if x in a: ans+=1 else: try: y=int(x) if y<18: ans+=1 except: continue print(ans) ```
6,211
Provide tags and a correct Python 3 solution for this coding contest problem. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Tags: implementation Correct Solution: ``` t = int(input()) alco = "ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE".replace(",","").split() check = 0 for _ in range(t): n = input() check += int(n.isdigit() and int(n) < 18 or n in alco) print(check) ```
6,212
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Submitted Solution: ``` alcohol=['ABSINTH','BEER','BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'] d=0 for _ in range(int(input())): b=input() if b.isnumeric()==True: if int(b)<18: d+=1 else: if b in alcohol: d+=1 print(d) ``` Yes
6,213
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Submitted Solution: ``` n = int(input()) alc = ["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"] cnt = 0 for i in range(n): s = input() if s in alc: cnt+=1 if s.isnumeric() and int(s) < 18: cnt+=1 print(cnt) ``` Yes
6,214
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Submitted Solution: ``` n=int(input()) a="ABCDEFGHIJKLMNOPQRSTUVWXYZ" s="0123456789" w={"ABSINTH","BEER", "BRANDY","CHAMPAGNE","GIN","RUM","SAKE","TEQUILA","VODKA","WHISKEY","WINE"} c=0 for i in range(n): i=input() if i[0] in s and int(i)<18: c=c+1 elif i[0] in a and i in w: c=c+1 print(c) ``` Yes
6,215
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Submitted Solution: ``` a=int(input()) d=[] count=0 b=0 for i in range(a): c=input() d.append(c) for i in range(a): try: if (int(d[i])<18): count=count+1 except: if d[i] in ['ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE']: b=b+1 print(count+b) ``` Yes
6,216
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Submitted Solution: ``` n=int(input()) bar=[ 'ABSINTH', 'BEER', 'BRANDY', 'CHAMPAGNE', 'GIN','RUM','SAKE','TEQUILA','VODKA', 'WHISKEY', 'WINE'] d=[] for i in range(n): x=input() d.append(x) z=0 for drink in d: if drink in bar: z+=1 if drink<'18': z+=1 print(z) ``` No
6,217
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Submitted Solution: ``` x=['ABSINTH', 'BEER', 'BRANDY', ' CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE'] c=0 num='0123456789' for _ in range(int(input())): y=input() if y[0] in num: if int(y)<18: c+=1 elif y in x: c+=1 print(c) ``` No
6,218
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Submitted Solution: ``` c=0 s=["ABSINTH", "BEER", "BRANDY", "CHAMPAGNE", "GIN", "RUM", "SAKE", "TEQUILA", "VODKA", "WHISKEY", "WINE"] n=int(input()) for i in range(n): v=input() if(v<"18"): c+=1 else: if(v in s): c+=1 print(c) ``` No
6,219
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks? The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE Input The first line contains an integer n (1 ≀ n ≀ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol. Output Print a single number which is the number of people Vasya should check to guarantee the law enforcement. Examples Input 5 18 VODKA COKE 19 17 Output 2 Note In the sample test the second and fifth clients should be checked. Submitted Solution: ``` forbid = "ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY".split(", ") n = int(input()) a = [] for i in range(n): x = input() if x.isnumeric(): if int(x) < 18: a.append(x) if x.isalpha(): if x in forbid: a.append(x) print(len(a)) ``` No
6,220
Provide tags and a correct Python 3 solution for this coding contest problem. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Tags: data structures, expression parsing, math Correct Solution: ``` bracket = input() stack = [] bracketType = { '[': (0, ']'), '(': (0, ')'), '<': (0, '>'), '{': (0, '}'), ']': (1,), ')': (1,), '>': (1,), '}': (1,) } res = 0 for b in bracket: if bracketType.get(b) == None: break elif bracketType.get(b)[0] == 0: stack.append(b) elif bracketType.get(b)[0] == 1: if len(stack) == 0: res = 'Impossible' break else: if b != bracketType[stack.pop()][1]: res += 1 if len(stack): print('Impossible') else: print(res) ```
6,221
Provide tags and a correct Python 3 solution for this coding contest problem. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Tags: data structures, expression parsing, math Correct Solution: ``` s = input().strip() braces = {'<' : '>', '>' : '<', '{' : '}', '}' : '{', '[' : ']', ']' : '[', '(' : ')', ')' : '('} stack = [] answer = 0 for char in s: if char in "(<{[": stack.append(char) elif char in ")>}]": if not stack: print('Impossible') exit() lastBrace = stack.pop() if char != braces[lastBrace]: answer += 1 if not stack: print(answer) else: print("Impossible") ```
6,222
Provide tags and a correct Python 3 solution for this coding contest problem. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Tags: data structures, expression parsing, math Correct Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright Β© 2016 missingdays <missingdays@missingdays> # # Distributed under terms of the MIT license. """ """ opening = { "[": "]", "<": ">", "{": "}", "(": ")", } closing = { "]": "[", ">": "<", "}": "{", ")": "(", } s = input() stack = [] answ = 0 for c in s: if c in opening: stack.append(c) else: if len(stack) == 0: print("Impossible") exit() op = stack.pop() if c != opening[op]: answ += 1 if len(stack) != 0: print("Impossible") exit() print(answ) ```
6,223
Provide tags and a correct Python 3 solution for this coding contest problem. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Tags: data structures, expression parsing, math Correct Solution: ``` import sys s = input() stack = [] piar = {'{' : '}', '(' : ')', '<' : '>', '[':']'} ans = 0 for ch in s: if ch in piar.keys(): stack.append(ch) else: if len(stack) == 0: print("Impossible") sys.exit() if piar[stack.pop()] != ch: ans+=1 if len(stack) != 0: print("Impossible") sys.exit() print(ans) ```
6,224
Provide tags and a correct Python 3 solution for this coding contest problem. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Tags: data structures, expression parsing, math Correct Solution: ``` from collections import * from itertools import * from random import * from bisect import * from string import * from queue import * from heapq import * from math import * from re import * from sys import * def fast(): return stdin.readline().strip() def zzz(): return [int(i) for i in fast().split()] z, zz = input, lambda: list(map(int, z().split())) szz, graph, mod, szzz = lambda: sorted( zz()), {}, 10**9 + 7, lambda: sorted(zzz()) def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2)) def output(answer): stdout.write(str(answer)) dx = [-1, 1, 0, 0, 1, -1, 1, -1] dy = [0, 0, 1, -1, 1, -1, -1, 1] ###########################---Test-Case---################################# """ If you Know me , Then you probably don't know me ! """ ###########################---START-CODING---############################## cnt = 0 arr = fast() opn = {'(': ')', '<': '>', '[': ']', '{': '}'} openBract = 0 que = deque() for i in arr: if i in opn: openBract += 1 que.append(opn[i]) else: try: x = que.pop() if i != x: cnt += 1 que.appendleft(x) except: print("Impossible") exit() print(cnt if openBract == len(arr) - openBract else "Impossible") ```
6,225
Provide tags and a correct Python 3 solution for this coding contest problem. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Tags: data structures, expression parsing, math Correct Solution: ``` #!/usr/bin/env python3 import sys s = input() OPENING = ('<', '{', '[', '(') CLOSING = ('>', '}', ']', ')') result = 0 stack = [] for c in s: if c in OPENING: stack.append(c) else: if stack: last_br = stack.pop() if c != CLOSING[OPENING.index(last_br)]: result += 1 else: print("Impossible") sys.exit(0) print("Impossible" if stack else result) ```
6,226
Provide tags and a correct Python 3 solution for this coding contest problem. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Tags: data structures, expression parsing, math Correct Solution: ``` import sys s=input() stack = [] c=0 brackets = {')':'(',']':'[','}':'{','>':'<'} for char in s: if char in brackets.values(): stack.append(char) elif char in brackets.keys(): if stack==[]: print('Impossible') sys.exit() if brackets[char] != stack.pop(): c=c+1 if len(stack)!=0: print('Impossible') sys.exit(0) print(c) ```
6,227
Provide tags and a correct Python 3 solution for this coding contest problem. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Tags: data structures, expression parsing, math Correct Solution: ``` import sys import bisect from bisect import bisect_left as lb input_=lambda: sys.stdin.readline().strip("\r\n") from math import log from math import gcd from math import atan2,acos from random import randint sa=lambda :input_() sb=lambda:int(input_()) sc=lambda:input_().split() sd=lambda:list(map(int,input_().split())) se=lambda:float(input_()) sf=lambda:list(input_()) flsh=lambda: sys.stdout.flush() #sys.setrecursionlimit(10**6) mod=10**9+7 gp=[] cost=[] dp=[] mx=[] ans1=[] ans2=[] special=[] specnode=[] a=0 kthpar=[] def dfs(root,par): if par!=-1: dp[root]=dp[par]+1 for i in range(1,20): if kthpar[root][i-1]!=-1: kthpar[root][i]=kthpar[kthpar[root][i-1]][i-1] for child in gp[root]: if child==par:continue kthpar[child][0]=root dfs(child,root) d={')':'(',']':'[','}':'{','>':'<'} op=['(','[','{','<'] def hnbhai(): s=sa() stck=[] tot=0 for i in s: if i in op: stck.append(i) elif len(stck)==0: print("Impossible") return else: if d[i]!=stck[-1]: tot+=1 stck.pop() if len(stck)==0: print(tot) else: print("Impossible") for _ in range(1): hnbhai() ```
6,228
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Submitted Solution: ``` st = input() c = 0 b = r = s = l = 0 for i in st: if i in [ '[' , '<' , '{' , '(' ]: c += 1 else: c -= 1 if c < 0: break ans = 0 if c != 0: print('Impossible') else: stack = [] for i in st: if i in [ '[' , '<' , '{' , '(' ]: stack.append(i) else: if stack[-1] == '(' and i == ')': stack.pop() continue elif stack[-1] == '<' and i == '>': stack.pop() continue elif stack[-1] == '{' and i == '}': stack.pop() continue elif stack[-1] == '[' and i == ']': stack.pop() continue else: stack.pop() ans += 1 print(ans) ``` Yes
6,229
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Submitted Solution: ``` s = input() cnt = 0 st = [] for elem in s: if elem in '([{<': st.append(elem) else: if len(st) == 0: print('Impossible') break elem2 = st.pop() if elem2 + elem not in '()[]{}<>': cnt += 1 else: if len(st) == 0: print(cnt) else: print('Impossible') ``` Yes
6,230
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Submitted Solution: ``` ''' Replace To Make Regular Bracket Sequence ''' S = input() stack = [] count = 0 length = len(S) flag = 0 if(length % 2): flag = 1 else: for i in range(length): if S[i] =='<' or S[i] =='(' or S[i] =='{' or S[i] =='[': stack.append(S[i]) elif stack != []: #print(S[i]) if S[i] == '>' and stack.pop() != '<': count += 1 elif S[i] == ')' and stack.pop() != '(': count += 1 elif S[i] == '}' and stack.pop() != '{': count += 1 elif S[i] == ']' and stack.pop() != '[': count += 1 if(flag): break else: flag = 1 break if flag != 0 or len(stack) != 0: print("Impossible") else: print(count) ``` Yes
6,231
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Submitted Solution: ``` #------------------Important Modules------------------# from sys import stdin,stdout from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import * input=stdin.readline prin=stdout.write from random import sample from collections import Counter,deque from math import sqrt,ceil,log2,gcd #dist=[0]*(n+1) mod=10**9+7 class DisjSet: def __init__(self, n): # Constructor to create and # initialize sets of n items self.rank = [1] * n self.parent = [i for i in range(n)] # Finds set of given item x def find(self, x): # Finds the representative of the set # that x is an element of if (self.parent[x] != x): # if x is not the parent of itself # Then x is not the representative of # its set, self.parent[x] = self.find(self.parent[x]) # so we recursively call Find on its parent # and move i's node directly under the # representative of this set return self.parent[x] # Do union of two sets represented # by x and y. def union(self, x, y): # Find current sets of x and y xset = self.find(x) yset = self.find(y) # If they are already in same set if xset == yset: return # Put smaller ranked item under # bigger ranked item if ranks are # different if self.rank[xset] < self.rank[yset]: self.parent[xset] = yset elif self.rank[xset] > self.rank[yset]: self.parent[yset] = xset # If ranks are same, then move y under # x (doesn't matter which one goes where) # and increment rank of x's tree else: self.parent[yset] = xset self.rank[xset] = self.rank[xset] + 1 # Driver code def f(arr,i,j,d,dist): if i==j: return nn=max(arr[i:j]) for tl in range(i,j): if arr[tl]==nn: dist[tl]=d #print(tl,dist[tl]) f(arr,i,tl,d+1,dist) f(arr,tl+1,j,d+1,dist) #return dist def ps(n): cp=0;lk=0;arr=[];countprev=0; while n%2==0: n=n//2 lk+=1 for ps in range(3,ceil(sqrt(n))+1,2): lk=0 while n%ps==0: n=n//ps lk+=1 if n!=1: lk+=1 return [lk,"NO"] return [lk,"YES"] #count=0 #dp=[[0 for i in range(m)] for j in range(n)] #[int(x) for x in input().strip().split()] def gcd(x, y): while(y): x, y = y, x % y return x # Driver Code def factorials(n,r): #This calculates ncr mod 10**9+7 slr=n;dpr=r qlr=1;qs=1 mod=10**9+7 for ip in range(n-r+1,n+1): qlr=(qlr*ip)%mod for ij in range(1,r+1): qs=(qs*ij)%mod #print(qlr,qs) ans=(qlr*modInverse(qs))%mod return ans def modInverse(b): qr=10**9+7 return pow(b, qr - 2,qr) #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func def power(arr): listrep = arr subsets = [] for i in range(2**len(listrep)): subset = [] for k in range(len(listrep)): if i & 1<<k: subset.append(listrep[k]) subsets.append(subset) return subsets def dis(xa,ya,xb,yb): return sqrt((xa-xb)**2+(ya-yb)**2) #### END ITERATE RECURSION #### #=============================================================================================== #----------Input functions--------------------# def ii(): return int(input()) def ilist(): return [int(x) for x in input().strip().split()] def outstrlist(array:list)->str: array=[str(x) for x in array] return ' '.join(array); def islist(): return list(map(str,input().split().rstrip())) def outfast(arr:list)->str: ss='' for ip in arr: ss+=str(ip)+' ' return prin(ss); ###-------------------------CODE STARTS HERE--------------------------------########### ######################################################################################### #t=int(input()) t=1 for jj in range(t): aa=input().strip() kk=[] ss={'<':0,'{':1,'[':2,'(':3,'>':4,'}':5,']':6,')':7} cc=0;bb=0 for i in aa: if ss[i]<4: kk.append(ss[i]) else: if len(kk)>0: if ss[i]-kk[-1]!=4: cc+=1 kk.pop(); else: bb=1;break if bb==1 or len(kk)>0: print("Impossible") else: print(cc) ``` Yes
6,232
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Submitted Solution: ``` from sys import stdin, stdout class SOLVE: def solve(self): R = stdin.readline #f = open('input.txt');R = f.readline W = stdout.write s = R()[:-1] brackets, cnt = [], 0 for i in range(len(s)): if s[i] in ['(', '<', '{', '[']: brackets.append(s[i]) else: if len(brackets) == 0: W("Impossible\n") return 0 if s[i] == ')': if brackets[-1] != '(': cnt += 1 elif s[i] == '>': if brackets[-1] != '<': cnt += 1 elif s[i] == '}': if brackets[-1] != '{': cnt += 1 elif s[i] == ']': if brackets[-1] != '[': cnt += 1 brackets.pop() W('%d\n' % cnt) return 0 def main(): s = SOLVE() s.solve() main() ``` No
6,233
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Submitted Solution: ``` s=list(input()) o,cl=0,0 a,b,c,d=0,0,0,0 for i in s: if i=="(": a+=1 o+=1 elif i==")": a-=1 cl+=1 elif i=="{": b+=1 o+=1 elif i=="}": b-=1 cl+=1 elif i=="[": c+=1 o+=1 elif i=="]": c-=1 cl+=1 elif i=="<": d+=1 o+=1 else: d-=1 cl+=1 z=abs(a)+abs(b)+abs(c)+abs(d) if o==cl and z==0: print(0) elif o==cl and z!=0: print(z//2) elif o!=c: print("impossible") ``` No
6,234
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Submitted Solution: ``` s = input() brackets = { '<': '>', '{': '}', '[': ']', '(': ')', } OPENING = "<{[(" CLOSING = ">}])" def main(s): stack = [] res = 0 for c in s: if c in OPENING: stack.append(c) else: if stack: top = stack.pop() if top in OPENING: if brackets[top] != c: res += 1 continue return 'Impossible' return res print(main(s)) ``` No
6,235
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >. The following definition of a regular bracket sequence is well-known, so you can be familiar with it. Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS. For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not. Determine the least number of replaces to make the string s RBS. Input The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106. Output If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s. Examples Input [&lt;}){} Output 2 Input {()}[] Output 0 Input ]] Output Impossible Submitted Solution: ``` import sys s = input() stack = [] ans = 0 brackets = { '>': '<', '}': '{', ']': '[', ')': '(' } for c in s: if c in '>}])': if not stack: print('Impossible') exit() if stack[-1] != brackets[c]: ans += 1 stack.pop() else: stack.append(c) print(ans) ``` No
6,236
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Tags: sortings, strings Correct Solution: ``` n = int(input()) def comp(a, b): l = a + b r = b + a if l < r: return -1 elif l == r: return 0 else: return 1 from functools import cmp_to_key d = [] for _ in range(n): s = input().rstrip() d.append(s) d.sort(key=cmp_to_key(comp)) print(''.join(d)) ```
6,237
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Tags: sortings, strings Correct Solution: ``` #### IMPORTANT LIBRARY #### ############################ ### DO NOT USE import random --> 250ms to load the library ############################ ### In case of extra libraries: https://github.com/cheran-senthil/PyRival ###################### ####### IMPORT ####### ###################### from functools import cmp_to_key from collections import deque, Counter from heapq import heappush, heappop from math import log, ceil ###################### #### STANDARD I/O #### ###################### import sys import os 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") 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) def print(*args, **kwargs): 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() def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def ii(): return int(inp()) def si(): return str(inp()) def li(lag = 0): l = list(map(int, inp().split())) if lag != 0: for i in range(len(l)): l[i] += lag return l def mi(lag = 0): matrix = list() for i in range(n): matrix.append(li(lag)) return matrix def lsi(): #string list return list(map(str, inp().split())) def print_list(lista, space = " "): print(space.join(map(str, lista))) ###################### ### BISECT METHODS ### ###################### def bisect_left(a, x): """i tale che a[i] >= x e a[i-1] < x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] < x: left = mid+1 else: right = mid return left def bisect_right(a, x): """i tale che a[i] > x e a[i-1] <= x""" left = 0 right = len(a) while left < right: mid = (left+right)//2 if a[mid] > x: right = mid else: left = mid+1 return left def bisect_elements(a, x): """elementi pari a x nell'Γ‘rray sortato""" return bisect_right(a, x) - bisect_left(a, x) ###################### ### MOD OPERATION #### ###################### MOD = 10**9 + 7 maxN = 5 FACT = [0] * maxN INV_FACT = [0] * maxN def add(x, y): return (x+y) % MOD def multiply(x, y): return (x*y) % MOD def power(x, y): if y == 0: return 1 elif y % 2: return multiply(x, power(x, y-1)) else: a = power(x, y//2) return multiply(a, a) def inverse(x): return power(x, MOD-2) def divide(x, y): return multiply(x, inverse(y)) def allFactorials(): FACT[0] = 1 for i in range(1, maxN): FACT[i] = multiply(i, FACT[i-1]) def inverseFactorials(): n = len(INV_FACT) INV_FACT[n-1] = inverse(FACT[n-1]) for i in range(n-2, -1, -1): INV_FACT[i] = multiply(INV_FACT[i+1], i+1) def coeffBinom(n, k): if n < k: return 0 return multiply(FACT[n], multiply(INV_FACT[k], INV_FACT[n-k])) ###################### #### GRAPH ALGOS ##### ###################### # ZERO BASED GRAPH def create_graph(n, m, undirected = 1, unweighted = 1): graph = [[] for i in range(n)] if unweighted: for i in range(m): [x, y] = li(lag = -1) graph[x].append(y) if undirected: graph[y].append(x) else: for i in range(m): [x, y, w] = li(lag = -1) w += 1 graph[x].append([y,w]) if undirected: graph[y].append([x,w]) return graph def create_tree(n, unweighted = 1): children = [[] for i in range(n)] if unweighted: for i in range(n-1): [x, y] = li(lag = -1) children[x].append(y) children[y].append(x) else: for i in range(n-1): [x, y, w] = li(lag = -1) w += 1 children[x].append([y, w]) children[y].append([x, w]) return children def dist(tree, n, A, B = -1): s = [[A, 0]] massimo, massimo_nodo = 0, 0 distanza = -1 v = [-1] * n while s: el, dis = s.pop() if dis > massimo: massimo = dis massimo_nodo = el if el == B: distanza = dis for child in tree[el]: if v[child] == -1: v[child] = 1 s.append([child, dis+1]) return massimo, massimo_nodo, distanza def diameter(tree): _, foglia, _ = dist(tree, n, 0) diam, _, _ = dist(tree, n, foglia) return diam def dfs(graph, n, A): v = [-1] * n s = [[A, 0]] v[A] = 0 while s: el, dis = s.pop() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges def bfs(graph, n, A): v = [-1] * n s = deque() s.append([A, 0]) v[A] = 0 while s: el, dis = s.popleft() for child in graph[el]: if v[child] == -1: v[child] = dis + 1 s.append([child, dis + 1]) return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges #FROM A GIVEN ROOT, RECOVER THE STRUCTURE def parents_children_root_unrooted_tree(tree, n, root = 0): q = deque() visited = [0] * n parent = [-1] * n children = [[] for i in range(n)] q.append(root) while q: all_done = 1 visited[q[0]] = 1 for child in tree[q[0]]: if not visited[child]: all_done = 0 q.appendleft(child) if all_done: for child in tree[q[0]]: if parent[child] == -1: parent[q[0]] = child children[child].append(q[0]) q.popleft() return parent, children # CALCULATING LONGEST PATH FOR ALL THE NODES def all_longest_path_passing_from_node(parent, children, n): q = deque() visited = [len(children[i]) for i in range(n)] downwards = [[0,0] for i in range(n)] upward = [1] * n longest_path = [1] * n for i in range(n): if not visited[i]: q.append(i) downwards[i] = [1,0] while q: node = q.popleft() if parent[node] != -1: visited[parent[node]] -= 1 if not visited[parent[node]]: q.append(parent[node]) else: root = node for child in children[node]: downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse = True)[0:2] s = [node] while s: node = s.pop() if parent[node] != -1: if downwards[parent[node]][0] == downwards[node][0] + 1: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1]) else: upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0]) longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1 for child in children[node]: s.append(child) return longest_path ### TBD SUCCESSOR GRAPH 7.5 ### TBD TREE QUERIES 10.2 da 2 a 4 ### TBD ADVANCED TREE 10.3 ### TBD GRAPHS AND MATRICES 11.3.3 e 11.4.3 e 11.5.3 (ON GAMES) ###################### ## END OF LIBRARIES ## ###################### n = ii() lista = [] for i in range(n): lista.append(si()) def custom_sort(lista): def cmp(x,y): if x+y>y+x: return 1 else: return -1 return sorted(lista, key = cmp_to_key(cmp)) lista = custom_sort(lista) print_list(lista, "") ```
6,238
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Tags: sortings, strings Correct Solution: ``` from functools import cmp_to_key def cmp(a,b): return -1 if a+b < b+a else 0 def main(): n = int(input()) l = [input() for i in range(n)] l = sorted(l,key=cmp_to_key(cmp)) for i in l: print(i,end="") if __name__ == "__main__": main() ```
6,239
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Tags: sortings, strings Correct Solution: ``` from functools import cmp_to_key as ctk def comp(a, b): if a + b < b + a: return -1 elif a + b > b + a: return 1 else: return 0 n = int(input()) string = list() for i in range(n): strtem = input() string.append(strtem) string.sort(key = ctk(comp)) print(''.join(string)) ```
6,240
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Tags: sortings, strings Correct Solution: ``` from functools import cmp_to_key n = int(input()) l = [] for i in range(n): l.append(input()) l.sort(key = cmp_to_key(lambda x,y : 1 if x+y > y+x else -1)) print(''.join(l)) ```
6,241
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Tags: sortings, strings Correct Solution: ``` # List = [[10,1],[20,2],[10,3]] --> Initial # List = [[10, 1], [10, 3], [20, 2]] --> Normal Sort # List = [[10, 3], [10, 1], [20, 2]] --> Sort with custom key [ascending, descending] from functools import cmp_to_key def custom(x,y): a = x +y b = y+ x if(a < b): return -1 elif(b < a): return 1 else: return 0 n = int(input()) arr = [] for i in range(n): s = input() arr.append(s) # arr.sort(key = cmp) arr.sort(key = cmp_to_key(custom)) # print(arr) ans = "" for i in arr: ans += i print(ans) ```
6,242
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Tags: sortings, strings Correct Solution: ``` from bisect import insort,bisect_right,bisect_left from sys import stdout, stdin, setrecursionlimit from heapq import heappush, heappop, heapify from io import BytesIO, IOBase from collections import * from itertools import * from random import * from string import * from queue import * from math import * from re import * from os import * # sqrt,ceil,floor,factorial,gcd,log2,log10,comb ####################################---fast-input-output----######################################### 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 = read(self._fd, max(fstat(self._fd).st_size, 8192)) 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 = read(self._fd, max(fstat(self._fd).st_size, 8192)) 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: 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") stdin, stdout = IOWrapper(stdin), IOWrapper(stdout) graph, mod, szzz = {}, 10**9 + 7, lambda: sorted(zzz()) def getStr(): return input() def getInt(): return int(input()) def listStr(): return list(input()) def getStrs(): return input().split() def isInt(s): return '0' <= s[0] <= '9' def input(): return stdin.readline().strip() def zzz(): return [int(i) for i in input().split()] def output(answer, end='\n'): stdout.write(str(answer) + end) def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2)) def getPrimes(N = 10**5): SN = int(sqrt(N)) sieve = [i for i in range(N+1)] sieve[1] = 0 for i in sieve: if i > SN: break if i == 0: continue for j in range(2*i, N+1, i): sieve[j] = 0 prime = [i for i in range(N+1) if sieve[i] != 0] return prime def primeFactor(n,prime=getPrimes()): lst = [] mx=int(sqrt(n))+1 for i in prime: if i>mx:break while n%i==0: lst.append(i) n//=i if n>1: lst.append(n) return lst dx = [-1, 1, 0, 0, 1, -1, 1, -1] dy = [0, 0, 1, -1, 1, -1, -1, 1] daysInMounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] #################################################---Some Rule For Me To Follow---################################# """ --instants of Reading problem continuously try to understand them. --Try & again try, maybe you're just one statement away! """ ##################################################---START-CODING---############################################### num = getInt() lst=[] for _ in range(num): lst.append(getStr()) def mergeSort(s): if len(s)==1: return s s1 = mergeSort(s[:len(s)//2]) s2 = mergeSort(s[len(s)//2:]) return merge(s1,s2) def merge(s1,s2): lst=[] ind1 = 0 ind2 = 0 while ind1!=len(s1) and ind2 != len(s2): if s1[ind1]+s2[ind2]>s2[ind2]+s1[ind1]: lst.append(s2[ind2]) ind2+=1 else: lst.append(s1[ind1]) ind1+=1 if ind1 != len(s1): lst+=s1[ind1:] else: lst+=s2[ind2:] return lst print(''.join(i for i in mergeSort(lst))) ```
6,243
Provide tags and a correct Python 3 solution for this coding contest problem. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Tags: sortings, strings Correct Solution: ``` def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class K: def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 return K n = int(input()) ls = [input() for _ in range(n)] def compare_str(x, y): if x + y < y + x: return -1 elif x + y > y + x: return 1 else: return 0 ls.sort(key=cmp_to_key(compare_str)) print("".join(ls)) ```
6,244
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Submitted Solution: ``` n = int(input()) a = [] for i in range(n): a.append(input()) from functools import cmp_to_key # a = ['abc', 'abcabb', 'abcabcabb', 'abcabcabbabc'] a_p = sorted(a, key=cmp_to_key(lambda x, y: -1 if x + y < y + x else 1)) print(''.join(a_p)) ``` Yes
6,245
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Submitted Solution: ``` from functools import cmp_to_key n = int(input()) a=[] for i in range(n): a.append(input()) def cmp(x,y): if x+y < y+x : return -1 elif x+y > y+x: return 1 else: return 0 print(''.join(sorted(a,key=cmp_to_key(cmp)))) #print(a.sort(key = lambda x,y: cmp(x,y))) ``` Yes
6,246
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Submitted Solution: ``` # -*- coding: utf-8 -*- """ Created on Thu Apr 14 15:41:54 2016 @author: kebl4230 Too slow. Possibly lots of unnecessary list manipulation. """ from functools import cmp_to_key n = int(input()) strings = list() for i in range(n): strings.append(input()) def cmpfunc(x, y): a = x + y b = y + x if a < b: return -1 elif a == b: return 0 else: return 1 bb = sorted(strings, key=cmp_to_key(cmpfunc)) print("".join(bb)) """ n = int(input()) strings = list() for i in range(n): strings.append(input()) aa = "abcdefghijklmnopqrstuvwxyz" positions = [strings.copy()] def myfunc(mylist, index, pos): scores = [aa.find(bb[index]) if index < len(bb) else 27 for bb in mylist] r = 0 mins = min(scores) while mins <= 27: if r == 0: for i in range(len(scores)): if scores[i] == mins: scores[i] = 100 else: group = [mylist[n] for n in range(len(scores)) if scores[n] == mins] positions.insert(pos + r, group) for string in group: mylist.remove(string) while any(s == mins for s in scores): scores.remove(mins) r += 1 mins = min(scores) index = 0 maxlen = len(positions) pos = 0 while any(len(pos) > 1 for pos in positions): myfunc(positions[pos], index, pos) pos += 1 if pos == maxlen: pos = 0 maxlen = len(positions) index += 1 result = '' for aa in positions: result += aa[0] print(result) """ ``` Yes
6,247
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc 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") 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 Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 from functools import cmp_to_key Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() n = int(ri()) s = [] for i in range(n): s.append(ri()) s.sort(key = cmp_to_key(lambda x,y : -1 if x+y < y+x else 1 )) print("".join(s)) ``` Yes
6,248
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Submitted Solution: ``` n = int(input()) ans = [] for i in range(n): a = input() ans.append(a) ans.sort(reverse = True) ans = ''.join(ans) print(ans) ``` No
6,249
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Submitted Solution: ``` n=int(input()) m=list() for i in range(n): m.append(str(input())) for i in range(n-1): if m[i]+m[i+1]>m[i+1]+m[i]: m[i+1]=m[i+1]+m[i] else: m[i+1]=m[i]+m[i+1] print(m[i+1]) ``` No
6,250
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Submitted Solution: ``` from functools import cmp_to_key def c(x,y): if x+y < y+x: return 1 else: return -1 n = int(input()) l = [] for _ in range(n): l.append(input()) l.sort(key = cmp_to_key(c)) print(''.join(l)) ``` No
6,251
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. Input The first line contains integer n β€” the number of strings (1 ≀ n ≀ 5Β·104). Each of the next n lines contains one string ai (1 ≀ |ai| ≀ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5Β·104. Output Print the only string a β€” the lexicographically smallest string concatenation. Examples Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc Submitted Solution: ``` from functools import cmp_to_key def f(x, y): return -1 if x + y <= y + x else 1 n = int(input()) A = [] for i in range(n): s = input() A.append(s) print(A) print(''.join(sorted(A, key = cmp_to_key(f)))) ``` No
6,252
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified. After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf. The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves β€” from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it. Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: * 1 i j β€” Place a book at position j at shelf i if there is no book at it. * 2 i j β€” Remove the book from position j at shelf i if there is a book at it. * 3 i β€” Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. * 4 k β€” Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position. After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so? Input The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 103, 1 ≀ q ≀ 105) β€” the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order β€” i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0. Output For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order. Examples Input 2 3 3 1 1 1 3 2 4 0 Output 1 4 0 Input 4 2 6 3 2 2 2 2 3 3 3 2 2 2 2 3 2 Output 2 1 3 3 2 4 Input 2 2 2 3 2 2 2 1 Output 2 1 Note <image> This image illustrates the second sample case. Submitted Solution: ``` n, m, q = map(int, input().split()) ans = [0] * q op = [(-1, -1)] cur = [[0 for _ in range(m)] for _ in range(n)] hist, histcnt = [], [] import math, copy sq = int(math.sqrt(q) + 0.5) hist.append(copy.deepcopy(cur)) histcnt.append(0) def apply(mat, cnt, u, v): if u == 1 and mat[v[0] - 1][v[1] - 1] == 0: mat[v[0] - 1][v[1] - 1] = 1 cnt += 1 elif u == 2 and mat[v[0] - 1][v[1] - 1] == 1: mat[v[0] - 1][v[1] - 1] = 0 cnt -= 1 else: for j in range(m): if mat[v[0] - 1][j] == 0: mat[v[0] - 1][j] = 1 cnt += 1 else: mat[v[0] - 1][j] = 0 cnt -= 1 return cnt def run(mat, cnt, f, t): if f > t: return cnt for i in range(f, t + 1): #print(mat, cnt, f, t, op[i]) if op[i][0] < 4: cnt = apply(mat, cnt, op[i][0], op[i][1]) else: k = (op[i][1][0] // sq) * sq mat, cnt = copy.deepcopy(hist[k]), histcnt[k] cnt = run(mat, cnt, k + 1, op[i][1][0]) return cnt for i in range(q): u, *v = map(int, input().split()) op.append((u, v)) if u < 4: ans[i] = apply(cur, ans[i - 1], u, v) else: k = (v[0] // sq) * sq ans[i] = run(copy.deepcopy(hist[k]), histcnt[k], k + 1, v[0]) if i % sq == 0: hist.append(copy.deepcopy(cur)) histcnt.append(ans[i]) print("\n".join(map(str, ans))) ``` No
6,253
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified. After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf. The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves β€” from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it. Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: * 1 i j β€” Place a book at position j at shelf i if there is no book at it. * 2 i j β€” Remove the book from position j at shelf i if there is a book at it. * 3 i β€” Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. * 4 k β€” Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position. After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so? Input The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 103, 1 ≀ q ≀ 105) β€” the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order β€” i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0. Output For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order. Examples Input 2 3 3 1 1 1 3 2 4 0 Output 1 4 0 Input 4 2 6 3 2 2 2 2 3 3 3 2 2 2 2 3 2 Output 2 1 3 3 2 4 Input 2 2 2 3 2 2 2 1 Output 2 1 Note <image> This image illustrates the second sample case. Submitted Solution: ``` A = list(map(int,input().split())) C = [0 for k in range(A[0])] G = [0] for i in range(A[2]): B = list(map(int,input().split())) if B[0] == 1: C[B[1]-1] += 1 G.append(G[-1]+1) elif B[0] == 2: C[B[1]-1] -= 1 G.append(G[-1]-1) elif B[0] == 3: x = C[B[1]-1] C[B[1]-1] = A[1]-C[B[1]-1] G.append(G[-1]-x+(C[B[1]-1])) else: G.append(G[B[1]]) print(G[-1]) ``` No
6,254
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified. After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf. The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves β€” from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it. Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: * 1 i j β€” Place a book at position j at shelf i if there is no book at it. * 2 i j β€” Remove the book from position j at shelf i if there is a book at it. * 3 i β€” Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. * 4 k β€” Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position. After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so? Input The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 103, 1 ≀ q ≀ 105) β€” the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order β€” i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0. Output For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order. Examples Input 2 3 3 1 1 1 3 2 4 0 Output 1 4 0 Input 4 2 6 3 2 2 2 2 3 3 3 2 2 2 2 3 2 Output 2 1 3 3 2 4 Input 2 2 2 3 2 2 2 1 Output 2 1 Note <image> This image illustrates the second sample case. Submitted Solution: ``` def bsch(a, x): n = len(a) l, r = -1, n-1 while (r-l >= 2): mid = (r+l) // 2 if a[mid] <= x: l = mid else: r = mid return r if __name__ == '__main__': n, m, q = map(int, input().split()) mask1 = [] for i in range(m): mask1.append(1 << i) invert = sum(mask1) mask2 = [] for i in range(m): mask2.append(invert-mask1[i]) state = [[0] for _ in range(n)] sumstate = [[0] for _ in range(n)] curr = [0 for _ in range(n)] currsum = [0 for _ in range(n)] currtot = 0 change = [[0] for _ in range(n)] for st in range(1,q+1): s = input().split() if s[0] == '1': i, j = map(lambda x:int(x)-1, s[1:]) if curr[i] & mask1[j] == 0: state[i].append(curr[i]) sumstate[i].append(currsum[i]) change[i].append(st) curr[i] |= mask1[j] currsum[i] += 1 currtot += 1 elif s[0] == '2': i, j = map(lambda x:int(x)-1, s[1:]) if curr[i] & mask1[j] != 0: state[i].append(curr[i]) sumstate[i].append(currsum[i]) change[i].append(st) curr[i] &= mask2[j] currsum[i] -= 1 currtot -= 1 elif s[0] == '3': i = int(s[1])-1 state[i].append(curr[i]) sumstate[i].append(currsum[i]) change[i].append(st) curr[i] ^= invert currtot += m - 2 * currsum[i] currsum[i] = m - currsum[i] else: k = int(s[1]) for i in range(n): if change[i][-1] <= k: continue t = bsch(change[i], k) if state[i][t] != curr[i]: state[i].append(state[i][t]) sumstate[i].append(currsum[i]) change[i].append(st) curr[i] = state[i][t] currtot += sumstate[i][t] - currsum[i] currsum[i] = sumstate[i][t] print(currtot) ``` No
6,255
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified. After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf. The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves β€” from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it. Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: * 1 i j β€” Place a book at position j at shelf i if there is no book at it. * 2 i j β€” Remove the book from position j at shelf i if there is a book at it. * 3 i β€” Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. * 4 k β€” Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position. After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so? Input The first line of the input contains three integers n, m and q (1 ≀ n, m ≀ 103, 1 ≀ q ≀ 105) β€” the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order β€” i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0. Output For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order. Examples Input 2 3 3 1 1 1 3 2 4 0 Output 1 4 0 Input 4 2 6 3 2 2 2 2 3 3 3 2 2 2 2 3 2 Output 2 1 3 3 2 4 Input 2 2 2 3 2 2 2 1 Output 2 1 Note <image> This image illustrates the second sample case. Submitted Solution: ``` n, m, q = map(int, input().split()) ans = [0] * q op = [] cur = [[0 for _ in range(m)] for _ in range(n)] hist, histcnt = [], [] import math, copy sq = int(math.sqrt(q) + 0.5) hist.append(copy.deepcopy(cur)) histcnt.append(0) def apply(mat, cnt, u, v): if u == 1 and mat[v[0] - 1][v[1] - 1] == 0: mat[v[0] - 1][v[1] - 1] = 1 cnt += 1 elif u == 2 and mat[v[0] - 1][v[1] - 1] == 1: mat[v[0] - 1][v[1] - 1] = 0 cnt -= 1 else: for j in range(m): if mat[v[0] - 1][j] == 0: mat[v[0] - 1][j] = 1 cnt += 1 else: mat[v[0] - 1][j] = 0 cnt -= 1 return cnt def run(mat, cnt, f, t): if f > t: return cnt for i in range(f, t + 1): if op[i][0] < 4: cnt = apply(mat, cnt, op[i][0], op[i][1]) else: k = (op[i][1][0] // sq) * sq mat, cnt = hist[k], histcnt[k] cnt = run(mat, cnt, k + 1, op[i][1][0]) return cnt for i in range(q): u, *v = map(int, input().split()) op.append((u, v)) if u < 4: ans[i] = apply(cur, ans[i - 1], u, v) else: k = (v[0] // sq) * sq ans[i] = run(hist[k], histcnt[k], k + 1, v[0]) if i % sq == 0: hist.append(copy.deepcopy(cur)) histcnt.append(ans[i]) print("\n".join(map(str, ans))) ``` No
6,256
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Tags: geometry, implementation Correct Solution: ``` n = int(input()) coord = 0 for i in range(n): ai, bi = input().split() ai = int(ai) if (coord == 0 and bi != 'South'): print("NO") break if (coord == 20000 and bi != 'North'): print("NO") break if (bi == 'North'): coord -= ai if (coord < 0): print("NO") break elif (bi == 'South'): coord += ai if (coord > 20000): print("NO") break else: if (coord != 0): print("NO") else: print("YES") ```
6,257
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Tags: geometry, implementation Correct Solution: ``` from math import sin def mp(): return map(int,input().split()) def lt(): return list(map(int,input().split())) def pt(x): print(x) def ip(): return input() def it(): return int(input()) def sl(x): return [t for t in x] def spl(x): return x.split() def aj(liste, item): liste.append(item) def bin(x): return "{0:b}".format(x) def listring(l): return ' '.join([str(x) for x in l]) def ptlist(l): print(' '.join([str(x) for x in l])) n = it() s = 10000 r = 0 deg = 0 bl = True for _ in range(n): a,b = input().split() c = int(a) if s == 10000 and b != "South": bl = False elif s == -10000 and b != "North": bl = False else: if b == "North": if s + c > 10000: bl = False else: s += c if b == "South": if s - c < -10000: bl = False else: s -= c if bl: if s == 10000: pt("YES") else: pt("NO") else: pt("NO") ```
6,258
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Tags: geometry, implementation Correct Solution: ``` import math as mt import sys,string,bisect input=sys.stdin.readline from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) def dist(x,y,c,d): return mt.sqrt((x-c)**2+(y-d)**2) def circle(x1, y1, x2,y2, r1, r2): distSq = (((x1 - x2)* (x1 - x2))+ ((y1 - y2)* (y1 - y2)))**(.5) if (distSq + r2 <= r1): return True else: return False n=I() x=0 d=0 for i in range(n): dis,dire=input().split() dis=int(dis) if(dire[0]=='S'): x+=dis if(dire[0]=="N"): x-=dis if(x==0 or x==20000): if(dire[0]=='E' or dire[0]=='W'): print("NO") d=1 break if(x<0): print("NO") d=1 break if(x>20000): print("NO") d=1 break if(x==0 and d==0): print("YES") elif(d==0): print("NO") ```
6,259
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Tags: geometry, implementation Correct Solution: ``` n=int(input()) b=0 currentPos=0 for i in range(n): k,dir=input().split() k=int(k) if currentPos==0 and dir!='South': b=1 elif currentPos==20000 and dir!='North': b=1 elif dir=='North' and currentPos-k<0: b=1 elif dir=='South' and currentPos+k>20000: b=1 else: if dir=='North': currentPos-=k elif dir=='South': currentPos+=k #print(currentPos) if currentPos!=0: b=1 if b==0: print('YES') else: print('NO') ```
6,260
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Tags: geometry, implementation Correct Solution: ``` from sys import * from math import * n=int(stdin.readline()) m=[] for i in range(n): a = list(stdin.readline().split()) m.append(a) x=0 f=0 for i in range(n): if x==0 and m[i][1]!="South": f=1 break if x==20000 and m[i][1]!="North": f=1 break if m[i][1]=="South": x+=int(m[i][0]) if x>20000: f=1 break if m[i][1]=="North": x-=int(m[i][0]) if x<0: f=1 break if x!=0 or f==1: print("NO") else: print("YES") ```
6,261
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Tags: geometry, implementation Correct Solution: ``` n=int(input()) w=0 e=0 y=0 r=0 for i in range(n): d,v=input().split(" ") d=int(d) if v=='North': y-=d elif v=='South': y+=d elif (v=='West' or v=='East') and (y==0 or y==20000): r=-1 if y<0 or y>20000: r=-1 if r==0 and y==0: print("YES") else: print("NO") ```
6,262
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Tags: geometry, implementation Correct Solution: ``` n = int(input()) y = 0 maxlen = 20000 for i in range(n): raw = input().split() cur = int(raw[0]) dir = raw[1] if y == 0 and dir != 'South': print('NO') quit() if y == maxlen and dir != 'North': print('NO') quit() if (dir == 'South'): y += cur elif (dir == 'North'): y -= cur if (y < 0 or y > maxlen): print('NO') quit() if y == 0: print('YES') else: print('NO') ```
6,263
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Tags: geometry, implementation Correct Solution: ``` n = int(input()) ans = 'YES' p = 0 for _ in range(n): t, d = input().split() if d == 'South': p += int(t) if p > 20000: ans = 'NO' break elif d == 'North': p -= int(t) if p < 0: ans = 'NO' break else: if abs(p) % 20000 == 0: ans = 'NO' break if p != 0: ans = 'NO' print(ans) ```
6,264
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Submitted Solution: ``` n = int(input()) p = 10000 for i in range(n): x, d = input().split() x = int(x) if d == 'South': if p != -10000 and p - x >= -10000: p -= x else: print('NO') exit() elif d == 'North': if p != 10000 and p + x <= 10000: p += x else: print('NO') exit() else: if p == 10000 or p == -10000: print('NO') exit() if p == 10000: print('YES') else: print('NO') ``` Yes
6,265
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Submitted Solution: ``` n = int(input()) l = [] for i in range(n): a , b = map(str, input().split()) a = int(a) c = [a, b] l.append(c) milles = 0 for i in range(n): dist = l[i][0] direcc = l[i][1] if direcc == "South": milles = milles + dist elif direcc == "North": milles = milles - dist elif (direcc == "West" or direcc == "East") and (milles == 0 or milles == 20000): print("NO") exit(0) if milles < 0 or milles > 2 * 10**4: print("NO") exit(0) if milles != 0: print("NO") else: print("YES") ``` Yes
6,266
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Submitted Solution: ``` import sys n=int(input()) y=0 for i in range(n): t,d=input().split() t=int(t) if y<0 or y>20000: print('NO') exit() if d[0]=='N': y-=t elif d[0]=='S': y+=t elif y==0 or y==20000: print('NO') exit() print('YES' if y==0 else 'NO') ``` Yes
6,267
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Submitted Solution: ``` n = int(input()) def solve(n): pos = 0 for i in range(n): km, direc = input().split() km = int(km) if pos == 0 and direc != "South": print("NO") return elif pos == 20000 and direc != "North": print("NO") return elif direc == "South": pos += km if pos > 20000: print("NO") return elif direc == "North": pos -= km if pos < 0: print("NO") return if pos == 0: print("YES") else: print("NO") solve(n) ``` Yes
6,268
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Submitted Solution: ``` total = 0 for _ in range(int(input().strip())): dist, direction = input().strip().split() dist = int(dist) if dist%20000 == 0 and dist != 20000: dist = 0 else: dist = 20000-dist%20000 if dist > 20000 else dist if total == 0: if direction[0] != 'S': print('NO') quit() if total == 20000: if direction[0] != 'N': print('NO') quit() if direction[0] == 'S': total += dist if direction[0] == 'N': total -= dist print(['YES', 'NO'][total!=0]) ``` No
6,269
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Submitted Solution: ``` #!/usr/bin/env python3 n = int(input()) cury = 0 for i in range(n): k, d = input().split() k = int(k) if cury == 0 and d != "South": print("NO") exit() if cury == 20000 and d != "North": print("NO") exit() if d == "East" or d == "West": continue if d == "North": k = k%40000 cury -= k if cury < 0: cury += 40000 cury = cury % 40000 if cury >= 20000: cury = 40000 - cury if d == "South": k = k%40000 cury += k cury = cury % 40000 if cury >= 20000: cury = 40000 - cury if cury%40000 != 0: print("NO") else: print("YES") ``` No
6,270
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Submitted Solution: ``` n=int(input().strip()) det=20000 for _ in range(n): dis,dir=input().strip().split() dis=int(dis)%40000 if 20000<dis: dis-=40000 if det==20000 and dir!='North': det-=dis elif det==0 and dir!='South': det+=dis elif dir=='South' and det!=0: det-=dis elif dir=='North' and det!=20000: det+=dis if det>20000: det=40000-det if det<0: det=-det print('YES' if det==20000 else 'NO') ``` No
6,271
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East". Limak isn’t sure whether the description is valid. You must help him to check the following conditions: * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South. * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North. * The journey must end on the North Pole. Check if the above conditions are satisfied and print "YES" or "NO" on a single line. Input The first line of the input contains a single integer n (1 ≀ n ≀ 50). The i-th of next n lines contains an integer ti and a string diri (1 ≀ ti ≀ 106, <image>) β€” the length and the direction of the i-th part of the journey, according to the description Limak got. Output Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes. Examples Input 5 7500 South 10000 East 3500 North 4444 West 4000 North Output YES Input 2 15000 South 4000 East Output NO Input 5 20000 South 1000 North 1000000 West 9000 North 10000 North Output YES Input 3 20000 South 10 East 20000 North Output NO Input 2 1000 North 1000 South Output NO Input 4 50 South 50 North 15000 South 15000 North Output YES Note Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole. <image> Submitted Solution: ``` Q=int(input()) X=0 for _ in range(Q): A=input().strip().split(' ') D=int(A[0]) if X==0: if A[1][0]!='S': print('NO') break else: X+=D X%=40000 if X>20000: X=40000-X elif X==20000: if A[1][0]!='N': print('NO') break else: X-=D X%=40000 if X>20000: X=40000-X else: if A[1][0]=='S': X+=D X%=40000 if X>20000: X=40000-X elif A[1][0]=='N': X-=D X%=40000 if X>20000: X=40000-X else: if X%40000==0: print('YES') else: print('NO') ``` No
6,272
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Mike has discovered a new way to encode permutations. If he has a permutation P = [p1, p2, ..., pn], he will encode it in the following way: Denote by A = [a1, a2, ..., an] a sequence of length n which will represent the code of the permutation. For each i from 1 to n sequentially, he will choose the smallest unmarked j (1 ≀ j ≀ n) such that pi < pj and will assign to ai the number j (in other words he performs ai = j) and will mark j. If there is no such j, he'll assign to ai the number - 1 (he performs ai = - 1). Mike forgot his original permutation but he remembers its code. Your task is simple: find any permutation such that its code is the same as the code of Mike's original permutation. You may assume that there will always be at least one valid permutation. Input The first line contains single integer n (1 ≀ n ≀ 500 000) β€” length of permutation. The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ n or ai = - 1) β€” the code of Mike's permutation. You may assume that all positive values from A are different. Output In first and only line print n numbers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” a permutation P which has the same code as the given one. Note that numbers in permutation are distinct. Examples Input 6 2 -1 1 5 -1 4 Output 2 6 1 4 5 3 Input 8 2 -1 4 -1 6 -1 8 -1 Output 1 8 2 7 3 6 4 5 Note For the permutation from the first example: i = 1, the smallest j is 2 because p2 = 6 > p1 = 2. i = 2, there is no j because p2 = 6 is the greatest element in the permutation. i = 3, the smallest j is 1 because p1 = 2 > p3 = 1. i = 4, the smallest j is 5 (2 was already marked) because p5 = 5 > p4 = 4. i = 5, there is no j because 2 is already marked. i = 6, the smallest j is 4 because p4 = 4 > p6 = 3. Submitted Solution: ``` n = int(input()) p = list(map(int, input().split(' '))) p = [None] + p p = [(p[i], i) for i in range(len(p))] maxx = n ans = [0]*len(p) todel = [] for i in range(1, n+1): if p[i][0] == -1: ans[i] = maxx maxx -= 1 todel.insert(0, i) for i in todel: del p[i] p = p[1:] p = sorted(p) maxx = 1 for x, i in p: ans[i] = maxx maxx += 1 ans = ans[1:] print((" ").join(list(map(str, ans)))) ``` No
6,273
Provide tags and a correct Python 3 solution for this coding contest problem. Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This time Alice wants to form four melodies for her tracks. Alice has a sheet with n notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Input The first line contains one integer number n (4 ≀ n ≀ 3000). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” notes written on a sheet. Output Print maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Examples Input 5 1 3 5 7 9 Output 4 Input 5 1 3 5 7 2 Output 5 Note In the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note). In the second example it is possible to compose one melody with 2 notes β€” {1, 2}. Remaining notes are used in other three melodies (one note per each melody). Tags: flows, graphs Correct Solution: ``` import sys def solve(): n = int(sys.stdin.readline()) a = [0] + [int(i) for i in sys.stdin.readline().split()] dp = [[0]*(n + 1) for i in range(n + 1)] ans = 0 maxnum = [0] * (10**5 + 2) maxmod = [0] * 7 for y in range(n + 1): maxmod = [0] * 7 for ai in a: maxnum[ai] = 0 for i in range(y): maxmod[a[i] % 7] = max(maxmod[a[i] % 7], dp[i][y]) maxnum[a[i]] = max(maxnum[a[i]], dp[i][y]) for x in range(y + 1, n + 1): dp[x][y] = max(maxmod[a[x] % 7], maxnum[a[x] + 1], maxnum[a[x] - 1], dp[0][y]) + 1 dp[y][x] = dp[x][y] maxmod[a[x] % 7] = max(maxmod[a[x] % 7], dp[x][y]) maxnum[a[x]] = max(maxnum[a[x]], dp[x][y]) ans = max(ans, dp[x][y]) print(ans) if __name__ == '__main__': solve() ```
6,274
Provide tags and a correct Python 3 solution for this coding contest problem. Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This time Alice wants to form four melodies for her tracks. Alice has a sheet with n notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Input The first line contains one integer number n (4 ≀ n ≀ 3000). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” notes written on a sheet. Output Print maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Examples Input 5 1 3 5 7 9 Output 4 Input 5 1 3 5 7 2 Output 5 Note In the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note). In the second example it is possible to compose one melody with 2 notes β€” {1, 2}. Remaining notes are used in other three melodies (one note per each melody). Tags: flows, graphs Correct Solution: ``` import sys n = int(sys.stdin.readline()) a = [0] + [int(i) for i in sys.stdin.readline().split()] dp = [[0]*(n + 1) for i in range(n + 1)] ans = 0 maxnum = [0] * (10**5 + 2) maxmod = [0] * 7 for y in range(n + 1): maxmod = [0] * 7 for ai in a: maxnum[ai] = 0 for i in range(y): maxmod[a[i] % 7] = max(maxmod[a[i] % 7], dp[i][y]) maxnum[a[i]] = max(maxnum[a[i]], dp[i][y]) for x in range(y + 1, n + 1): dp[x][y] = max(maxmod[a[x] % 7], maxnum[a[x] + 1], maxnum[a[x] - 1], dp[0][y]) + 1 dp[y][x] = dp[x][y] maxmod[a[x] % 7] = max(maxmod[a[x] % 7], dp[x][y]) maxnum[a[x]] = max(maxnum[a[x]], dp[x][y]) ans = max(ans, dp[x][y]) print(ans) ```
6,275
Provide tags and a correct Python 3 solution for this coding contest problem. Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This time Alice wants to form four melodies for her tracks. Alice has a sheet with n notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Input The first line contains one integer number n (4 ≀ n ≀ 3000). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” notes written on a sheet. Output Print maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Examples Input 5 1 3 5 7 9 Output 4 Input 5 1 3 5 7 2 Output 5 Note In the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note). In the second example it is possible to compose one melody with 2 notes β€” {1, 2}. Remaining notes are used in other three melodies (one note per each melody). Tags: flows, graphs Correct Solution: ``` import sys n = int(input()) + 1 a = [0] + list(map(int, input().split())) mod7 = [x % 7 for x in a] dp = [[0]*n for _ in range(n)] maxnum = [0]*(10**5+10) ans = 0 for i in range(n): maxmod = [0]*7 for j in range(n): maxnum[a[j]] = 0 for j in range(i): maxnum[a[j]] = max(maxnum[a[j]], dp[j][i]) maxmod[mod7[j]] = max(maxmod[mod7[j]], dp[j][i]) for j in range(i+1, n): dp[i][j] = max( maxnum[a[j]-1], maxnum[a[j]+1], maxmod[mod7[j]], dp[0][i] ) + 1 maxnum[a[j]] = max(maxnum[a[j]], dp[i][j]) maxmod[mod7[j]] = max(maxmod[mod7[j]], dp[i][j]) ans = max(ans, dp[i][j]) print(ans) ```
6,276
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This time Alice wants to form four melodies for her tracks. Alice has a sheet with n notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Input The first line contains one integer number n (4 ≀ n ≀ 3000). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” notes written on a sheet. Output Print maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Examples Input 5 1 3 5 7 9 Output 4 Input 5 1 3 5 7 2 Output 5 Note In the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note). In the second example it is possible to compose one melody with 2 notes β€” {1, 2}. Remaining notes are used in other three melodies (one note per each melody). Submitted Solution: ``` import sys n = int(input()) + 1 a = [0] + list(map(int, input().split())) mod7 = [x % 7 for x in a] inf = 10**9 next_i = [[[inf]*3 for _ in range(n+1)] for _ in range(n+1)] for j in range(n-1, -1, -1): next_i[0][j] = [j]*3 for i in range(1, n): next_i[i][j][0] = j if a[i]-1 == a[j] else next_i[i][j+1][0] next_i[i][j][1] = j if a[i]+1 == a[j] else next_i[i][j+1][1] next_i[i][j][2] = j if mod7[i] == mod7[j] else next_i[i][j+1][2] dp = [[1]+[2]*n for _ in range(n)] dp[0] = [0] + [1]*n for j in range(1, n): for i in range(j): for k in range(3): if next_i[i][j+1][k] != inf: dp[j][next_i[i][j+1][k]] = max(dp[j][next_i[i][j+1][k]], dp[i][j]+1) if next_i[j][j+1][k] != inf: dp[i][next_i[j][j+1][k]] = max(dp[i][next_i[j][j+1][k]], dp[i][j]+1) dp[i][j+1] = max(dp[i][j+1], dp[i][j]) dp[j][j+1] = max(dp[j][j+1], dp[i][j]) print(max(max(row[1:]) for row in dp[1:])) ``` No
6,277
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This time Alice wants to form four melodies for her tracks. Alice has a sheet with n notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Input The first line contains one integer number n (4 ≀ n ≀ 3000). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” notes written on a sheet. Output Print maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Examples Input 5 1 3 5 7 9 Output 4 Input 5 1 3 5 7 2 Output 5 Note In the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note). In the second example it is possible to compose one melody with 2 notes β€” {1, 2}. Remaining notes are used in other three melodies (one note per each melody). Submitted Solution: ``` import sys n = int(input()) + 1 a = [0] + list(map(int, input().split())) mod7 = [x % 7 for x in a] inf = 10**9 next_i = [[[inf]*3 for _ in range(n+1)] for _ in range(n+1)] for j in range(n-1, -1, -1): next_i[0][j] = [j]*3 for i in range(1, n): next_i[i][j][0] = j if a[i]-1 == a[j] else next_i[i][j+1][0] next_i[i][j][1] = j if a[i]+1 == a[j] else next_i[i][j+1][1] next_i[i][j][2] = j if mod7[i] == mod7[j] else next_i[i][j+1][2] dp = [[0]*n for _ in range(n)] i0_max = 0 for j in range(1, n-1): dp[0][j] = max(dp[0][j], 1) i0_max = max(i0_max, dp[0][j]) for k in range(3): if next_i[j][j+1][k] != inf: dp[0][next_i[j][j+1][k]] = max( dp[0][next_i[j][j+1][k]], dp[0][j]+1 ) for k in range(j+1, n): dp[j][k] = max(dp[j][k], i0_max+1) for i in range(1, n): for j in range(i+1, n): for k in range(3): if next_i[i][j+1][k] != inf: dp[j][next_i[i][j+1][k]] = max( dp[j][next_i[i][j+1][k]], dp[i][j]+1 ) if next_i[j][j+1][k] != inf: dp[i][next_i[j][j+1][k]] = max( dp[i][next_i[j][j+1][k]], dp[i][j]+1 ) print(max(max(row[1:]) for row in dp[1:])) ``` No
6,278
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This time Alice wants to form four melodies for her tracks. Alice has a sheet with n notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Input The first line contains one integer number n (4 ≀ n ≀ 3000). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” notes written on a sheet. Output Print maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Examples Input 5 1 3 5 7 9 Output 4 Input 5 1 3 5 7 2 Output 5 Note In the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note). In the second example it is possible to compose one melody with 2 notes β€” {1, 2}. Remaining notes are used in other three melodies (one note per each melody). Submitted Solution: ``` import sys n = int(input()) a = list(map(int, input().split())) mod7 = [x % 7 for x in a] inf = 10**9 next_i = [[inf]*3 for _ in range(n)] for i in range(n): for j in range(i+1, n): if a[i]-1 == a[j]: next_i[i][0] = min(next_i[i][0], j) if a[i]+1 == a[j]: next_i[i][1] = min(next_i[i][1], j) if mod7[i] == mod7[j]: next_i[i][2] = min(next_i[i][2], j) dp = [[2]*n for _ in range(n)] for j in range(1, n): for i in range(j): for k in range(3): if j < next_i[i][k] < inf: dp[j][next_i[i][k]] = max(dp[j][next_i[i][k]], dp[i][j]+1) if j < next_i[j][k] < inf: dp[i][next_i[j][k]] = max(dp[i][next_i[j][k]], dp[i][j]+1) print(max(max(row) for row in dp)) ``` No
6,279
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult! Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This time Alice wants to form four melodies for her tracks. Alice has a sheet with n notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7. You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Input The first line contains one integer number n (4 ≀ n ≀ 3000). The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” notes written on a sheet. Output Print maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody. Examples Input 5 1 3 5 7 9 Output 4 Input 5 1 3 5 7 2 Output 5 Note In the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note). In the second example it is possible to compose one melody with 2 notes β€” {1, 2}. Remaining notes are used in other three melodies (one note per each melody). Submitted Solution: ``` import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split())) def inps(): return sys.stdin.readline() def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x]) def err(x): print(x); exit() n = inp() a = inpl() g = [[] for _ in range(n)] ny = [0]*n for i in range(n): for j in range(i+1,n): if abs(a[i]-a[j]) == 1 or a[i]%7 == a[j]%7: g[i].append(j) ny[j] += 1 q = deque([]) su = [1]*n seen = [0]*n for i,x in enumerate(ny): if x == 0: q.append(i) seen[i] = 1 while q: u = q.popleft() for v in g[u]: if seen[v]: continue su[v] = max(su[v], su[u]+1) ny[v] -= 1 if ny[v] == 0: seen[v] = 1 q.append(v) su.sort(reverse=True) print(su[0]+su[1]) ``` No
6,280
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) a = sorted(zip(map(int, input().split()), range(n))) s = [] for i in range(n): if a[i]: s.append([]) while a[i]: s[-1].append(i + 1) a[i], i = None, a[i][1] print(len(s)) for l in s: print(len(l), *l) ```
6,281
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) a=list(map(int,input().split())) a = sorted([(a[i],i) for i in range(n)]) p =[] c = [False]*n for i in range(n): if not c[i]: k=i b=[] while not c[k]: c[k]=True b.append(str(k+1)) k = a[k][1] p.append(b) print(len(p)) for i in p: print(str(len(i))+" "+" ".join(i)) ```
6,282
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) a = sorted((a[i], i) for i in range(n)) s = [] for i in range(n): if a[i]: l = [] s.append(l) while a[i]: l.append(i + 1) a[i], i = None, a[i][1] print(len(s)) for l in s: print(len(l), *l) ```
6,283
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) s = list(map(int, input().split())) s1 = sorted(s) d = {s1[i] : i for i in range(n)} ans = [] for i in range(n): if d[s[i]] > -1: curans = [i + 1] cur = i place = d[s[cur]] while place != i: curans.append(place + 1) d[s[cur]] = -1 cur = place place = d[s[cur]] d[s[cur]] = -1 ans.append(curans) print(len(ans)) for a in ans: print(len(a), end=' ') print(*a) ```
6,284
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) a = [int(x) for x in input().split()] a = list(enumerate(a)) a = sorted(a, key=lambda x: x[1]) a = [(i, x, j) for j, (i, x) in enumerate(a)] a = sorted(a, key=lambda x: x[0]) count_cycles = 0 cycle = [-1] * n i = 0 while True: while i < n and cycle[i] >= 0: i += 1 if i == n: break k = i cycle[i] = count_cycles while a[k][2] != i: k = a[k][2] cycle[k] = count_cycles count_cycles += 1 print(count_cycles) cycles = [[] for i in range(count_cycles)] for i in range(n): cycles[cycle[i]].append(i + 1) for i in range(count_cycles): print(str(len(cycles[i])) + ' ' + ' '.join([str(x) for x in cycles[i]])) ```
6,285
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) ind = sorted(range(n), key=lambda i: a[i]) visited = [False] * n s = [] for i in range(n): if not visited[i]: s.append([i + 1]) l = s[-1] j = ind[i] while j != i: visited[j] = True l.append(j + 1) j = ind[j] print(len(s)) for l in s: print(len(l), *l) ```
6,286
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) sa = sorted(a) sg = {} for i in range(n): sg[sa[i]] = i vis = set() ans = [] for i in range(n): if i in vis: continue vis.add(i) c = [i+1] v = i while 1: nv = sg[a[v]] if nv not in vis: vis.add(nv) c.append(nv+1) v = nv else: break ans.append(c) print(len(ans)) for c in ans: print(len(c), ' '.join([str(e) for e in c])) ```
6,287
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Tags: dfs and similar, dsu, implementation, math, sortings Correct Solution: ``` n = int(input()) lis = list(map(int,input().split())) a = sorted(lis)[:] d={} for i in range(n): d[a[i]]=i #print(d) vis=[0]*(n) ans=[] for i in range(n): tmp=[] if vis[i]==0: j=i while vis[j]==0: vis[j]=1 tmp.append(j+1) j=d[lis[j]] ans.append([len(tmp)]+tmp) print(len(ans)) for i in ans: print(*i) ```
6,288
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` n = int(input()) a = sorted(zip(map(int, input().split()), range(n))) s = [] for i in range(n): if a[i]: l = [] s.append(l) while a[i]: l.append(i + 1) a[i], i = None, a[i][1] print(len(s)) for l in s: print(len(l), *l) ``` Yes
6,289
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` from __future__ import print_function import sys sys.setrecursionlimit(100005) n = int(input()) a = list(map(int, input().split())) b = sorted(a) pos = {} for i in range(n): pos[b[i]] = i g = [[] for _ in range(n)] used = [False for _ in range(n)] for i in range(n): g[i] += [pos[a[i]]] b = [] for i in range(n): if used[i] == False: w = [] q = [i] while q: v = q[-1] q.pop() w.append(v) used[v] = True for to in g[v]: if used[to] == False: q += [to] b.append(list(w)) print(len(b)) for i in range(len(b)): b[i] = [x + 1 for x in b[i]] print(len(b[i]), *b[i], sep=' ') ``` Yes
6,290
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` # -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random import itertools """ created by shhuan at 2017/10/20 10:12 """ N = int(input()) A = [int(x) for x in input().split()] B = [x for x in A] B.sort() ind = {v: i for i,v in enumerate(B)} order = [ind[A[i]] for i in range(N)] done = [0] * N ans = [] for i in range(N): if not done[i]: g = [] cur = i while not done[cur]: g.append(cur) done[cur] = 1 cur = order[cur] ans.append([len(g)] + [j+1 for j in g]) print(len(ans)) for row in ans: print(' '.join(map(str, row))) ``` Yes
6,291
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) a = sorted(range(n), key=lambda i: a[i]) s = [] for i in range(n): if a[i] + 1: l = [] s.append(l) while a[i] + 1: l.append(i + 1) a[i], i = -1, a[i] print(len(s)) for l in s: print(len(l), *l) ``` Yes
6,292
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` n=int(input()) anss=0 a=list(map(int,input().split())) b=[] for i in range(n): b.append([i,a[i],0]) b=sorted(b,key = lambda a : a[1]) for i in range(n): b[i].append(i) b=sorted(b,key = lambda a : a[0]) c=[] d=[] for i in range(n): if b[i][2]!=1: j=i c.append([]) d.append(0) while b[j][2]!=1: c[anss].append(b[j][0]) d[anss]=d[anss]+1 b[j][2]=b[j][2]+1 j=b[j][3] anss=anss+1 print(anss) for i in range(anss): print(d[i],end=" ") for j in c[i]: print(j,end=" ") print() ``` No
6,293
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` # -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random import itertools """ created by shhuan at 2017/10/20 10:12 """ N = int(input()) A = [int(x) for x in input().split()] B = [x for x in A] B.sort() ans = [] vis = [0]*N def merge_sort(l, r): if r > l+1: m = (l+r)//2 merge_sort(l, m) merge_sort(m, r) # merge A[l:r] = sorted(A[l:r]) if A[l:r] == B[l:r]: ids = [i+1 for i in range(l, r) if not vis[i]] if ids: for i in ids: vis[i-1] = 1 ans.append([len(ids)]+ids) merge_sort(0, N) print(len(ans)) if ans: for row in ans: print(' '.join(map(str, row))) ``` No
6,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 sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` n = int(input()) d = list(map(int, input().split())) temp = d[:] d.sort() from bisect import bisect_left A = [bisect_left(d,i) for i in temp] del d,temp f = [False]*len(A) for i in range(n): if not f[i]: L = [i+1] f[i] = True j = A[i] while j != i: L.append(j+1) f[j] = True j = A[j] print(len(L),' '.join(map(str,L))) ``` No
6,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 sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order. Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places. Every element of the sequence must appear in exactly one subsequence. Input The first line of input data contains integer n (1 ≀ n ≀ 105) β€” the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. Output In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≀ n), then ci integers l1, l2, ..., lci (1 ≀ lj ≀ n) β€” indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. Examples Input 6 3 2 1 6 5 4 Output 4 2 1 3 1 2 2 4 6 1 5 Input 6 83 -75 -49 11 37 62 Output 1 6 1 2 3 4 5 6 Note In the first sample output: After sorting the first subsequence we will get sequence 1 2 3 6 5 4. Sorting the second subsequence changes nothing. After sorting the third subsequence we will get sequence 1 2 3 4 5 6. Sorting the last subsequence changes nothing. Submitted Solution: ``` n = int(input()) m = list(map(int, input().split())) d = {} for i, k in enumerate(sorted(m)): d[k] = i r = set() ans = [] for k in m: if k not in r: r.add(k) ans.append({k,}) j = k while m[d[j]] != k: r.add(m[d[j]]) ans[-1].add(m[d[j]]) j = m[d[j]] print(len(ans)) for s in ans: print(len(s), *s) ``` No
6,296
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y. A path from city s to city t is a sequence of cities p1, p2, ... , pk, where p1 = s, pk = t, and there is a road from city pi to city pi + 1 for each i from 1 to k - 1. The path can pass multiple times through each city except t. It can't pass through t more than once. A path p from s to t is ideal if it is the lexicographically minimal such path. In other words, p is ideal path from s to t if for any other path q from s to t pi < qi, where i is the minimum integer such that pi β‰  qi. There is a tourist agency in the country that offers q unusual excursions: the j-th excursion starts at city sj and ends in city tj. For each pair sj, tj help the agency to study the ideal path from sj to tj. Note that it is possible that there is no ideal path from sj to tj. This is possible due to two reasons: * there is no path from sj to tj; * there are paths from sj to tj, but for every such path p there is another path q from sj to tj, such that pi > qi, where i is the minimum integer for which pi β‰  qi. The agency would like to know for the ideal path from sj to tj the kj-th city in that path (on the way from sj to tj). For each triple sj, tj, kj (1 ≀ j ≀ q) find if there is an ideal path from sj to tj and print the kj-th city in that path, if there is any. Input The first line contains three integers n, m and q (2 ≀ n ≀ 3000,0 ≀ m ≀ 3000, 1 ≀ q ≀ 4Β·105) β€” the number of cities, the number of roads and the number of excursions. Each of the next m lines contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), denoting that the i-th road goes from city xi to city yi. All roads are one-directional. There can't be more than one road in each direction between two cities. Each of the next q lines contains three integers sj, tj and kj (1 ≀ sj, tj ≀ n, sj β‰  tj, 1 ≀ kj ≀ 3000). Output In the j-th line print the city that is the kj-th in the ideal path from sj to tj. If there is no ideal path from sj to tj, or the integer kj is greater than the length of this path, print the string '-1' (without quotes) in the j-th line. Example Input 7 7 5 1 2 2 3 1 3 3 4 4 5 5 3 4 6 1 4 2 2 6 1 1 7 3 1 3 2 1 3 5 Output 2 -1 -1 2 -1 Submitted Solution: ``` def tryExcursion(grid, start, end, city): path = [start] currentCity = start move = moveCities(grid, path, start) while move != -1: if not move in path: path += [move] if move == end: if not move in path: path += [move] break move = moveCities(grid, path, move) if move == -1 and path[-1] != end: return move elif city - 1 < len(path): return path[city-1] else: return -1 class Hello(BaseException): pass def moveCities(grid, path, currentCity): #print(path) #print(grid[currentCity -1 ]) for a in grid[currentCity-1]: for b in path: if a == b: return -1 return a return -1 ''' for a in grid[currentCity - 1]: #print(a) try: for b in path: if a == b: return -1 #print("THIS IS B ", b) raise Hello() except Hello: #print("SKIPPING ", a) continue #path += [a] return a return -1 ''' inputtext = input().split(" ") cities = int(inputtext[0]) roads = int(inputtext[1]) excursions = int(inputtext[2]) excursionslist = [] grid = [[] for i in range(cities)] for a in range(roads): road = [int(a) for a in input().split(" ")] if road[1] not in grid[road[0]-1]: grid[road[0] - 1] += [road[1]] if road[0] not in grid[road[1]-1]: grid[road[1] - 1] += [road[0]] for gr in grid: gr.sort() for _ in range(excursions): excursionslist += [[int(i) for i in input().split(" ")]] for _ in range(excursions): #if excursionslist[_][0] > excursionslist[_][1]: # print(-1) #else: print(tryExcursion(grid, excursionslist[_][0], excursionslist[_][1], excursionslist[_][2])) ``` No
6,297
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y. A path from city s to city t is a sequence of cities p1, p2, ... , pk, where p1 = s, pk = t, and there is a road from city pi to city pi + 1 for each i from 1 to k - 1. The path can pass multiple times through each city except t. It can't pass through t more than once. A path p from s to t is ideal if it is the lexicographically minimal such path. In other words, p is ideal path from s to t if for any other path q from s to t pi < qi, where i is the minimum integer such that pi β‰  qi. There is a tourist agency in the country that offers q unusual excursions: the j-th excursion starts at city sj and ends in city tj. For each pair sj, tj help the agency to study the ideal path from sj to tj. Note that it is possible that there is no ideal path from sj to tj. This is possible due to two reasons: * there is no path from sj to tj; * there are paths from sj to tj, but for every such path p there is another path q from sj to tj, such that pi > qi, where i is the minimum integer for which pi β‰  qi. The agency would like to know for the ideal path from sj to tj the kj-th city in that path (on the way from sj to tj). For each triple sj, tj, kj (1 ≀ j ≀ q) find if there is an ideal path from sj to tj and print the kj-th city in that path, if there is any. Input The first line contains three integers n, m and q (2 ≀ n ≀ 3000,0 ≀ m ≀ 3000, 1 ≀ q ≀ 4Β·105) β€” the number of cities, the number of roads and the number of excursions. Each of the next m lines contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), denoting that the i-th road goes from city xi to city yi. All roads are one-directional. There can't be more than one road in each direction between two cities. Each of the next q lines contains three integers sj, tj and kj (1 ≀ sj, tj ≀ n, sj β‰  tj, 1 ≀ kj ≀ 3000). Output In the j-th line print the city that is the kj-th in the ideal path from sj to tj. If there is no ideal path from sj to tj, or the integer kj is greater than the length of this path, print the string '-1' (without quotes) in the j-th line. Example Input 7 7 5 1 2 2 3 1 3 3 4 4 5 5 3 4 6 1 4 2 2 6 1 1 7 3 1 3 2 1 3 5 Output 2 -1 -1 2 -1 Submitted Solution: ``` # -*- coding: utf-8 -*- import collections N, M, Q = map(int, input().split()) ST = [] for i in range(M): ST.append([int(x) for x in input().split()]) ST.sort() P = collections.defaultdict(list) for s,t in ST: P[s].append(t) INF = False memo = {} def dfs(start, end, path, visited, circle): global INF if INF: return [] key = (start, end) if start == end: return path if key in memo: rest = memo[key] if not rest: return [] # maybe exists circle # path += rest[1:] # return path for to in P[start]: if to not in visited: ans = dfs(to, end, path+[to], visited | {to}, circle) if ans: memo[key] = ans[len(path)-1:] return ans else: if not circle: # circle, break out from some point on the circle, # if it can reach destination, no smallest lexicographically path. # no need to record path ci = path.index(to) for j in range(ci+1, len(path)+1): key = (path[j-1], end) if key in memo: if memo[key]: return [] if dfs(path[j-1], end, [], visited, True): INF = True memo[(start, end)] = [] return [] memo[key] = [] return [] for i in range(Q): s, t, k = map(int, input().split()) INF = False p = dfs(s, t, [s], {s}, False) # print(s, t, k, p) if INF: print(-1) continue if not p: print(-1) continue if k > len(p): print(-1) else: print(p[k - 1]) # 2 3 4 5 4 5 4 5 .... 4 6 ``` No
6,298
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Some pairs of them are connected with m directed roads. One can use only these roads to move from one city to another. There are no roads that connect a city to itself. For each pair of cities (x, y) there is at most one road from x to y. A path from city s to city t is a sequence of cities p1, p2, ... , pk, where p1 = s, pk = t, and there is a road from city pi to city pi + 1 for each i from 1 to k - 1. The path can pass multiple times through each city except t. It can't pass through t more than once. A path p from s to t is ideal if it is the lexicographically minimal such path. In other words, p is ideal path from s to t if for any other path q from s to t pi < qi, where i is the minimum integer such that pi β‰  qi. There is a tourist agency in the country that offers q unusual excursions: the j-th excursion starts at city sj and ends in city tj. For each pair sj, tj help the agency to study the ideal path from sj to tj. Note that it is possible that there is no ideal path from sj to tj. This is possible due to two reasons: * there is no path from sj to tj; * there are paths from sj to tj, but for every such path p there is another path q from sj to tj, such that pi > qi, where i is the minimum integer for which pi β‰  qi. The agency would like to know for the ideal path from sj to tj the kj-th city in that path (on the way from sj to tj). For each triple sj, tj, kj (1 ≀ j ≀ q) find if there is an ideal path from sj to tj and print the kj-th city in that path, if there is any. Input The first line contains three integers n, m and q (2 ≀ n ≀ 3000,0 ≀ m ≀ 3000, 1 ≀ q ≀ 4Β·105) β€” the number of cities, the number of roads and the number of excursions. Each of the next m lines contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), denoting that the i-th road goes from city xi to city yi. All roads are one-directional. There can't be more than one road in each direction between two cities. Each of the next q lines contains three integers sj, tj and kj (1 ≀ sj, tj ≀ n, sj β‰  tj, 1 ≀ kj ≀ 3000). Output In the j-th line print the city that is the kj-th in the ideal path from sj to tj. If there is no ideal path from sj to tj, or the integer kj is greater than the length of this path, print the string '-1' (without quotes) in the j-th line. Example Input 7 7 5 1 2 2 3 1 3 3 4 4 5 5 3 4 6 1 4 2 2 6 1 1 7 3 1 3 2 1 3 5 Output 2 -1 -1 2 -1 Submitted Solution: ``` # -*- coding: utf-8 -*- import collections N, M, Q = map(int, input().split()) ST = [] for i in range(M): ST.append([int(x) for x in input().split()]) ST.sort() P = collections.defaultdict(list) for s,t in ST: P[s].append(t) INF = False memo = {} def dfs(start, end, path, visited, circle): global INF if INF: return [] key = (start, end) if start == end: memo[key] = path return path if key in memo: rest = memo[key] if not rest: return [] path += rest[1:] return path for to in P[start]: if to not in visited: ans = dfs(to, end, path+[to], visited | {to}, circle) if ans: memo[key] = ans return ans else: if not circle: # circle, break out from some point on the circle, # if it can reach destination, no smallest lexicographically path. # no need to record path ci = path.index(to) for j in range(ci+1, len(path)+1): if dfs(path[j-1], end, [], visited, True): INF = True memo[key] = [] return [] memo[key] = [] return [] for i in range(Q): s, t, k = map(int, input().split()) INF = False p = dfs(s, t, [s], {s}, False) # print(s, t, k, p) if INF: print(-1) continue if not p: print(-1) continue if k > len(p): print(-1) else: print(p[k - 1]) # 2 3 4 5 4 5 4 5 .... 4 6 ``` No
6,299