message
stringlengths
2
43.5k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
853
107k
cluster
float64
24
24
__index_level_0__
int64
1.71k
214k
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end.
instruction
0
102,675
24
205,350
Tags: dp Correct Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop,heapify import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline from itertools import accumulate from functools import lru_cache M = mod = 998244353 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('\n')] sys.setrecursionlimit(10 ** 6) a, n, m = li() l = [] rain = defaultdict(int) for i in range(n): c, b = li() for j in range(c, b): rain[(j, j + 1)] = 1 # print(rain) umbrellas = [float('inf')] * (a + 5) for i in range(m): c, b = li() umbrellas[c] = min(umbrellas[c], b) # print(umbrellas[:a + 1]) @lru_cache(None) def dp(i = 0, umbon = 0): # print(i, umbon) if i == a: if rain[(i - 1, i)]: if umbon:return umbon return float('inf') else:return umbon else: ans = float('inf') last = umbon if rain[(i - 1, i)]: umbon = min(umbon, umbrellas[i]) if umbon else umbrellas[i] if not last:last = float('inf') ans = min(ans, last + dp(i + 1, umbon)) ans = min(ans, last + dp(i + 1, 0)) else: ans = min(ans, dp(i + 1, 0) + last) umbon = min(umbon, umbrellas[i]) if umbon else umbrellas[i] ans = min(ans, dp(i + 1, umbon) + last) return ans print(dp(0, 0) if dp(0, 0) != float('inf') else -1) ```
output
1
102,675
24
205,351
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end.
instruction
0
102,676
24
205,352
Tags: dp Correct Solution: ``` import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline INF = 10**15 def dp_min(dp, pos, new_val): if pos not in dp: dp[pos] = new_val else: dp[pos] = min(dp[pos], new_val) def solve(): a, n, m = list(map(int, input().split())) has_rain = [False] * a for _ in range(n): l, r = map(int, input().split()) for i in range(l, r): has_rain[i] = True umbrella = [INF] * a for _ in range(m): x, p = map(int, input().split()) if x == a: continue umbrella[x] = min(umbrella[x], p) # dp: best cost so far if I am currently carrying no umbrella (-1), or some umbrella of certain weight dp = {-1: 0} for i in range(a): new_dp = {} for umbrella_weight, best_cost in dp.items(): if not has_rain[i]: # carry no umbrella dp_min(new_dp, -1, best_cost) # take the new umbrella dp_min(new_dp, umbrella[i], best_cost + umbrella[i]) if umbrella_weight != -1: # continue same umbrella dp_min(new_dp, umbrella_weight, best_cost + umbrella_weight) dp = new_dp best = min(dp.values()) if best >= INF: print(-1) else: print(best) t = 1 for _ in range(t): solve() ```
output
1
102,676
24
205,353
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end.
instruction
0
102,677
24
205,354
Tags: dp Correct Solution: ``` import sys a, n, m = map(int, input().split(' ')) seg = [] for i in range(n): rained = tuple(map(int, input().split(' '))) for k in range(rained[0], rained[1]): seg.append(k+1) umbrella = [] for j in range(m): u = tuple(map(int, input().split(' '))) umbrella.append(u) memo = [0] * (a+1) umbrella = sorted(umbrella, key=lambda x: x[0]) if umbrella[0][0] > seg[0] - 1: print(-1) sys.exit(0) for index in range(1, len(memo)): if index not in seg: memo[index] = memo[index-1] continue for each in umbrella: if index >= each[0]: cur = (index - each[0]) * each[1] + memo[each[0]] if memo[index] > 0: if cur < memo[index]: memo[index] = cur else: memo[index] = cur print(memo[-1]) ```
output
1
102,677
24
205,355
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end.
instruction
0
102,678
24
205,356
Tags: dp Correct Solution: ``` # Codeforces Round #486 (Div. 3) from functools import cmp_to_key #key=cmp_to_key(lambda x,y: 1 if x not in y else -1 ) import sys def getIntList(): return list(map(int, input().split())) a,n,m = getIntList() rainend = set() umbr = {} keyPointSet = set([0,a]) for i in range(n): t =tuple(getIntList()) for j in range(t[0] + 1, t[1] + 1): rainend.add(j) keyPointSet.add(t[1]) for i in range(m): t =getIntList() if t[0] not in umbr or t[1]< umbr[t[0]]: umbr[t[0]] = t[1] keyPointSet.add(t[0]) keyPoint = list(keyPointSet) keyPoint.sort() dp = {} dp[0] = {} dp[0] [0] = 0 if 0 in umbr: dp[0][umbr[0]] = 0 for i in range(1, len(keyPoint)): x = keyPoint[i] lx = keyPoint[i-1] ifrain = x in rainend dp[x] = {} nowdp = dp[x] lastdp = dp[lx] for z in lastdp: if z == 0 : if not ifrain: nowdp[0] = lastdp[0] else: nowdp[z] = lastdp[z] + z * (x-lx) if len(nowdp) >0: nowdp[0] = min(nowdp.values()) if x in umbr: if umbr[x] not in nowdp or nowdp[0] < nowdp[umbr[x]]: nowdp[umbr[x]] = nowdp[0] else: print(-1) sys.exit() print( min(dp[a].values()) ) ```
output
1
102,678
24
205,357
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end.
instruction
0
102,679
24
205,358
Tags: dp Correct Solution: ``` import sys a,m,n=list(map(int,input().split())) aux=[0]*(a+1) inf=10**15 dp=[aux.copy() for i in range(n+1)] m1=10**12 m2=10**12 for i in range(m): l,r=list(map(int,input().split())) if l<m1: m1=l for j in range(l,r): dp[0][j+1]=inf s=[] for i in range(1,n+1): x,w=list(map(int,input().split())) s.append(tuple([x,w])) if x<m2: m2=x if m2>m1: print(-1) sys.exit() s.sort() for i in range(1,n+1): x=s[i-1][0] w=s[i-1][1] for j in range(x+1): dp[i][j]=dp[i-1][j] for j in range(x+1,a+1): if i!=1: dp[i][j]=min(dp[0][j]+dp[i][j-1],dp[i-1][j],w*(j-x)+dp[i][x]) else: dp[i][j]=min(dp[0][j]+dp[i][j-1],w*(j-x)+dp[i][x]) ans=dp[-1][-1] if ans>=inf: print(-1) else: print(ans) ```
output
1
102,679
24
205,359
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end.
instruction
0
102,680
24
205,360
Tags: dp Correct Solution: ``` import sys def input(): return sys.stdin.readline().strip() def input_l(): return map(int, input().split()) def input_t(): return tuple(input_l()) def main(): a, s, d = input_l() q = [] e = [] z = [0] * (a + 1) for i in range(s): w = input_t() for k in range(w[0], w[1]): q.append(k + 1) for j in range(d): e.append(input_t()) e = sorted(e, key = lambda x: x[0]) if e[0][0] > q[0] - 1: print(-1) sys.exit(0) for i in range(1, len(z)): if i not in q: z[i] = z[i-1] continue for j in e: if i >= j[0]: c = (i - j[0]) * j[1] + z[j[0]] if z[i] > 0: if c < z[i]: z[i] = c else: z[i] = c print(z[-1]) main() ```
output
1
102,680
24
205,361
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` import math def main(): a, n, m = map(int, input().split()) rain = [] u = [] w = [] raining = [False] * (a+1) for i in range(n): l, r = map(int, input().split()) rain.append((l, r)) for j in range(l, r): raining[j] = True for i in range(m): x, y = map(int, input().split()) u.append(x) w.append(y) rain_int = [0] * a for i in range(n): rain_int[rain[i][0]-1] = 1 rain_int[rain[i][1]-1] = -1 umbrellas = [-1 for _ in range(a+1)] for i, x in enumerate(u): if umbrellas[x] == -1 or w[umbrellas[x]] > w[i]: umbrellas[x] = i dp = [[math.inf for _ in range(m+1)] for _ in range(a+1)] dp[0][m] = 0 for i in range(a): for j in range(m+1): if dp[i][j] == math.inf: continue if not raining[i]: dp[i+1][m] = min(dp[i+1][m], dp[i][j]) if j < m: dp[i+1][j] = min(dp[i+1][j], dp[i][j] + w[j]) if umbrellas[i] != -1: dp[i+1][umbrellas[i]] = min(dp[i+1][umbrellas[i]], dp[i][j]+w[umbrellas[i]]) ans = math.inf for i in range(m+1): ans = min(ans, dp[a][i]) print(-1 if ans == math.inf else ans) if __name__ == '__main__': main() ```
instruction
0
102,681
24
205,362
Yes
output
1
102,681
24
205,363
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` #!/usr/bin/env pypy from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip MOD = 10**9 + 7 # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion a, s, d = map(int, input().split()) q = [] e = [] z = [0] * (a + 1) for i in range(s): w = tuple(map(int, input().split())) for k in range(w[0], w[1]): q.append(k + 1) for j in range(d): e.append(tuple(map(int, input().split()))) e = sorted(e, key = lambda x: x[0]) # ~ print(e) if e[0][0] > q[0] - 1: print(-1) exit() for i in range(1, a +1): if i not in q: z[i] = z[i-1] continue for j in e: if i >= j[0]: c = (i - j[0]) * j[1] + z[j[0]] if z[i] > 0: if c < z[i]: z[i] = c else: z[i] = c print(z[-1]) ```
instruction
0
102,682
24
205,364
Yes
output
1
102,682
24
205,365
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` rd = lambda: map(int, input().split()) a, n, m = rd() s = set() u = {} k = set([0, a]) for _ in range(n): l, r = rd() for x in range(l + 1, r + 1): s.add(x) k.add(r) for _ in range(m): x, p = rd() u[x] = min(p, u.get(x, 1e9)) k.add(x) k = sorted(list(k)) dp = {} dp[0] = {} dp[0][0] = 0 if 0 in u: dp[0][u[0]] = 0 for i in range(1, len(k)): x = k[i] y = k[i - 1] dp[x] = {} for z in dp[y]: if z: dp[x][z] = dp[y][z] + z * (x - y) else: if x not in s: dp[x][0] = dp[y][0] if len(dp[x]): dp[x][0] = min(dp[x].values()) if x in u: if u[x] not in dp[x] or dp[x][0] < dp[x][u[x]]: dp[x][u[x]] = dp[x][0] else: print(-1) exit() print(dp[a][0]) ```
instruction
0
102,683
24
205,366
Yes
output
1
102,683
24
205,367
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` a,m,n=list(map(int,input().split())) aux=[0]*(a+1) inf=10**15 dp=[aux.copy() for i in range(n+1)] for i in range(m): l,r=list(map(int,input().split())) for j in range(l,r): dp[0][j+1]=inf s=[] for i in range(1,n+1): x,w=list(map(int,input().split())) s.append(tuple([x,w])) s.sort() for i in range(1,n+1): x=s[i-1][0] w=s[i-1][1] for j in range(x+1): dp[i][j]=dp[i-1][j] for j in range(x+1,a+1): if i!=1: dp[i][j]=min(dp[0][j]+dp[i][j-1],dp[i-1][j],w*(j-x)+dp[i][x]) else: dp[i][j]=min(dp[0][j]+dp[i][j-1],w*(j-x)+dp[i][x]) ans=dp[-1][-1] if ans>=inf: print(-1) else: print(ans) ```
instruction
0
102,684
24
205,368
No
output
1
102,684
24
205,369
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` #!python3 # http://codeforces.com/contest/988/problem/F from bisect import bisect_left as bl a, n, m = [int(i) for i in input().strip().split(' ')] R = [] for i in range(n): l, r = [int(j) for j in input().strip().split(' ')] inx = bl(R, l) R.insert(inx, l) R.insert(inx+1, r) A = [] for i in range(m): A += [tuple(int(j) for j in input().strip().split(' '))] A = sorted(A) class S: # Solution def __init__(self, a, t): self.t = t # tiredness self.a = a # ambrella def __repr__(self): return "({} {})".format(self.a, self.t) O = [S(0,0)] # no ambrellas, not tired x = 0 # starts at 0 x_prev = 0 is_rain = False optimal = None while x <= a: # check if rain: rain_inx = bl(R, x) if rain_inx < len(R): rain_coord = R[rain_inx] if x == rain_coord: is_rain = not is_rain # update tiredness in solutions: distance = x - x_prev optimal = 9*999 for o in O: amb = o.a if amb > 0: p = A[amb-1][1] o.t += p*distance if o.t < optimal: optimal = o.t # pick up new ambrellas: k = bl(A, (x, 0)) # inx of next ambrellas or one at x if k < len(A): # have some here or next while k < len(A) and A[k][0] == x: # every ambrella at x amb = k + 1 O += [S(amb, optimal)] k += 1 assert k >= len(A) or A[k][0] != x, "k should be next amb or none" # drop solution without ambrella if rains: index_list = [i for i, el in enumerate(O) if el.a == 0] s_inx = index_list[0] if len(index_list) > 0 else None if is_rain and s_inx is not None: # can not go without ambrella assert O[s_inx].a == 0 del O[s_inx] elif not is_rain and s_inx is None: # can go without one O.append(S(0, optimal)) if not any(O) and x != a: optimal = -1 break # get next x: next_x = a if rain_inx < len(R): if x < R[rain_inx]: next_x = R[rain_inx] elif rain_inx + 1 < len(R): next_x = R[rain_inx+1] if k < len(A) and A[k][0] < next_x: next_x = A[k][0] if x == next_x: break x_prev = x x = next_x print(optimal) ```
instruction
0
102,685
24
205,370
No
output
1
102,685
24
205,371
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` def main(): a, n, m = map(int, input().split()) rain = [False] * (a + 1) for _ in range(n): x, y = map(int, input().split()) for i in range(x, y + 1): rain[i] = True umrella = [0] * (a + 1) for _ in range(m): x, y = map(int, input().split()) if umrella[x] == 0: umrella[x] = y else: umrella[x] = min(umrella[x], y) max_value = 10 ** 18 dp = [max_value] * (a + 1) ok = True if not rain[0] or umrella[0] > 0: dp[0] = 0 else: ok = False if ok: for i in range(1, a + 1): if not rain[i]: dp[i] = dp[i - 1] else: for j in range(0, i + 1): if umrella[j] > 0: if j >= 1: dp[i] = min(dp[i], dp[j - 1] + umrella[j] * (i - j)) else: dp[i] = min(dp[i], umrella[j] * (i - j)) if dp[a] == max_value: print(-1) else: print(dp[a]) else: print(-1) if __name__ == "__main__": main() ```
instruction
0
102,686
24
205,372
No
output
1
102,686
24
205,373
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` s=input()[::-1] m=I=41 f=s.find('5')+1 i=s.find('0')+1 t=len(s) if i: j=min(s.find('0',i)+1or I,f or I) if j<I: m=i+j-3 if j<i:m+=1 if f: j=min(s.find('2')+1or I,s.find('7')+1or I) if j<I: l=f+j-3 if j<f:l+=1 if f==t: i=t-1 while i==j or s[i-1]=='0': if i!=j:l+=1 i-=1 m=min(m,l) print((-1,m)[m<I]) ```
instruction
0
102,687
24
205,374
No
output
1
102,687
24
205,375
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
instruction
0
103,362
24
206,724
Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` cycle = False def DFS(s): global cycle visited[s] = 1 stack = [s] while len(stack) != 0: u = stack[-1] visited[u] = 1 if len(graph[u]) != 0: v = graph[u].pop() if visited[v] == 1: cycle = True return if visited[v] == 2: continue stack.append(v) else: result.append(u) stack.pop() visited[u] = 2 def TopoSort(graph, result, visited): for i in range (m): if not visited[requiredCourse[i]]: DFS(requiredCourse[i]) return result n, m = map(int, input().split()) requiredCourse = list(map(int, input().split())) visited = [0 for i in range (n + 1)] graph = [[] for i in range (n + 1)] result = [] for i in range (1, n + 1): tmp = list(map(int, input().split())) if tmp[0] == 0: continue for j in range (1, tmp[0] + 1): graph[i].append(tmp[j]) res = TopoSort(graph, result, visited) if cycle: print(-1) else: print(len(res)) for i in res: print(i, end = " ") ```
output
1
103,362
24
206,725
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
instruction
0
103,363
24
206,726
Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` # https://codeforces.com/problemset/problem/770/C n, k = map(int, input().split()) K = set(list(map(int, input().split()))) g = {} rg = {} deg = {} def push_d(deg, u, val): if u not in deg: deg[u] = 0 deg[u] += val def push_g(g, u, v): if u not in g: g[u] = [] g[u].append(v) for u in range(1, n+1): list_v = list(map(int, input().split()))[1:] deg[u] = 0 for v in list_v: push_d(deg, u, 1) push_g(g, v, u) push_g(rg, u, v) S = [x for x in K] used = [0] * (n+1) i = 0 while i<len(S): u = S[i] if u in rg: for v in rg[u]: if used[v] == 0: used[v] = 1 S.append(v) i+=1 S = {x:1 for x in S} deg0 = [x for x in S if deg[x]==0] ans = [] def process(g, deg, deg0, u): if u in g: for v in g[u]: if v in S: push_d(deg, v, -1) if deg[v] == 0: deg0.append(v) while len(deg0) > 0 and len(K) > 0: u = deg0.pop() ans.append(u) if u in K: K.remove(u) process(g, deg, deg0, u) if len(K) > 0: print(-1) else: print(len(ans)) print(' '.join([str(x) for x in ans])) #6 2 #5 6 #0 #1 1 #1 4 5 #2 2 1 #1 4 #2 5 3 ```
output
1
103,363
24
206,727
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
instruction
0
103,364
24
206,728
Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` def dfs(start_node, edges, colors, result): stack = [start_node] while stack: current_node = stack[-1] if colors[current_node] == 2: stack.pop() continue colors[current_node] = 1 children = edges[current_node] if not children: colors[current_node] = 2 result.append(stack.pop()) else: child = children.pop() if colors[child] == 1: return False stack.append(child) return True def find_courses_sequence(member_of_node, find_nodes, edges): colors = [0] * member_of_node result = [] for node in find_nodes: if not dfs(node, edges, colors, result): return [] return result if __name__ == '__main__': n, k = map(int, input().split()) main_courses = [int(c)-1 for c in input().split()] courses = dict() for index in range(n): courses[index] = [int(d)-1 for d in input().split()[1:]] result = find_courses_sequence(n, main_courses, courses) if result: print(len(result)) for v in result: print(v+1, end=" ") else: print(-1) ```
output
1
103,364
24
206,729
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
instruction
0
103,365
24
206,730
Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` n,k=list(map(lambda x: int(x), input().split())) m=list(map(lambda x: int(x), input().split())) from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc class Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] @bootstrap def DFSUtil(self, temp, v, visited): visited[v] = True for i in self.adj[v]: if visited[i] == False: yield self.DFSUtil(temp, i, visited) temp.append(v) yield temp def addEdge(self, v, w): self.adj[v].append(w) # self.adj[w].append(v) @bootstrap def isCyclicUtil(self, v, visited, recStack): # Mark current node as visited and # adds to recursion stack visited[v] = True recStack[v] = True # Recur for all neighbours # if any neighbour is visited and in # recStack then graph is cyclic for neighbour in self.adj[v]: if visited[neighbour] == False: ans =yield self.isCyclicUtil(neighbour, visited, recStack) if ans == True: yield True elif recStack[neighbour] == True: yield True # The node needs to be poped from # recursion stack before function ends recStack[v] = False yield False # Returns true if graph is cyclic else false def isCyclic(self,nodes): visited = [False] * self.V recStack = [False] * self.V for node in nodes: if visited[node] == False: if self.isCyclicUtil(node, visited, recStack) == True: return True return False G=Graph(n) for i in range(0,n): x=list(map(lambda x: int(x), input().split())) if x[0]==0: continue else: for k in range(1,x[0]+1): G.addEdge(i,x[k]-1) visited=[False for _ in range(n)] path=[] # print(G.adj) for subj in m: temp = [] if visited[subj-1]==False: G.DFSUtil(temp,subj-1,visited) path.extend(temp) if G.isCyclic([x-1 for x in m]): print(-1) else: print(len(path)) for p in path: print(p+1,end=" ") print() ```
output
1
103,365
24
206,731
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
instruction
0
103,366
24
206,732
Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` import sys def main(): n,k = map(int,sys.stdin.readline().split()) courses = list(map(int,sys.stdin.readline().split())) courses = [x-1 for x in courses] visited = [False]*n used = [False]*n ans = [] t = [] for i in range(n): temp = list(map(int,sys.stdin.readline().split())) temp = [x-1 for x in temp] t.append(temp[1:]) for i in range(k): c = courses[i] if used[c]: continue q = [c] visited[c]=True while len(q)>0: cur = q[-1] if len(t[cur])!=0: s = t[cur].pop() if visited[s] and not used[s]: print(-1) return if used[s]: continue q.append(s) visited[s]=True else: ans.append(cur) q.pop() used[cur] = True ans = [str(x+1) for x in ans] print(len(ans)) print(" ".join(ans)) main() ```
output
1
103,366
24
206,733
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
instruction
0
103,367
24
206,734
Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` import collections as col import itertools as its import sys import operator from copy import copy, deepcopy class Solver: def __init__(self): pass def solve(self): n, k = map(int, input().split()) q = list(map(lambda x: int(x) - 1, input().split())) used = [False] * n for e in q: used[e] = True edges = [[] for _ in range(n)] redges = [[] for _ in range(n)] for i in range(n): l = list(map(lambda x: int(x) - 1, input().split()))[1:] edges[i] = l for e in l: redges[e].append(i) degs = [len(edges[i]) for i in range(n)] d = 0 while d < len(q): v = q[d] d += 1 for e in edges[v]: if not used[e]: used[e] = True q.append(e) q = q[::-1] nq = [] for v in q: if degs[v] == 0: nq.append(v) d = 0 while d < len(nq): v = nq[d] d += 1 for e in redges[v]: if not used[e]: continue degs[e] -= 1 if degs[e] == 0: nq.append(e) #print(nq) if len(q) != len(nq): print(-1) return print(len(nq)) print(' '.join(map(lambda x: str(x + 1), nq))) if __name__ == '__main__': s = Solver() s.solve() ```
output
1
103,367
24
206,735
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
instruction
0
103,368
24
206,736
Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` f = lambda: map(int, input().split()) g = lambda: [int(q) - 1 for q in f()] class T: def __init__(s, i): s.i, s.t = i, g()[1:] s.a = s.q = 0 n, k = f() d = g() p = [T(i) for i in range(n)] s = [] while d: x = p[d.pop()] if x.a: continue d.append(x.i) q = 1 for i in x.t: y = p[i] if y.a: continue d.append(y.i) q = 0 if q: s.append(x.i + 1) x.a = 1 elif x.q: print(-1) exit() else: x.q = 1 print(len(s), *s) ```
output
1
103,368
24
206,737
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.
instruction
0
103,369
24
206,738
Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` from sys import * f = lambda: list(map(int, stdin.readline().split())) class T: def __init__(self, i): self.i, self.t = i, f()[1:] self.a = self.q = 0 n, k = f() d = f() p = [None] + [T(i + 1) for i in range(n)] s = [] while d: x = p[d.pop()] if x.a: continue d.append(x.i) q = 1 for i in x.t: y = p[i] if y.a: continue d.append(y.i) q = 0 if q: s.append(x.i) x.a = 1 elif x.q: print(-1) exit() else: x.q = 1 print(len(s), *s) ```
output
1
103,369
24
206,739
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 8) cycle = False def DFS(i, graph, result, visited): global cycle stack = [i] while len(stack) != 0: u = stack[-1] visited[u] = 1 if len(graph[u]) != 0: v = graph[u].pop() if visited[v] == 1: cycle = True return if visited[v] == 2: continue stack.append(v) visited[u] = 1 else: result.append(u) stack.pop() visited[u] = 2 def TopoSort(graph, result): for i in range(m): if not visited[requiredCourse[i]]: DFS(requiredCourse[i], graph, result, visited) return result n, m = map(int, input().split()) requiredCourse = list(map(int, input().split())) graph = [[] for i in range(n + 1)] result = [] visited = [False for i in range(n + 1)] for i in range(1, n + 1): tmp = list(map(int, input().split())) if tmp[0] == 0: continue for j in range(1, tmp[0] + 1): graph[i].append(tmp[j]) res = TopoSort(graph, result) if cycle == True: print(-1) else: print(len(res)) for i in res: print(i, end=" ") ```
instruction
0
103,370
24
206,740
Yes
output
1
103,370
24
206,741
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` '''import sys flag=True sys.setrecursionlimit(2000000) c=[];st=[]; def topo(s):#Traversing the array and storing the vertices global c,st,flag; c[s]=1; #Being Visited for i in adjli[s]:#visiting neighbors if c[i]==0: topo(i) if c[i]==1: flag=False# If Back Edge , Then Not Possible st.append(str(s)) c[s]=2 # Visited try: n,k=map(int,input().split(' '))#Number Of Courses,Dependencies main=list(map(int,input().split(' ')))#Main Dependencies depen=[]#Dependencies List for i in range(n): depen.append(list(map(int,input().split(' ')))[1:]);c.append(0)#Append Input To Dependencies List, Marking Visited as 0(False) c.append(0) adjli=[] adjli.append(main)#Assuming Main Course at index 0 with dependencies as Main Dependency(main) for i in range(len(depen)): adjli.append(depen[i])#Appending Other Dependencies topo(0)#TopoLogical Sort Order st.pop(-1)#popping the assumed Main Couse if flag:# IF possible then print print(len(st)) print(' '.join(st)) else: print(-1) except Exception as e: print(e,"error")''' import sys flag=True sys.setrecursionlimit(2000000000) c=[];st=[]; cur_adj=[] def topo(s):#Traversing the array and storing the vertices global c,st,flag; stack = [s] while(stack): s = stack[-1] c[s]=1; #Being Visited if(cur_adj[s] < len(adjli[s])): cur = adjli[s][cur_adj[s]] if(c[cur]==0): stack.append(cur) if(c[cur]==1): flag=False# If Back Edge , Then Not Possible cur_adj[s]+=1 else: c[s]=2 st.append(str(s)) del stack[-1] try: n,k=map(int,input().split(' ')) main=list(map(int,input().split(' '))) depen=[] for i in range(n): depen.append(list(map(int,input().split(' ')))[1:]);c.append(0) cur_adj.append(0) c.append(0) cur_adj.append(0) adjli=[] adjli.append(main)#Assuming Main Course at index 0 with dependencies as Main Dependency(main) for i in range(len(depen)): adjli.append(depen[i])#Appending Other Dependencies topo(0)#TopoLogical Sort Order st.pop(-1)#popping the assumed Main Couse if flag:# IF possible then print print(len(st)) print(' '.join(st)) else: print(-1) except Exception as e: print(e,"error") ```
instruction
0
103,371
24
206,742
Yes
output
1
103,371
24
206,743
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` import sys flag=True sys.setrecursionlimit(2000000000) c=[];st=[]; cur_adj=[] def topo(s):#Traversing the array and storing the vertices global c,st,flag; stack = [s] while(stack): s = stack[-1] c[s]=1; #Being Visited if(cur_adj[s] < len(adjli[s])): cur = adjli[s][cur_adj[s]] if(c[cur]==0): stack.append(cur) if(c[cur]==1): flag=False# If Back Edge , Then Not Possible cur_adj[s]+=1 else: c[s]=2 st.append(str(s)) del stack[-1] try: n,k=map(int,input().split(' ')) main=list(map(int,input().split(' '))) depen=[] for i in range(n): depen.append(list(map(int,input().split(' ')))[1:]);c.append(0) cur_adj.append(0) c.append(0) cur_adj.append(0) adjli=[] adjli.append(main)#Assuming Main Course at index 0 with dependencies as Main Dependency(main) for i in range(len(depen)): adjli.append(depen[i])#Appending Other Dependencies topo(0)#TopoLogical Sort Order st.pop(-1)#popping the assumed Main Couse if flag:# IF possible then print print(len(st)) print(' '.join(st)) else: print(-1) except Exception as e: print(e,"error") ```
instruction
0
103,372
24
206,744
Yes
output
1
103,372
24
206,745
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` #This code is dedicated to Vlada S. class Course: def __init__(self, reqs, number): self.reqs = list(map(int, reqs.split()[1:])) self.available = False self.in_stack = False self.number = number n, k = list(map(int, input().split())) requirements = list(map(int, input().split())) courses = {} answer = "" for i in range(n): courses[i + 1]= Course(input(), i + 1) for i in range(len(requirements)): requirements[i] = courses[requirements[i]] while requirements: data = {} course = requirements.pop() if not course.available: requirements.append(course) done = True for c in course.reqs: c = courses[c] if not c.available: requirements.append(c) done = False if done: answer += " " + str(course.number) course.available = True else: if course.in_stack: print(-1) break course.in_stack = True else: print(answer.count(" ")) print(answer[1:]) # Made By Mostafa_Khaled ```
instruction
0
103,373
24
206,746
Yes
output
1
103,373
24
206,747
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` putninja=[] courses=[] B=True def mff(A, num): global putninja global courses if A[0]=='0': putninja.append(num) courses[int(num)-1][0]='stop' elif A[0]=='stop': pass else: for j in range(int(A[0])): mff(courses[int(A[j+1])-1],A[j+1]) putninja.append(num) courses[int(num)-1][0]='stop' kn=input().split() k=int(kn[0]) n=int(kn[1]) mk=input().split() for i in range(k): s=input() courses.append(s.split(' ')) for i in range(n): try: mff(courses[int(mk[i])-1],mk[i]) except: B=False break if B: print(len(putninja)) print(' '.join(putninja)) else: print(-1) ```
instruction
0
103,374
24
206,748
No
output
1
103,374
24
206,749
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` from sys import stdin, stdout n,k = stdin.readline().split() n = int(n) k = int(k) toLearn = [-1] * n kList = input().split() for i in range(len(kList)): kList[i] = int(kList[i]) nList = [] flag = True for i in range(n): nL = stdin.readline().split() nL.pop(0) for j in range(len(nL)): nL[j] = int(nL[j]) if len(nL) == 0: flag = False nList.append(nL) # n = 100000 # k = 1 # kList = [100000] # nList =[[]] # flag = False # for i in range(1, n): # nList.append([i]) res = [] if k == 0: print(0) print("") elif flag: print(-1) else: res = [] notCircle = True current = 0 while len(kList) > 0 and notCircle: temp = [] for i in kList: res.append(i) toLearn[i - 1] = current for j in nList[i - 1]: if toLearn[j - 1] >= 0: notCircle = False break break if toLearn[j - 1] == -1: temp.append(j) kList = temp current += 1 if notCircle: res.reverse() s = "" for i in res: s += str(i) + " " stdout.write(str(len(res)) + '\n') stdout.write(s[: -1] + '\n') else: stdout.write('-1\n') ```
instruction
0
103,375
24
206,750
No
output
1
103,375
24
206,751
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` itog = '' result = [] iskl = 0 control = 0 maxway = -1 wayStolb = 0 table = [] fs = input() inp = fs.split(' ') nk = [int(i) for i in inp] ss = input() inp = ss.split(' ') maincour = [int(i) for i in inp] for i in range(0,nk[0]): table.append([]) s = input() inp = s.split(' ') t = [int(i) for i in inp] for j in range(0,t[0]+1): table[i].append(t[j]) for i in range (0,len(maincour)): #print(table[maincour[i]-1]) if table[maincour[i]-1][0] > maxway: wayStolb = maincour[i] - 1 maxway = table[maincour[i]-1][0] #print(wayStolb) #print(maxway) e = maxway stolb = wayStolb #4 startStolb = stolb while control != len(maincour) : while table[wayStolb][0] != 0: maxway = -1 e = table[stolb][0] for i in range(1,e+1): if table[table[stolb][i]-1][0] > maxway: wayStolb = table[stolb][i] - 1 maxway = table[table[stolb][i]-1][0] e = maxway if e > 0: stolb = wayStolb iskl = iskl + 1; if iskl > 100000: iskl = -1 break #print('WayStolb = '+str(wayStolb)) #print('Π‘Ρ‹Π» здСсь'+str(stolb)) if iskl == -1: result = '-1' break #print('ΠžΡΡ‚Π°Π½ΠΎΠ²ΠΊΠ° ' +str(wayStolb)) result.append(wayStolb+1) for i in range(0,len(maincour)): if wayStolb == maincour[i] - 1: control = control + 1; if control != len(maincour): table[stolb][0] = table[stolb][0] - 1 try: table[stolb].remove(wayStolb+1) except ValueError: for i in range(0,len(maincour)): if table[maincour[i]-1][0] == 0 and result.count(maincour[i]) == 0: result.append(maincour[i]) control = control + 1 if control != len(maincour): for i in range (0,len(maincour)): #print(table[maincour[i]-1]) if table[maincour[i]-1][0] > maxway: wayStolb = maincour[i] - 1 maxway = table[maincour[i]-1][0] #print(wayStolb) #print(maxway) e = maxway stolb = wayStolb #4 startStolb = stolb #print(table[stolb]) #print(table[stolb][1]) wayStolb = startStolb #print('wayStolb = '+str(wayStolb)) stolb = wayStolb if result != '-1': itog = itog + str(result[0]) for i in range(1,len(result)): itog = itog + ' ' + str(result[i]) print(len(result)) print(itog) else: print(result) ```
instruction
0
103,376
24
206,752
No
output
1
103,376
24
206,753
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` import collections as col import itertools as its import sys import operator from copy import copy, deepcopy class Solver: def __init__(self): pass def solve(self): n, k = map(int, input().split()) q = list(map(lambda x: int(x) - 1, input().split())) used = [False] * n for e in q: used[e] = True edges = [[] for _ in range(n)] redges = [[] for _ in range(n)] for i in range(n): l = list(map(lambda x: int(x) - 1, input().split()))[1:] edges[i] = l for e in l: redges[e].append(i) degs = [len(edges[i]) for i in range(n)] d = 0 while d < len(q): v = q[d] d += 1 for e in edges[v]: if not used[e]: used[e] = True q.append(e) q = q[::-1] nq = [] for v in q: if degs[v] == 0: nq.append(v) d = 0 while d < len(nq): v = nq[d] d += 1 for e in redges[v]: degs[e] -= 1 if degs[e] == 0: nq.append(e) if len(q) != len(nq): print(-1) return print(len(nq)) print(' '.join(map(lambda x: str(x + 1), nq))) if __name__ == '__main__': s = Solver() s.solve() ```
instruction
0
103,377
24
206,754
No
output
1
103,377
24
206,755
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful.
instruction
0
103,903
24
207,806
Tags: dp, math, number theory, sortings Correct Solution: ``` for _ in range(int(input())): length=int(input()) array=list(map(int,input().split())) array.sort() cnt=[0]*(max(array)+1) dp=[0]*(max(array)+1) for x in array: cnt[x]+=1 """ [3, 7, 9, 14, 63] """ for i in range(1,len(dp)): dp[i]+=cnt[i] for j in range(i,len(dp),i): dp[j]=max(dp[j],dp[i]) print(length-max(dp)) ```
output
1
103,903
24
207,807
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful.
instruction
0
103,904
24
207,808
Tags: dp, math, number theory, sortings Correct Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from math import sqrt, pi, ceil, log, inf, gcd, floor from itertools import combinations, permutations from bisect import * from fractions import Fraction from heapq import * from random import randint def main(): for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ma=max(a) b=Counter(a) c=sorted(set(a)) d=[0]*(ma+1) d[c[-1]] =b[c[-1]] ans = b[c[-1]] c.pop() c.reverse() for i in range(len(c)): j=2*c[i] zz=0 while j<=ma: zz=max(zz,d[j]) j+=c[i] d[c[i]]=b[c[i]]+zz ans=max(ans,d[c[i]]) print(n-ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
output
1
103,904
24
207,809
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful.
instruction
0
103,905
24
207,810
Tags: dp, math, number theory, sortings Correct Solution: ``` import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import deque for i in range(int(input())): n=int(input()) alist=list(map(int,input().split())) maxN=int(2e5+1) anslist=[0]*maxN blist=[0]*maxN for i,val in enumerate(alist):blist[val]+=1 for i in range(1,maxN): if blist[i]==0: continue anslist[i]+=blist[i] for j in range(2*i,maxN,i): anslist[j]=max(anslist[i],anslist[j]) print(n-max(anslist)) ```
output
1
103,905
24
207,811
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful.
instruction
0
103,906
24
207,812
Tags: dp, math, number theory, sortings Correct Solution: ``` import sys import math def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def MI(): return map(int, sys.stdin.readline().split()) def SI(): return sys.stdin.readline().strip() def FACT(n, mod): s = 1 facts = [1] for i in range(1,n+1): s*=i s%=mod facts.append(s) return facts[n] def C(n, k, mod): return (FACT(n,mod) * pow((FACT(k,mod)*FACT(n-k,mod))%mod,mod-2, mod))%mod t = II() for q in range(t): n = II() a = LI() inf = max(a)+1 cnt = [0 for i in range(inf)] for i in a: cnt[i]+=1 dp = [0 for i in range(inf)] for i in range(1,inf): dp[i]+=cnt[i] for j in range(i*2,inf, i): dp[j] = max(dp[j], dp[i]) print(n-max(dp)) ```
output
1
103,906
24
207,813
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful.
instruction
0
103,907
24
207,814
Tags: dp, math, number theory, sortings Correct Solution: ``` import sys import copy input=sys.stdin.readline for z in range(int(input())): n=int(input()) a=list(map(int,input().split())) cnt=[0]*(2*10**5+10) cnt2=[0]*(2*10**5+10) a.sort() num10=-1 cnt10=0 a2=[] for i in range(n): if num10!=a[i]: if cnt10!=0: a2.append(num10) cnt[num10]=cnt10 cnt10=1 num10=a[i] else: cnt10+=1 if cnt10!=0: a2.append(num10) cnt[num10]=cnt10 cnt2=copy.copy(cnt) a2.sort() for i in range(len(a2)): b=a2[i] num11=cnt2[b] for j in range(b*2,2*10**5+10,b): cnt2[j]=max(cnt2[j],num11+cnt[j]) ans=n+10 for i in range(len(a2)): ans=min(ans,n-cnt2[a2[i]]) print(ans) ```
output
1
103,907
24
207,815
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful.
instruction
0
103,908
24
207,816
Tags: dp, math, number theory, sortings Correct Solution: ``` from sys import stdin from collections import Counter input = stdin.readline for test in range(int(input())): n = int(input()) lst = list(map(int, input().strip().split())) N = max(lst) + 1 po = [0] * N cnt = Counter(lst) for k in range(1, N): po[k] += cnt.get(k, 0) for i in range(2 * k, N, k): po[i] = max(po[i], po[k]) print(n - max(po)) ```
output
1
103,908
24
207,817
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful.
instruction
0
103,909
24
207,818
Tags: dp, math, number theory, sortings Correct Solution: ``` from bisect import bisect_left for _ in range(int(input())): n = int(input()) l = list(map(int, input().split())) l.sort() m = max(l) z = [0] * (m+1) f = [0] * (m+1) for i in range(n): z[l[i]] += 1 for i in sorted(set(l)): b = i+i f[i] += z[i] while b <= m: f[b] = max(f[b], f[i]) b += i print(n-max(f)) ```
output
1
103,909
24
207,819
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful.
instruction
0
103,910
24
207,820
Tags: dp, math, number theory, sortings Correct Solution: ``` from collections import Counter #fk this shit def f(arr): cnt=Counter(arr) mxn=max(arr)+100 factor=[0]*(mxn) for i in range(1,len(factor)): factor[i]+=cnt.get(i,0) for j in range(2*i,mxn,i): factor[j]=max(factor[i],factor[j]) return len(arr)-max(factor) for i in range(int(input())): s=input() lst=list(map(int,input().strip().split())) print(f(lst)) ```
output
1
103,910
24
207,821
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` from collections import Counter MX = 200001 def solve(arr): total = len(arr) cnt = [0] * MX for a in arr: cnt[a] += 1 u = sorted(set(arr)) loc = [-1] * MX for i,a in enumerate(u): loc[a] = i N = len(u) dp = [0] * N for i,a in enumerate(u): dp[i] = max(dp[i], cnt[a]) for b in range(2*a,MX,a): j = loc[b] if j >= 0: dp[j] = max(dp[j], dp[i] + cnt[b]) return total - max(dp) for _ in range(int(input())): input() arr = list(map(int,input().split())) print(solve(arr)) ```
instruction
0
103,911
24
207,822
Yes
output
1
103,911
24
207,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): def __init__(self, file): self.newlines = 0 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() # -------------------------------------------------------------------- def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def S(): return input().strip() def print_list(l): print(' '.join(map(str, l))) # sys.setrecursionlimit(200000) # import random # from functools import reduce # from functools import lru_cache # from heapq import * # from collections import deque as dq # import math # import bisect as bs from collections import Counter # from collections import defaultdict as dc for t in range(N()): n = N() a = RLL() count = Counter(a) dp = [0] * 200001 for i in range(1, 200001): if count[i] == 0: continue dp[i] += count[i] for j in range(2 * i, 200001, i): dp[j] = max(dp[i], dp[j]) print(n - max(dp)) ```
instruction
0
103,912
24
207,824
Yes
output
1
103,912
24
207,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import sys,math def main(): for _ in range(int(sys.stdin.readline().strip())): n=int(sys.stdin.readline().strip()) arr=list(map(int,sys.stdin.readline().strip().split())) table=[0]*(200001) dp=[0]*(200001) for i in range(n): table[arr[i]]+=1 for i in range(1,200001): dp[i]+=table[i] if dp[i]>0: for j in range(2*i,200001,i): dp[j]=max(dp[j],dp[i]) ans=n-max(dp) sys.stdout.write(str(ans)+'\n') main() ```
instruction
0
103,913
24
207,826
Yes
output
1
103,913
24
207,827
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` factorsMemo=[-1 for _ in range(200001)] def getAllFactors(x): #returns a sorted list of all the factors or divisors of x (including 1 and x) if factorsMemo[x]==-1: factors=[] for i in range(1,int(x**0.5)+1): if x%i==0: factors.append(i) if x//i!=i: factors.append(x//i) factorsMemo[x]=factors return factorsMemo[x] def main(): t=int(input()) allAns=[] for _ in range(t): n=int(input()) a=readIntArr() a.sort() dp=[-inf for _ in range(200001)] #dp[previous number]max number of elements before and including it to be beautiful} maxSizeOfBeautifulArray=0 for x in a: maxPrevCnts=0 for f in getAllFactors(x): maxPrevCnts=max(maxPrevCnts,dp[f]) dp[x]=1+maxPrevCnts maxSizeOfBeautifulArray=max(maxSizeOfBeautifulArray,dp[x]) allAns.append(n-maxSizeOfBeautifulArray) multiLineArrayPrint(allAns) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) #import sys #input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] inf=float('inf') MOD=10**9+7 main() ```
instruction
0
103,914
24
207,828
Yes
output
1
103,914
24
207,829
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import sys,math # FASTEST IO from io import BytesIO, IOBase from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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) # End of FASTEST IO def main(): for _ in range(int(sys.stdin.readline().strip())): n=int(sys.stdin.readline().strip()) arr=list(map(int,sys.stdin.readline().strip().split())) table=[0]*(200001) dp=[0]*(200001) for i in range(n): table[arr[i]]+=1 for i in range(1,200001): for j in range(2*i,200001,i): dp[j]=max(dp[j],table[i]+dp[i]) ans=n-max(dp) sys.stdout.write(str(ans)+'\n') main() ```
instruction
0
103,915
24
207,830
No
output
1
103,915
24
207,831
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import heapq __all__ = ['MappedQueue'] class MappedQueue(object): """The MappedQueue class implements an efficient minimum heap. The smallest element can be popped in O(1) time, new elements can be pushed in O(log n) time, and any element can be removed or updated in O(log n) time. The queue cannot contain duplicate elements and an attempt to push an element already in the queue will have no effect. MappedQueue complements the heapq package from the python standard library. While MappedQueue is designed for maximum compatibility with heapq, it has slightly different functionality. Examples -------- A `MappedQueue` can be created empty or optionally given an array of initial elements. Calling `push()` will add an element and calling `pop()` will remove and return the smallest element. >>> q = MappedQueue([916, 50, 4609, 493, 237]) >>> q.push(1310) True >>> x = [q.pop() for i in range(len(q.h))] >>> x [50, 237, 493, 916, 1310, 4609] Elements can also be updated or removed from anywhere in the queue. >>> q = MappedQueue([916, 50, 4609, 493, 237]) >>> q.remove(493) >>> q.update(237, 1117) >>> x = [q.pop() for i in range(len(q.h))] >>> x [50, 916, 1117, 4609] References ---------- .. [1] Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2001). Introduction to algorithms second edition. .. [2] Knuth, D. E. (1997). The art of computer programming (Vol. 3). Pearson Education. """ def __init__(self, data=[]): """Priority queue class with updatable priorities. """ self.h = list(data) self.d = dict() self._heapify() def __len__(self): return len(self.h) def _heapify(self): """Restore heap invariant and recalculate map.""" heapq.heapify(self.h) self.d = dict([(elt, pos) for pos, elt in enumerate(self.h)]) if len(self.h) != len(self.d): raise AssertionError("Heap contains duplicate elements") def push(self, elt): """Add an element to the queue.""" # If element is already in queue, do nothing if elt in self.d: return False # Add element to heap and dict pos = len(self.h) self.h.append(elt) self.d[elt] = pos # Restore invariant by sifting down self._siftdown(pos) return True def pop(self): """Remove and return the smallest element in the queue.""" # Remove smallest element elt = self.h[0] del self.d[elt] # If elt is last item, remove and return if len(self.h) == 1: self.h.pop() return elt # Replace root with last element last = self.h.pop() self.h[0] = last self.d[last] = 0 # Restore invariant by sifting up, then down pos = self._siftup(0) self._siftdown(pos) # Return smallest element return elt def update(self, elt, new): """Replace an element in the queue with a new one.""" # Replace pos = self.d[elt] self.h[pos] = new del self.d[elt] self.d[new] = pos # Restore invariant by sifting up, then down pos = self._siftup(pos) self._siftdown(pos) def remove(self, elt): """Remove an element from the queue.""" # Find and remove element try: pos = self.d[elt] del self.d[elt] except KeyError: # Not in queue raise # If elt is last item, remove and return if pos == len(self.h) - 1: self.h.pop() return # Replace elt with last element last = self.h.pop() self.h[pos] = last self.d[last] = pos # Restore invariant by sifting up, then down pos = self._siftup(pos) self._siftdown(pos) def _siftup(self, pos): """Move element at pos down to a leaf by repeatedly moving the smaller child up.""" h, d = self.h, self.d elt = h[pos] # Continue until element is in a leaf end_pos = len(h) left_pos = (pos << 1) + 1 while left_pos < end_pos: # Left child is guaranteed to exist by loop predicate left = h[left_pos] try: right_pos = left_pos + 1 right = h[right_pos] # Out-of-place, swap with left unless right is smaller if right < left: h[pos], h[right_pos] = right, elt pos, right_pos = right_pos, pos d[elt], d[right] = pos, right_pos else: h[pos], h[left_pos] = left, elt pos, left_pos = left_pos, pos d[elt], d[left] = pos, left_pos except IndexError: # Left leaf is the end of the heap, swap h[pos], h[left_pos] = left, elt pos, left_pos = left_pos, pos d[elt], d[left] = pos, left_pos # Update left_pos left_pos = (pos << 1) + 1 return pos def _siftdown(self, pos): """Restore invariant by repeatedly replacing out-of-place element with its parent.""" h, d = self.h, self.d elt = h[pos] # Continue until element is at root while pos > 0: parent_pos = (pos - 1) >> 1 parent = h[parent_pos] if parent > elt: # Swap out-of-place element with parent h[parent_pos], h[pos] = elt, parent parent_pos, pos = pos, parent_pos d[elt] = pos d[parent] = parent_pos else: # Invariant is satisfied break return pos ########################################################## ########################################################## ########################################################## from collections import Counter # from sortedcontainers import SortedList t = int(input()) DEBUG = False for asdasd in range(t): # with open('temp.txt', 'w') as file: # for i in range(1, 200001): # file.write(str(i) + ' ') # break n = int(input()) arr = [int(i) for i in input().split(" ")] # if n==200000: # DEBUG = True # if DEBUG and asdasd == 3: # arr.insert(0,n) # line = str(arr) # n = 400 # x = [line[i:i+n] for i in range(0, len(line), n)] # for asd in x: # print(asd) arr.sort(reverse = True) # print(arr) count = dict(Counter(arr)) edges = {} ########################################## # DOESNT REALLY WORK ########################################## # heads = set() # for x in count: # edges[x] = set() # heads_to_remove = set() # for head in heads: # if head % x == 0: # edges[x].update(edges[head]) # edges[x].add(head) # heads_to_remove.add(head) # heads -= heads_to_remove # heads.add(x) # # print(edges) # edges_copy = edges.copy() # for x, edge_set in edges.items(): # for e in edge_set: # edges_copy[e].add(x) # edges = edges_copy ############################################ print('x1') ########################################## # TRYING N^2 EDGEs ########################################## for x in count: edges[x] = set() count_list = list(count.items()) for i in range(len(count_list)): if i % 10 == 0: print(i/len(count_list)) for j in range(i+1, len(count_list)): if count_list[i][0] % count_list[j][0] == 0 or count_list[j][0] % count_list[i][0] == 0: edges[count_list[i][0]].add(count_list[j][0]) edges[count_list[j][0]].add(count_list[i][0]) ############################################ print('x2') edge_count = {} total_edges = 0 for x, edge_set in edges.items(): edge_count[x] = count[x]-1 for e in edge_set: edge_count[x] += count[e] total_edges += count[x] * edge_count[x] total_edges //= 2 NODE_VALUE = 1 N_EDGES = 0 # queue = SortedList(list(edge_count.items()), key=lambda x: -x[N_EDGES]) # for key, value in edge_count.items(): # edge_count[key] = value * count[key] queue = MappedQueue([(n_edges, node_value) for node_value, n_edges in edge_count.items()]) # print('edges:', edges) # print('edge_count:', edge_count) # print('total_edges', total_edges) # print() # print('queue:', queue) # print() remaining_nodes = n # print('total_edges:', total_edges, 'remaining_nodes:', remaining_nodes) # print() # print(count) while total_edges != remaining_nodes*(remaining_nodes-1)//2: small = queue.pop() # remaining_nodes -= count[small[NODE_VALUE]] remaining_nodes -= 1 # print('popping node:', small[NODE_VALUE], 'edges:', small[N_EDGES]) # print(queue) for e in edges[small[NODE_VALUE]]: # print('updating edge', e) # queue.remove((e, edge_count[e])) queue.remove((edge_count[e], e)) # print('rem2', count[e] * count[small[NODE_VALUE]]) # edge_count[e] -= count[e] * count[small[NODE_VALUE]] # total_edges -= count[e] * count[small[NODE_VALUE]] # print('decreasing edge', e, ' edges by', 1) edge_count[e] -= 1 # print('decreasing total edges by', count[e]) total_edges -= count[e] if count[small[NODE_VALUE]] == 1: edges[e].remove(small[NODE_VALUE]) # queue.add((e, edge_count[e])) queue.push((edge_count[e], e)) # Edges between nodes of same value t = count[small[NODE_VALUE]] # print('rem1', t*(t-1)//2) t2 = t-1 total_edges -= t2 # print(t, '(*) decreasing total edges by', t2) count[small[NODE_VALUE]] -= 1 if count[small[NODE_VALUE]] != 0: queue.push((small[N_EDGES]-1, small[NODE_VALUE])) # print(queue) # print('total_edges:', total_edges, 'remaining_nodes:', remaining_nodes) # print() print(n - remaining_nodes) ```
instruction
0
103,916
24
207,832
No
output
1
103,916
24
207,833
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict,Counter m=2*10**5+5 t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) c=Counter(a) greater_count=defaultdict(lambda: 0) #Stores number of numbers a given number(not necessarily in a) is greater than or equal to the numbers in a. greater_count[0]=c[0] for i in range(1,m+1): greater_count[i]=greater_count[i-1]+c[i] dp=[float('inf') for i in range(m+1)] for i in range(m,0,-1): dp[i]=n-greater_count[i-1] #number of numbers in a, strictly greater than i (this is worst case answer for the sublist consisting of all numbers in a >=i) for j in range(2*i,m,i): dp[i]=min(dp[i],dp[j]+greater_count[j-1]-greater_count[i]) #number of numbers in a, between (i,j) print(dp[1]) ```
instruction
0
103,917
24
207,834
No
output
1
103,917
24
207,835
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from math import sqrt, pi, ceil, log, inf, gcd, floor from itertools import combinations, permutations from bisect import * from fractions import Fraction from heapq import * from random import randint def main(): for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ma=max(a) b=[0]*(ma+1) for i in a: b[i]+=1 c=[] for i in range(1,ma+1): if b[i]: c.append(i) d = [0] * (ma + 1) d[c[-1]] =b[c[-1]] c.pop() c.reverse() ans=1 for i in range(len(c)): j=2*c[i] zz=0 while j<=ma: zz=max(zz,d[j]) j+=c[i] d[c[i]]=b[c[i]]+zz ans=max(ans,d[c[i]]) print(n-ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
instruction
0
103,918
24
207,836
No
output
1
103,918
24
207,837
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.
instruction
0
105,305
24
210,610
Tags: implementation, math Correct Solution: ``` a,b,c=map(int,input().split()) fu=0 fu=min(a//3,b//2,c//2) a-=3*fu b-=2*fu c-=2*fu x=[1,2,3,1,3,2,1] k=0 m=0 for i in range(len(x)): d=0 f=0 j=i a1=a b1=b c1=c z=1 while z==1: k=x[j] if (k==1)&(a1>0): a1-=1 d+=1 if (k==2)&(b1>0): b1-=1 d+=1 if (k==3)&(c1>0): c1-=1 d+=1 if d==f: z=0 else: f=d j+=1 j=j%7 if d>m: m=d print(7*fu+m) ```
output
1
105,305
24
210,611
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.
instruction
0
105,306
24
210,612
Tags: implementation, math Correct Solution: ``` def dfs(day_l,day_r,a,b,c): global span if day_l<1 or day_r>14: return if a<0 or b<0 or c<0: return #print(day_l,day_r,a,b,c) span=max(span,day_r-day_l+1) if day_l-1 in [1,4,7,8,11,14]: dfs(day_l-1,day_r,a-1,b,c) elif day_l-1 in [2,6,9,13]: dfs(day_l-1,day_r,a,b-1,c) elif day_l-1 in [3,5,10,12]: dfs(day_l-1,day_r,a,b,c-1) if day_r+1 in [1,4,7,8,11,14]: dfs(day_l,day_r+1,a-1,b,c) elif day_r+1 in [2,6,9,13]: dfs(day_l,day_r+1,a,b-1,c) elif day_r+1 in [3,5,10,12]: dfs(day_l,day_r+1,a,b,c-1) a,b,c=list(map(int,input().split())) weeks=min([a//3,b//2,c//2]) a-=weeks*3 b-=weeks*2 c-=weeks*2 if weeks>0: span=0 if a>0: day_min,day_max=7,7 dfs(7,7,a-1,b,c) ans1=7*weeks+span span=0 day_min,day_max=7,7 dfs(7,7,a-1+3,b+2,c+2) ans2=7*(weeks-1)+span print(max(ans1,ans2)) else: span=0 for i in [4,5,6,7]: day_min,day_max=i,i if i in [4,7]: dfs(i,i,a-1,b,c) elif i==6: dfs(i,i,a,b-1,c) else: dfs(i,i,a,b,c-1) print(span) ```
output
1
105,306
24
210,613
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.
instruction
0
105,307
24
210,614
Tags: implementation, math Correct Solution: ``` a, b, c = map(int, input().split()) x = min(a//3, b//2, c//2) a,b,c = a-3*x, b-2*x, c-2*x z = [1,1,2,3,1,3,2] m = 0 for i in range(7): lis = [0,a,b,c] j = i cnt = 0 while(lis[1]>=0 and lis[2]>=0 and lis[3]>=0): lis[z[j]] -= 1 j = (j+1)%7 cnt += 1 m = max(m,cnt-1) print(x*7+m) ```
output
1
105,307
24
210,615
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.
instruction
0
105,308
24
210,616
Tags: implementation, math Correct Solution: ``` a = [int(i) for i in input().split()] days = [0, 1, 2, 0, 2, 1, 0] week = min(a[0] // 3, a[1] // 2, a[2] // 2) a[0], a[1], a[2] = a[0] - week * 3, a[1] - week * 2, a[2] - week * 2 m = 0 for day in range(7): b = a.copy() c = 0 for this_day in range(7): if b[days[(day + this_day) % 7]] > 0: b[days[(day + this_day) % 7]] -= 1 c += 1 else: break if c > m: m = c print(m + week * 7) ```
output
1
105,308
24
210,617
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.
instruction
0
105,309
24
210,618
Tags: implementation, math Correct Solution: ``` a,b,c = map(int,input().strip().split()) ans = 0 basi = min(c//2,min(b//2,a//3)) #print(basi) aa = a- 3*basi bb = b - 2*basi cc = c - 2*basi mp = {0:'aa',1:'aa',2:'bb',3:'cc',4:'aa',5:'cc',6:'bb'} #print(aa,bb,cc) for i in range(7): aaa = aa bbb = bb ccc = cc an = 0 for j in range(i,i+15): if mp[j%7]=='aa': aaa-=1 if mp[j%7]=='bb': bbb-=1 if mp[j%7]=='cc': ccc-=1 if aaa<0 or bbb<0 or ccc<0: break else: an+=1 ans = max(ans,basi*7+an) print(ans) ```
output
1
105,309
24
210,619