text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Tags: brute force, implementation Correct Solution: ``` from collections import Counter n = int(input()) s = input() k = 0 for i in range(n-1): for j in range(i+2, n+1, 2): c = Counter(s[i:j]) k += (c['U']==c['D'] and c['R']==c['L']) print(k) ```
87,100
Provide tags and a correct Python 3 solution for this coding contest problem. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Tags: brute force, implementation Correct Solution: ``` def f(i, j): subs = s[i:j+1] return subs.count("L") == subs.count("R") and subs.count("U") == subs.count("D") n = int(input()) s = input() r = 0 for i in range(n): for j in range(i+1,n): if f(i, j): r += 1 print(r) ```
87,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Submitted Solution: ``` n = int(input()) string = input() c = [] for char in string: if char == 'U': c.append(1) if char == 'D': c.append(-1) if char == 'R': c.append(2000) if char == 'L': c.append(-2000) ans = 0 for k in range(2,len(c) + 1,2): #groups of odd lentgh can NOT sum to 0 for i in range(0,len(c) - k + 1): #print(c[i:i + k]) t = sum(c[i:i + k]) if t == 0: ans += 1 print(ans) ``` Yes
87,102
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Submitted Solution: ``` n = int(input()) c = input() s = 0 for i in range(n): for j in range(i + 1, n): x = 0 y = 0 sub = c[i : j + 1] for k in sub: if k == "L": x -= 1 elif k == "R": x += 1 elif k == "U": y += 1 else: y -= 1 if x == 0 and y == 0: s += 1 print(s) ``` Yes
87,103
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Submitted Solution: ``` n = int(input()) l = input() ans = 0 for i in range(2, n + 1): for j in range(n - i + 1): st = l[j : j + i] if st.count('L') == st.count('R') and st.count('U') == st.count('D'): ans += 1 print(ans) ``` Yes
87,104
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Submitted Solution: ``` import collections import math n = int(input()) s = input() ans = 0 for i in range(len(s)): for j in range(i, len(s)): t = s[i:j+1] if t.count('U') == t.count('D') and t.count('L') == t.count('R'): ans += 1 print(ans) ``` Yes
87,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Submitted Solution: ``` if __name__=='__main__': n=int(input()) s=input() i=0 ans=0 while(i<n): r,l,u,d=0,0,0,0 g=i while(g<n): if(s[g]=='R'): r+=1 elif(s[g]=='L'): l+=1 elif(s[g]=='U'): u+=1 elif(s[g]=='D'): d+=1 if(d==u and l ==r): print("i-> ",i," g-> ",g) ans+=1 g+=1 i+=1 print(ans) ``` No
87,106
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Submitted Solution: ``` n = int(input()) s = input() print(2) ``` No
87,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Submitted Solution: ``` #!/usr/bin/python3.5 n=int(input()) s=input() i,e=0,0 while i<n: k=i+1 while k<=n: c,d=0,0 for j in range(i,k): if s[j]=='U': c+=1 elif s[j]=='D': c-=1 elif s[j]=='R': d+=1 else: d-=1 if c==0 and c==0: e+=1 k+=1 i+=1 print(e) ``` No
87,108
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Calvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L' β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices. Input The first line of the input contains a single positive integer, n (1 ≀ n ≀ 200) β€” the number of commands. The next line contains n characters, each either 'U', 'R', 'D', or 'L' β€” Calvin's source code. Output Print a single integer β€” the number of contiguous substrings that Calvin can execute and return to his starting square. Examples Input 6 URLLDR Output 2 Input 4 DLUU Output 0 Input 7 RLRLRLR Output 12 Note In the first case, the entire source code works, as well as the "RL" substring in the second and third characters. Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result. Submitted Solution: ``` C=lambda x,y:x.count(y) def P(s): return C(s,"R")-C(s,"L")+1j*(C(s,"U")-C(s,"D")) n=int(input()) s=input() p=P(s) c=0 for z in range(0,n): for l in range(z+1,n+1): print(s[z:l],p,P(s[z:l]),p+P(s[z:l])) c+=p+P(s[z:l])==0 print(c) ``` No
87,109
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Tags: brute force, constructive algorithms, math Correct Solution: ``` n,a,b,c,d = map(int, input().split()) num = 0 i = 0 while n > i: i += 1 if i + b - c < 1 or i + b - c > n: continue if i + a - d < 1 or i + a - d > n: continue if i + a - d + b - c < 1 or i + a - d + b - c > n: continue num += 1 print(num * n) ```
87,110
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Tags: brute force, constructive algorithms, math Correct Solution: ``` import sys sys.stderr = sys.stdout def painting(n, a, b, c, d): lo = min(a+b, c+d, a+c, b+d) hi = max(a+b, c+d, a+c, b+d) delta = hi - lo return max(n - delta, 0) * n def main(): n, a, b, c, d = readinti() print(painting(n, a, b, c, d)) ########## def readint(): return int(input()) def readinti(): return map(int, input().split()) def readintt(): return tuple(readinti()) def readintl(): return list(readinti()) def readinttl(k): return [readintt() for _ in range(k)] def readintll(k): return [readintl() for _ in range(k)] def log(*args, **kwargs): print(*args, **kwargs, file=sys.__stderr__) if __name__ == '__main__': main() ```
87,111
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Tags: brute force, constructive algorithms, math Correct Solution: ``` n, a, b, c, d = map(int, input().split()) k = 0 for u in range(1, n + 1): v = u + b - c if (v >= 1) and (v <= n): z = a + v - d if (z >= 1) and (z <= n): y = c + z - b if (y >= 1) and (y <= n): u = d + y - a if (u >= 1) and (u <= n): k += 1 print(k * n) ```
87,112
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Tags: brute force, constructive algorithms, math Correct Solution: ``` n, a, b, c, d = map(int, input().split()) lo = min(a+b, a+c, c+d, b+d) hi = max(a+b, a+c, c+d, b+d) ans = 0 for x in range(1, n+1): ans += max(0, n-(hi-lo)) print(ans) ```
87,113
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Tags: brute force, constructive algorithms, math Correct Solution: ``` from re import * from sys import stderr def readint(): return int(input()) def readfloat(): return float(input()) def readarray(N, foo=input): return [foo() for i in range(N)] def readlinearray(foo=int): return map(foo, input().split()) def NOD(a, b): while b: a,b = b, a%b return a def gen_primes(max): primes = [1]*(max+1) for i in range(2, max+1): if primes[i]: for j in range(i+i, max+1, i): primes[j] = 0 primes[0] = 0 return [x for x in range(max+1) if primes[x]] def is_prime(N): i = 3 if not(N % 2): return 0 while i*i < N: if not(N % i): return 0 i += 3 return 1 n, a, b, c, d = readlinearray() maxx = min(n, n - b + c, n - a + d, n - a + c - b + d) minx = max(1, 1 - b + c, 1 - a + d, 1 - a + c - b + d) if maxx < minx: print(0) else: print((maxx - minx + 1) * n) ```
87,114
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Tags: brute force, constructive algorithms, math Correct Solution: ``` import math as m n,a,b,c,d=(map(int,input().split())) ans=0 for i in range(n): x=i+1 t=x+b-c curr=1 if t>=1 and t<=n: curr=1 else: curr=0 t=x+a-d if t>=1 and t<=n and curr!=0: curr=1 else: curr*=0 t=x+a+b-d-c if t>=1 and t<=n and curr!=0: curr=1 else: curr*=0 ans+=curr*n # print(x,curr) print(ans) ```
87,115
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Tags: brute force, constructive algorithms, math Correct Solution: ``` from collections import * n,a,b,c,d = list(map(int,input().split())) print((n-min(n,max(abs(a+b-c-d),abs(b-c),abs(a-d),abs(a+c-b-d))))*n) ```
87,116
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Tags: brute force, constructive algorithms, math Correct Solution: ``` n, a, b, c, d = map(int, input().split()) count = 0 for x in range(1, n + 1): w = x + c - b if w >= 1 and w <= n: y = a + w - d if y >= 1 and y <= n: z = a + x - d if z >= 1 and z <= n: count = count + 1 print(count * n) ```
87,117
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Submitted Solution: ``` n, a, b, c, d = map(int, input().split()) ans = 0 for centro in range(1, n+1): q1 = a + b + centro q2 = a + c + centro q3 = b + d + centro q4 = c + d + centro v = [q1, q2, q3, q4] v.sort() q_min = v[0] q_max = v[-1] if q_min + n < q_max + 1: continue elif q_min + n == q_max + 1: ans += 1 else: ans += (q_min + n) - (q_max + 1) + 1 print(ans) ``` Yes
87,118
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Submitted Solution: ``` import sys,os,io import math,bisect,operator inf,mod = float('inf'),10**9+7 # sys.setrecursionlimit(10 ** 6) from itertools import groupby,accumulate from heapq import heapify,heappop,heappush from collections import deque,Counter,defaultdict input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ Neo = lambda : list(map(int,input().split())) # test, = Neo() n,a,b,c,d = Neo() Ans = 0 for i in range(1,n+1): p = i+a+b q = p-a-c r = p-b-d s = p-c-d if 1<=q<=n and 1<=r<=n and 1<=s<=n: Ans += 1 print(n*Ans) ``` Yes
87,119
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Submitted Solution: ``` n, a, b, c, d = map(int, input().split()) ans = n * (n - abs(a - d) - abs(b - c)) print(max(0, ans)) ``` Yes
87,120
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Submitted Solution: ``` n,a,b,c,d=tuple(map(int,input().split())) ans=0 sum=0 def ch(c): return (n>=c and c>0) for i in range(1,n+1): sum=i+a+b x2=sum-a-c x3=sum-c-d x4=sum-b-d if ch(i) and ch(x2) and ch(x3) and ch(x4): ans+=1 print(ans*n) ``` Yes
87,121
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Submitted Solution: ``` n,a,b,c,d=map(int,input().split()) print((max(a+b+1,b+c+1,c+d+1,a+d+1)-min(a+b+n,b+c+n,c+d+n,d+a+n)+1)*n) ``` No
87,122
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Submitted Solution: ``` nabcd = list(map(int, input().split())) RANGE = range(1,nabcd[0]) a = nabcd[1] b = nabcd[2] c = nabcd[3] d = nabcd[4] dif1 = a-d dif2 = b-c dif = abs(dif1) + abs(dif2) counter = nabcd[0]*(nabcd[0]-dif) print(counter) ``` No
87,123
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Submitted Solution: ``` n, a, b, c, d = map(int, input().split()) ans = 0 l = [a+b, a+c, b+d, d+c] sum = (min(l)+n)-(max(l)+1)+1 ans = sum*n print(ans) ``` No
87,124
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. * The painting is a square 3 Γ— 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. * The sum of integers in each of four squares 2 Γ— 2 is equal to the sum of integers in the top left square 2 Γ— 2. * Four elements a, b, c and d are known and are located as shown on the picture below. <image> Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong. Two squares are considered to be different, if there exists a cell that contains two different integers in different squares. Input The first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n) β€” maximum possible value of an integer in the cell and four integers that Vasya remembers. Output Print one integer β€” the number of distinct valid squares. Examples Input 2 1 1 1 2 Output 2 Input 3 3 1 2 3 Output 6 Note Below are all the possible paintings for the first sample. <image> <image> In the second sample, only paintings displayed below satisfy all the rules. <image> <image> <image> <image> <image> <image> Submitted Solution: ``` n, a, b, c, d = map(int, input().split()) ans = 0 if n >= 10 : ans = 0 else : S1 = set([a,b,c,d]) for i in range(1, n+1) : s = a+b+i j = s - a - c k = s - b - d l = s - c - d if 1 <= j <=n and 1<= k <= n and 1<= l <= n : S2 = set([i, j, k, l]) if len(S1 | S2) == n : ans += n elif len(S1 | S2) == n-1 : ans += 1 print(ans) ``` No
87,125
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Tags: dp Correct Solution: ``` import sys from functools import lru_cache from collections import defaultdict possible = { 0: {'r'}, 1: {'r', 'c'}, 2: {'r', 'g'}, 3: {'r', 'c', 'g'} } @lru_cache(maxsize=None) def min_rest(i, prev_action): if i == len(arr): return 0 # At least one elem in the arr. p = possible[arr[i]] best = float("inf") for act in p: if act == 'r': # Can always rest, no restrictions. best = min(best, 1 + min_rest(i + 1, 'r')) elif act != prev_action: best = min(best, min_rest(i + 1, act)) return best def iterative(arr): DP = defaultdict(int) for i in range(len(arr) - 1, -1, -1): p = possible[arr[i]] for prev_act in ('r', 'c', 'g'): best = float("inf") for act in p: if act == 'r': # Can always rest, no restrictions. best = min(best, 1 + DP[('r', i + 1)]) elif act != prev_act: best = min(best, DP[act, i + 1]) DP[(prev_act, i)] = best return DP[('r', 0)] if __name__ == "__main__": mat = [] for e, line in enumerate(sys.stdin.readlines()): if e == 0: continue arr = list(map(int, line.strip().split())) # print(min_rest(0, 'r')) print(iterative(arr)) ```
87,126
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Tags: dp Correct Solution: ``` days = int(input()) lst = list(map(int,input().split())) rest, gym, cont = [0], [0], [0] if lst[0] in (1,3): cont = [1] if lst[0] in (2,3): gym = [1] for i in range(1,days): rest.append(max(rest[-1],gym[-1],cont[-1])) if lst[i] == 3: cont.append(max(rest[-2],gym[-1])+1) gym.append(max(rest[-2],cont[-2])+1) elif lst[i] == 1: cont.append(max(rest[-2],gym[-1])+1) elif lst[i] == 2: gym.append(max(rest[-2],cont[-1])+1) #print(rest,gym,cont) print(days-max(rest[-1],gym[-1],cont[-1])) ```
87,127
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Tags: dp Correct Solution: ``` n = int(input()) a = list(map(int, input().split(' '))) dp = [[0 for i in range(3)] for _ in range(102)] for i in range(1, n + 1): if a[i - 1] == 0: dp[i][0] = min(dp[i - 1]) + 1 dp[i][1] = dp[i - 1][1] + 1 dp[i][2] = dp[i - 1][2] + 1 elif a[i - 1] == 1: dp[i][0] = min(dp[i - 1]) + 1 dp[i][1] = min(dp[i - 1][0], dp[i - 1][2]) dp[i][2] = dp[i- 1][2] + 1 elif a[i - 1] == 2: dp[i][0] = min(dp[i - 1]) + 1 dp[i][1] = dp[i - 1][1] + 1 dp[i][2] = min(dp[i - 1][0], dp[i - 1][1]) elif a[i - 1] == 3: dp[i][0] = min(dp[i - 1]) + 1 dp[i][2] = min(dp[i - 1][0], dp[i - 1][1]) dp[i][1] = min(dp[i - 1][0], dp[i - 1][2]) print(min(dp[n])) ```
87,128
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Tags: dp Correct Solution: ``` a = int(input()) days = [int(x) for x in input().split()] dp = [[666, 666, 666] for i in range(a)] if days[0] == 3: dp[0][0] = 0 dp[0][1] = 0 dp[0][2] = 0 else: dp[0][0], dp[0][days[0]] = 0, 0 dp[0][0] += 1 for x in range(1, a): dp[x][0] = min(dp[x - 1][:]) + 1 if days[x] == 3: dp[x][1] = min(dp[x - 1][0], dp[x - 1][2]) dp[x][2] = min(dp[x - 1][0], dp[x - 1][1]) elif days[x] == 2: dp[x][2] = min(dp[x - 1][0], dp[x - 1][1]) elif days[x] == 1: dp[x][1] = min(dp[x - 1][0], dp[x - 1][2]) print(min(dp[a - 1][:])) ```
87,129
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Tags: dp Correct Solution: ``` n = int(input()) arr = list(map(lambda x: int(x), input().split(" "))) dp = [[None] * n for _ in range(3)] first = arr[0] dp[0][0] = 1 if first == 1: dp[1][0] = 0 if first == 2: dp[2][0] = 0 if first == 3: dp[1][0] = 0 dp[2][0] = 0 for c in range(1, n): val = arr[c] cand = [dp[0][c-1], dp[1][c-1], dp[2][c-1]] cand = list(filter(lambda x: x != None, cand)) dp[0][c] = 1+min(cand) if val == 1 or val == 3: cand = [dp[0][c-1], dp[2][c-1]] cand = list(filter(lambda x: x != None, cand)) dp[1][c] = min(cand) if val == 2 or val == 3: cand = [dp[0][c-1], dp[1][c-1]] cand = list(filter(lambda x: x != None, cand)) dp[2][c] = min(cand) cand = [dp[0][-1], dp[1][-1], dp[2][-1]] #print(dp) print(min(filter(lambda x: x != None, cand))) ```
87,130
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Tags: dp Correct Solution: ``` def get_ints(string): return list(map(int, string.split())) def get_input(): n = int(input()) xs = get_ints(input()) return n, xs def foo(xs, res, last): # print(xs) if len(xs) is []: return res for i, x in enumerate(xs): if x == 0: res += 1 last = 0 elif x == 1 and last == 1: res += 1 last = 0 elif x == 1: last = 1 elif x == 2 and last == 2: res += 1 last = 0 elif x == 2: last = 2 else: if last == 1: last = 2 elif last == 2: last = 1 elif i < len(xs)-1 and xs[i+1] == 0: last = 1 else: return min(foo(xs[i+1:], res, 1), foo(xs[i+1:], res, 2)) return res def main(): n, xs = get_input() res = foo(xs, 0, 0) print(res) return res if __name__ == '__main__': main() ```
87,131
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Tags: dp Correct Solution: ``` n = int(input()) a = [int(i) for i in input().split()] dp = [[0]*(n+1), [0]*(n+1), [0]*(n+1)] INF = 1e9 for i in range(1, n + 1): dp[0][i] = min(dp[0][i - 1], dp[1][i - 1], dp[2][i - 1]) + 1 if a[i - 1] == 0: dp[1][i] = INF dp[2][i] = INF elif a[i - 1] == 1: dp[1][i] = min(dp[0][i - 1], dp[2][i - 1]) dp[2][i] = INF elif a[i - 1] == 2: dp[1][i] = INF dp[2][i] = min(dp[0][i - 1], dp[1][i - 1]) elif a[i - 1] == 3: dp[1][i] = min(dp[0][i - 1], dp[2][i - 1]) dp[2][i] = min(dp[0][i - 1], dp[1][i - 1]) print(min(dp[0][n], dp[1][n], dp[2][n])) ```
87,132
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Tags: dp Correct Solution: ``` n = int(input()) ai = list(map(int,input().split())) for i in range(n): if i < n-1: if ai[i] % 3 != 0 and ai[i] == ai[i+1]: ai[i+1] = 0 elif ai[i+1] == 3 and ai[i] % 3 != 0: ai[i+1] = 3 - ai[i] ai[i] = int(ai[i] > 0) print(n - sum(ai)) ```
87,133
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Submitted Solution: ``` import math n = int(input()) arr = list(map(int,input().split())) dp = [[float("inf") for _ in range(n+1)] for j in range(3)] for i in range(3): dp[i][0] = 0 for idx in range(1,n+1): # print(f"idx = {idx} day = {arr[idx-1]}") # print('\n'.join([''.join(['{:4}'.format(item) for item in row]) # for row in dp])) day = arr[idx-1] dp[0][idx] = min([dp[0][idx-1],dp[1][idx-1],dp[2][idx-1]])+1 if day == 1 or day ==3: dp[1][idx] = min(dp[0][idx-1],dp[2][idx-1]) if day == 2 or day == 3: dp[2][idx] = min(dp[0][idx-1],dp[1][idx-1]) # print("------------------------------------------------") # print('\n'.join([''.join(['{:4}'.format(item) for item in row]) # for row in dp])) #print(dp) ans = float("inf") for i in range(3): ans = min(ans,dp[i][n]) print(ans) ``` Yes
87,134
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Submitted Solution: ``` n = int(input()) list1 = [int(i)for i in input().split()] dp = [] for x in range(n): dp.append([10**9,10**9,10**9]) dp[0][0]=1 if list1[0]==0: dp[0][1]=1 dp[0][2]=1 elif list1[0]==1: dp[0][1]=0 dp[0][2]=1 elif list1[0]==2: dp[0][1]=1 dp[0][2]=0 else: dp[0][1]=0 dp[0][2]=0 for x in range(1,n): dp[x][0]=1+min([dp[x-1][0],dp[x-1][1],dp[x-1][2]]) if list1[x]==0: dp[x][1]=1+min([dp[x-1][0],dp[x-1][1],dp[x-1][2]]) dp[x][2]=1+min([dp[x-1][0],dp[x-1][1],dp[x-1][2]]) elif list1[x]==1: dp[x][1]=min([dp[x-1][0],dp[x-1][2]]) dp[x][2]=1+min([dp[x-1][0],dp[x-1][1],dp[x-1][2]]) elif list1[x]==2: dp[x][1]=1+min([dp[x-1][0],dp[x-1][1],dp[x-1][2]]) dp[x][2]=min([dp[x-1][0],dp[x-1][1]]) else: dp[x][1]=min([dp[x-1][0],dp[x-1][2]]) dp[x][2]=min([dp[x-1][0],dp[x-1][1]]) print(min([dp[n-1][0],dp[n-1][1],dp[n-1][2]])) ``` Yes
87,135
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Submitted Solution: ``` n = int(input()) nums = input() nums = [int(i) for i in nums.split()] MAXVAL = 999 dp = [[MAXVAL for i in range(3)] for i in range(n)] if nums[0] == 0: dp[0][0] = 1 elif nums[0] == 1: dp[0][1] = 0 elif nums[0] == 2: dp[0][2] = 0 else: dp[0][1] = 0 # if both, CONTEST dp[0][2] = 0 # if both, GYM #print(dp) for i in range(1,n): if nums[i] == 0: dp[i][0] = min(dp[i-1]) + 1 elif nums[i] == 1: # Do contest dp[i][1] = min(dp[i-1][0], dp[i-1][2]) + 0 # Rest dp[i][0] = min(dp[i-1][0], dp[i-1][1], dp[i-1][2]) + 1 elif nums[i] == 2: # Do gym dp[i][2] = min(dp[i-1][0], dp[i-1][1]) + 0 # Rest dp[i][0] = min(dp[i-1][0], dp[i-1][1], dp[i-1][2]) + 1 else: # Rest dp[i][0] = min(dp[i-1][0], dp[i-1][1], dp[i-1][2]) + 1 # Do gym dp[i][2] = min(dp[i-1][0], dp[i-1][1]) + 0 # Do contest dp[i][1] = min(dp[i-1][0], dp[i-1][2]) + 0 #print(dp) ans = min(dp[n-1]) print(ans) ``` Yes
87,136
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Submitted Solution: ``` z,zz=input,lambda:list(map(int,z().split())) fast=lambda:stdin.readline().strip() zzz=lambda:[int(i) for i in stdin.readline().split()] szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz()) from string import * from re import * from collections import * from queue import * from sys import * from collections import * from math import * from heapq import * from itertools import * from bisect import * from collections import Counter as cc from math import factorial as f from bisect import bisect as bs from bisect import bisect_left as bsl from itertools import accumulate as ac def lcd(xnum1,xnum2):return (xnum1*xnum2//gcd(xnum1,xnum2)) def prime(x): p=ceil(x**.5)+1 for i in range(2,p): if (x%i==0 and x!=2) or x==0:return 0 return 1 def dfs(u,visit,graph): visit[u]=True for i in graph[u]: if not visit[i]: dfs(i,visit,graph) ###########################---Test-Case---################################# """ """ ###########################---START-CODING---############################## n=int(z()) arr=zzz() dp=[[10**9]*3 for _ in range(n+1)] dp[0][0]=0 for i in range(n): k=arr[i] dp[i+1][0]=min(dp[i][2],dp[i][1],dp[i][0])+1 if k==1: dp[i+1][1]=min(dp[i][0],dp[i][2]) if k==2: dp[i+1][2]=min(dp[i][0],dp[i][1]) if k==3: dp[i+1][1]=min(dp[i][0],dp[i][2]) dp[i+1][2]=min(dp[i][0],dp[i][1]) print(min(dp[n])) ``` Yes
87,137
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Submitted Solution: ``` n = int(input()) c = [int(x) for x in input().split(' ')] a = [(2, -1)] b = [(1, -1)] for i in range(n): if c[i] == 0: pass elif c[i] == 1 or c[i] == 2: if a[-1][0] != c[i]: a.append((c[i], i)) if b[-1][0] != c[i]: b.append((c[i], i)) else: a.append((2, i) if a[-1][0] == 1 else (1, i)) b.append((2, i) if b[-1][0] == 1 else (1, i)) #print(a, b) print( n - max(len(a), len(b)) + 1) ``` No
87,138
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Submitted Solution: ``` n=int(input()) s=input().split() aflag=0 bflag=0 ans=0 for i in range(n): if s[i]=='0': ans+=1;aflag=0;bflag=0 elif s[i]=='1': if aflag==1: ans+=1;aflag=0;bflag=0 else: aflag=1;bflag=0 elif s[i]=='2': if bflag==1: ans+=1;aflag=0;bflag=0 else: bflag=1;aflag=0 else: if aflag==1: bflag=1;aflag=0 else: aflag=1;bflag=0 print(ans) ``` No
87,139
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Submitted Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 10**9 + 7 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').split(' ')] def li3():return [int(i) for i in input().rstrip('\n')] n = val() l = li() dp = [[0 for i in range(2)] for j in range(n)] dp[0][0] = 1 if l[0]>1 else 0 dp[0][1] = 1 if l[0]&1 else 0 ans = 0 if dp[0][0] == 0 and dp[0][1] == 0:ans = 1 currmax = ans for i in range(1,n): if not dp[i-1][0] and l[i] > 1:dp[i][0] = 1 if not dp[i-1][1] and l[i]&1:dp[i][1] = 1 if sum(dp[i]) == 0:ans += 1 else:ans = 0 currmax = max(ans,currmax) print(currmax) ``` No
87,140
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and the contest is not carried out; 2. on this day the gym is closed and the contest is carried out; 3. on this day the gym is open and the contest is not carried out; 4. on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day). Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β€” he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days. Input The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 3) separated by space, where: * ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out; * ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out; * ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out; * ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out. Output Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses: * to do sport on any two consecutive days, * to write the contest on any two consecutive days. Examples Input 4 1 3 2 0 Output 2 Input 7 1 3 3 2 1 2 3 Output 0 Input 2 2 2 Output 1 Note In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days. In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day. In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day. Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) count = 0 prev = 0 f=0 for i in range(n): if a[i] == 0: count+=1 prev = 0 if a[i] == 1 or a[i] == 2: if prev == a[i]: count+=1 prev = 0 prev = a[i] if a[i] == 3: if prev != 3 and prev != 0: prev = 3-prev else: prev = 3 print(count) ``` No
87,141
Provide tags and a correct Python 3 solution for this coding contest problem. There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of k atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized. Output If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line Β«YESΒ», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples. Examples Input 10 3 Mn Co Li Mg C P F Zn Sc K Sn Pt Y Output YES Mn+C+K-&gt;Sn Co+Zn+Sc-&gt;Pt Li+Mg+P+F-&gt;Y Input 2 1 H H He Output YES H+H-&gt;He Input 2 2 Bk Fm Cf Es Output NO Note The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <image> <image> <image> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints. Tags: bitmasks, dp Correct Solution: ``` numbersDict = { "1": "H", "2": "He", "3": "Li", "4": "Be", "5": "B", "6": "C", "7": "N", "8": "O", "9": "F", "10": "Ne", "11": "Na", "12": "Mg", "13": "Al", "14": "Si", "15": "P", "16": "S", "17": "Cl", "18": "Ar", "19": "K", "20": "Ca", "21": "Sc", "22": "Ti", "23": "V", "24": "Cr", "25": "Mn", "26": "Fe", "27": "Co", "28": "Ni", "29": "Cu", "30": "Zn", "31": "Ga", "32": "Ge", "33": "As", "34": "Se", "35": "Br", "36": "Kr", "37": "Rb", "38": "Sr", "39": "Y", "40": "Zr", "41": "Nb", "42": "Mo", "43": "Tc", "44": "Ru", "45": "Rh", "46": "Pd", "47": "Ag", "48": "Cd", "49": "In", "50": "Sn", "51": "Sb", "52": "Te", "53": "I", "54": "Xe", "55": "Cs", "56": "Ba", "57": "La", "58": "Ce", "59": "Pr", "60": "Nd", "61": "Pm", "62": "Sm", "63": "Eu", "64": "Gd", "65": "Tb", "66": "Dy", "67": "Ho", "68": "Er", "69": "Tm", "70": "Yb", "71": "Lu", "72": "Hf", "73": "Ta", "74": "W", "75": "Re", "76": "Os", "77": "Ir", "78": "Pt", "79": "Au", "80": "Hg", "81": "Tl", "82": "Pb", "83": "Bi", "84": "Po", "85": "At", "86": "Rn", "87": "Fr", "88": "Ra", "89": "Ac", "90": "Th", "91": "Pa", "92": "U", "93": "Np", "94": "Pu", "95": "Am", "96": "Cm", "97": "Bk", "98": "Cf", "99": "Es", "100": "Fm" } lettersDict = { "H": "1", "He": "2", "Li": "3", "Be": "4", "B": "5", "C": "6", "N": "7", "O": "8", "F": "9", "Ne": "10", "Na": "11", "Mg": "12", "Al": "13", "Si": "14", "P": "15", "S": "16", "Cl": "17", "Ar": "18", "K": "19", "Ca": "20", "Sc": "21", "Ti": "22", "V": "23", "Cr": "24", "Mn": "25", "Fe": "26", "Co": "27", "Ni": "28", "Cu": "29", "Zn": "30", "Ga": "31", "Ge": "32", "As": "33", "Se": "34", "Br": "35", "Kr": "36", "Rb": "37", "Sr": "38", "Y": "39", "Zr": "40", "Nb": "41", "Mo": "42", "Tc": "43", "Ru": "44", "Rh": "45", "Pd": "46", "Ag": "47", "Cd": "48", "In": "49", "Sn": "50", "Sb": "51", "Te": "52", "I": "53", "Xe": "54", "Cs": "55", "Ba": "56", "La": "57", "Ce": "58", "Pr": "59", "Nd": "60", "Pm": "61", "Sm": "62", "Eu": "63", "Gd": "64", "Tb": "65", "Dy": "66", "Ho": "67", "Er": "68", "Tm": "69", "Yb": "70", "Lu": "71", "Hf": "72", "Ta": "73", "W": "74", "Re": "75", "Os": "76", "Ir": "77", "Pt": "78", "Au": "79", "Hg": "80", "Tl": "81", "Pb": "82", "Bi": "83", "Po": "84", "At": "85", "Rn": "86", "Fr": "87", "Ra": "88", "Ac": "89", "Th": "90", "Pa": "91", "U": "92", "Np": "93", "Pu": "94", "Am": "95", "Cm": "96", "Bk": "97", "Cf": "98", "Es": "99", "Fm": "100" } _ = input() # Supposed to be n, k but we do not need them atoms = input().split(" ") outAtoms = input().split(" ") atoms = sorted(list(map(lambda x: int(lettersDict[x]), atoms))) outAtoms = sorted(list(map(lambda x: int(lettersDict[x]), outAtoms))) sumAtoms = 0 def testIfPossible(): atomsx = atoms.copy() outAtomsx = outAtoms.copy() for i in range(len(atoms) - 1, -1, -1): if atomsx[i] > outAtomsx[-1]: atomsx.pop() if sum(outAtomsx) > sum(atomsx): print("NO") exit() testIfPossible() for at in atoms: sumAtoms += at outAtom = 0 for at in outAtoms: outAtom += at def dfs(i: int, currentSum: int, arr: [int], searchSum: int) -> [[int]]: if i >= len(arr) or currentSum + arr[i] > searchSum: return [] totalRes = [] # we take res = dfs(i + 1, currentSum + arr[i], arr, searchSum) totalRes += [[i] + a for a in res] # we don't take res = dfs(i + 1, currentSum, arr, searchSum) totalRes += [a for a in res] if currentSum + arr[i] == searchSum: totalRes.append([i]) return totalRes allCombos = [[set(x) for x in dfs(0, 0, atoms, out)] for out in outAtoms] currentSet = set() stack = [] resultFound = False def dfs2(i: int): global resultFound global stack global currentSet if i >= len(allCombos): resultFound = True return for set in allCombos[i]: if not set & currentSet: stack.append(set) currentSet = currentSet | set dfs2(i + 1) if resultFound: break stack.pop() currentSet = currentSet - set isAnyEmpty = False for comb in allCombos: if not comb: isAnyEmpty = True if not isAnyEmpty: dfs2(0) if resultFound: print("YES") res = list(map(lambda x: "+".join(list(map(lambda y: numbersDict[f"{atoms[y]}"],list(x)))), stack)) outs = list(map(lambda x: numbersDict[f"{x}"], outAtoms)) tot = list(map(lambda x: x[0] + "->" + x[1], zip(res, outs))) for t in tot: print(t) else: print("NO") ```
87,142
Provide tags and a correct Python 3 solution for this coding contest problem. There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of k atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized. Output If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line Β«YESΒ», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples. Examples Input 10 3 Mn Co Li Mg C P F Zn Sc K Sn Pt Y Output YES Mn+C+K-&gt;Sn Co+Zn+Sc-&gt;Pt Li+Mg+P+F-&gt;Y Input 2 1 H H He Output YES H+H-&gt;He Input 2 2 Bk Fm Cf Es Output NO Note The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <image> <image> <image> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints. Tags: bitmasks, dp Correct Solution: ``` #!/usr/bin/env python3 import itertools # Initialize look-up tables element_to_value = { 'H':1, 'He':2, 'Li':3, 'Be':4, 'B':5, 'C':6, 'N':7, 'O':8, 'F':9, 'Ne':10, 'Na':11, 'Mg':12, 'Al':13, 'Si':14, 'P':15, 'S':16, 'Cl':17, 'Ar':18, 'K':19, 'Ca':20, 'Sc':21, 'Ti':22, 'V':23, 'Cr':24, 'Mn':25, 'Fe':26, 'Co':27, 'Ni':28, 'Cu':29, 'Zn':30, 'Ga':31, 'Ge':32, 'As':33, 'Se':34, 'Br':35, 'Kr':36, 'Rb':37, 'Sr':38, 'Y':39, 'Zr':40, 'Nb':41, 'Mo':42, 'Tc':43, 'Ru':44, 'Rh':45, 'Pd':46, 'Ag':47, 'Cd':48, 'In':49, 'Sn':50, 'Sb':51, 'Te':52, 'I':53, 'Xe':54, 'Cs':55, 'Ba':56, 'La':57, 'Ce':58, 'Pr':59, 'Nd':60, 'Pm':61, 'Sm':62, 'Eu':63, 'Gd':64, 'Tb':65, 'Dy':66, 'Ho':67, 'Er':68, 'Tm':69, 'Yb':70, 'Lu':71, 'Hf':72, 'Ta':73, 'W':74, 'Re':75, 'Os':76, 'Ir':77, 'Pt':78, 'Au':79, 'Hg':80, 'Tl':81, 'Pb':82, 'Bi':83, 'Po':84, 'At':85, 'Rn':86, 'Fr':87, 'Ra':88, 'Ac':89, 'Th':90, 'Pa':91, 'U':92, 'Np':93, 'Pu':94, 'Am':95, 'Cm':96, 'Bk':97, 'Cf':98, 'Es':99, 'Fm':100 } value_to_element = dict() for (element, value) in element_to_value.items(): value_to_element[value] = element # Read inputs (n,k) = map(int,input().split()) products_start_str = input().split() products_end_str = input().split() # Translate elements to their values products_start = [element_to_value[elem] for elem in products_start_str] products_end = [element_to_value[elem] for elem in products_end_str] # Filter out duplicates; keep track of ingredient values and their number products_start.sort() ingredient_value = [] ingredient_count = [] for (key, lst) in itertools.groupby(products_start): ingredient_value.append(key) ingredient_count.append(len(list(lst))) nr_ingredients = len(ingredient_value) # Figure out the options for constructing the final products construction_options = [[] for i in range(k)] for combination in itertools.product(*[range(l+1) for l in ingredient_count]): value = sum(combination[i]*ingredient_value[i] for i in range(nr_ingredients)) if (value in products_end): for i in range(k): if products_end[i] == value: construction_options[i].append(combination) # Do a depth-first search on the construction options for a possible solution solution = [None for i in range(k)] def find_solution(used = [0 for i in range(nr_ingredients)], next = 0): if (next == k): return all(used[i] == ingredient_count[i] for i in range(nr_ingredients)) else: for option in construction_options[next]: usage = [used[i]+option[i] for i in range(nr_ingredients)] if all(used[i] <= ingredient_count[i] for i in range(nr_ingredients)): possible = find_solution(usage, next+1) if (possible): solution[next] = option return True return False possible = find_solution() # Print the answer if not possible: print("NO") exit() def combination_to_recipe(combination): recipe = [] for i in range(nr_ingredients): for j in range(combination[i]): recipe.append(value_to_element[ingredient_value[i]]) return recipe print("YES") for i in range(k): recipe = combination_to_recipe(solution[i]) print("%s->%s" % ("+".join(recipe),products_end_str[i])) ```
87,143
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of k atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized. Output If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line Β«YESΒ», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples. Examples Input 10 3 Mn Co Li Mg C P F Zn Sc K Sn Pt Y Output YES Mn+C+K-&gt;Sn Co+Zn+Sc-&gt;Pt Li+Mg+P+F-&gt;Y Input 2 1 H H He Output YES H+H-&gt;He Input 2 2 Bk Fm Cf Es Output NO Note The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <image> <image> <image> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints. Submitted Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') elem = ['*'] + ''' H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm'''.split() n, k = map(int, input().split()) a = [elem.index(e) for e in input().split()] b = [elem.index(e) for e in input().split()] req = [[] for _ in range(k)] for i in range(k): for bit in range(1 << n): if sum(a[j] for j in range(n) if (1 << j) & bit) == b[i]: req[i].append(bit) for i in range(k): req[i] = req[i][:50] dp = [array('i', [-1]) * (1 << n) for _ in range(k + 1)] dp[0][0] = 0 full_bit = (1 << n) - 1 bs_set = {0} for i in range(k): next_bs = set() for bitset in list(bs_set)[:15000]: if dp[i][bitset] != -1: for req_bit in req[i]: if not (bitset & req_bit): next_bs.add(bitset + req_bit) dp[i + 1][bitset | req_bit] = bitset bs_set = next_bs bitset = -1 for bit in range(1 << n): if dp[-1][bit] != -1: bitset = bit break if bitset == -1: print('NO') exit() ans = [] for i in range(k, 0, -1): prev = dp[i][bitset] delta = bitset - prev s = '+'.join(elem[a[j]] for j in range(n) if (1 << j) & delta) ans.append(s + '->' + elem[b[i - 1]]) bitset = prev print('YES') print(*reversed(ans), sep='\n') ``` No
87,144
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of k atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized. Output If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line Β«YESΒ», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples. Examples Input 10 3 Mn Co Li Mg C P F Zn Sc K Sn Pt Y Output YES Mn+C+K-&gt;Sn Co+Zn+Sc-&gt;Pt Li+Mg+P+F-&gt;Y Input 2 1 H H He Output YES H+H-&gt;He Input 2 2 Bk Fm Cf Es Output NO Note The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <image> <image> <image> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints. Submitted Solution: ``` numbersDict = { "1": "H", "2": "He", "3": "Li", "4": "Be", "5": "B", "6": "C", "7": "N", "8": "O", "9": "F", "10": "Ne", "11": "Na", "12": "Mg", "13": "Al", "14": "Si", "15": "P", "16": "S", "17": "Cl", "18": "Ar", "19": "K", "20": "Ca", "21": "Sc", "22": "Ti", "23": "V", "24": "Cr", "25": "Mn", "26": "Fe", "27": "Co", "28": "Ni", "29": "Cu", "30": "Zn", "31": "Ga", "32": "Ge", "33": "As", "34": "Se", "35": "Br", "36": "Kr", "37": "Rb", "38": "Sr", "39": "Y", "40": "Zr", "41": "Nb", "42": "Mo", "43": "Tc", "44": "Ru", "45": "Rh", "46": "Pd", "47": "Ag", "48": "Cd", "49": "In", "50": "Sn", "51": "Sb", "52": "Te", "53": "I", "54": "Xe", "55": "Cs", "56": "Ba", "57": "La", "58": "Ce", "59": "Pr", "60": "Nd", "61": "Pm", "62": "Sm", "63": "Eu", "64": "Gd", "65": "Tb", "66": "Dy", "67": "Ho", "68": "Er", "69": "Tm", "70": "Yb", "71": "Lu", "72": "Hf", "73": "Ta", "74": "W", "75": "Re", "76": "Os", "77": "Ir", "78": "Pt", "79": "Au", "80": "Hg", "81": "Tl", "82": "Pb", "83": "Bi", "84": "Po", "85": "At", "86": "Rn", "87": "Fr", "88": "Ra", "89": "Ac", "90": "Th", "91": "Pa", "92": "U", "93": "Np", "94": "Pu", "95": "Am", "96": "Cm", "97": "Bk", "98": "Cf", "99": "Es", "100": "Fm" } lettersDict = { "H": "1", "He": "2", "Li": "3", "Be": "4", "B": "5", "C": "6", "N": "7", "O": "8", "F": "9", "Ne": "10", "Na": "11", "Mg": "12", "Al": "13", "Si": "14", "P": "15", "S": "16", "Cl": "17", "Ar": "18", "K": "19", "Ca": "20", "Sc": "21", "Ti": "22", "V": "23", "Cr": "24", "Mn": "25", "Fe": "26", "Co": "27", "Ni": "28", "Cu": "29", "Zn": "30", "Ga": "31", "Ge": "32", "As": "33", "Se": "34", "Br": "35", "Kr": "36", "Rb": "37", "Sr": "38", "Y": "39", "Zr": "40", "Nb": "41", "Mo": "42", "Tc": "43", "Ru": "44", "Rh": "45", "Pd": "46", "Ag": "47", "Cd": "48", "In": "49", "Sn": "50", "Sb": "51", "Te": "52", "I": "53", "Xe": "54", "Cs": "55", "Ba": "56", "La": "57", "Ce": "58", "Pr": "59", "Nd": "60", "Pm": "61", "Sm": "62", "Eu": "63", "Gd": "64", "Tb": "65", "Dy": "66", "Ho": "67", "Er": "68", "Tm": "69", "Yb": "70", "Lu": "71", "Hf": "72", "Ta": "73", "W": "74", "Re": "75", "Os": "76", "Ir": "77", "Pt": "78", "Au": "79", "Hg": "80", "Tl": "81", "Pb": "82", "Bi": "83", "Po": "84", "At": "85", "Rn": "86", "Fr": "87", "Ra": "88", "Ac": "89", "Th": "90", "Pa": "91", "U": "92", "Np": "93", "Pu": "94", "Am": "95", "Cm": "96", "Bk": "97", "Cf": "98", "Es": "99", "Fm": "100" } _ = input() # Supposed to be n, k but we do not need them atoms = sorted(list(map(lambda x: int(lettersDict[x]), input().split(" ")))) outAtoms = sorted(list(map(lambda x: int(lettersDict[x]), input().split(" ")))) allStack = [] currentSet = set() stack = [] resultFound = False memo = set() cycles = 0 def dfs3(i: int, currentSum: int): global cycles cycles += 1 if cycles >= 250000: print("NO") exit() return global stack global allStack global currentSet global resultFound if i == len(outAtoms): resultFound = True return if currentSum > outAtoms[i]: return if currentSum == outAtoms[i]: previousStack = stack.copy() allStack.append(stack.copy()) stack = [] dfs3(i + 1, 0) if resultFound: return allStack.pop() stack = previousStack return for j in range(len(atoms)): if j in currentSet: continue currentSet.add(j) stack.append(j) dfs3(i, currentSum + atoms[j]) if resultFound: return currentSet.remove(j) stack.remove(j) dfs3(0, 0) if resultFound: print("YES") res = [[numbersDict[f"{atoms[s]}"] for s in st] for st in allStack] res = ["+".join(x) for x in res] outs = list(map(lambda x: numbersDict[f"{x}"], outAtoms)) tot = list(map(lambda x: x[0] + "->" + x[1], zip(res, outs))) for t in tot: print(t) else: print("NO") ``` No
87,145
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of k atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized. Output If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line Β«YESΒ», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples. Examples Input 10 3 Mn Co Li Mg C P F Zn Sc K Sn Pt Y Output YES Mn+C+K-&gt;Sn Co+Zn+Sc-&gt;Pt Li+Mg+P+F-&gt;Y Input 2 1 H H He Output YES H+H-&gt;He Input 2 2 Bk Fm Cf Es Output NO Note The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <image> <image> <image> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints. Submitted Solution: ``` en={'H': '1', 'He': '2', 'Li': '3', 'Be': '4', 'B': '5', 'C': '6', 'N': '7', 'O': '8', 'F': '9', 'Ne': '10', 'Na': '11', 'Mg': '12', 'Al': '13', 'Si': '14', 'P': '15', 'S': '16', 'Cl': '17', 'Ar': '18', 'K': '19', 'Ca': '20', 'Sc': '21', 'Ti': '22', 'V': '23', 'Cr': '24', 'Mn': '25', 'Fe': '26', 'Co': '27', 'Ni': '28', 'Cu': '29', 'Zn': '30', 'Ga': '31', 'Ge': '32', 'As': '33', 'Se': '34', 'Br': '35', 'Kr': '36', 'Rb': '37', 'Sr': '38', 'Y': '39', 'Zr': '40', 'Nb': '41', 'Mo': '42', 'Tc': '43', 'Ru': '44', 'Rh': '45', 'Pd': '46', 'Ag': '47', 'Cd': '48', 'In': '49', 'Sn': '50', 'Sb': '51', 'Te': '52', 'I': '53', 'Xe': '54', 'Cs': '55', 'Ba': '56', 'La': '57', 'Ce': '58', 'Pr': '59', 'Nd': '60', 'Pm': '61', 'Sm': '62', 'Eu': '63', 'Gd': '64', 'Tb': '65', 'Dy': '66', 'Ho': '67', 'Er': '68', 'Tm': '69', 'Yb': '70', 'Lu': '71', 'Hf': '72', 'Ta': '73', 'W': '74', 'Re': '75', 'Os': '76', 'Ir': '77', 'Pt': '78', 'Au': '79', 'Hg': '80', 'Tl': '81', 'Pb': '82', 'Bi': '83', 'Po': '84', 'At': '85', 'Rn': '86', 'Fr': '87', 'Ra': '88', 'Ac': '89', 'Th': '90', 'Pa': '91', 'U': '92', 'Np': '93', 'Pu': '94', 'Am': '95', 'Cm': '96', 'Bk': '97', 'Cf': '98', 'Es': '99', 'Fm': '100', 'Md': '101', 'No': '102', 'Lr': '103', 'Rf': '104', 'Db': '105', 'Sg': '106', 'Bh': '107', 'Hs': '108', 'Mt': '109', 'Ds ': '110', 'Rg ': '111', 'Cn ': '112', 'Nh': '113', 'Fl': '114', 'Mc': '115', 'Lv': '116', 'Ts': '117', 'Og': '118'} ne={en[x]:x for x in en} n,m=map(int,input().split()) e=[int(en[x])for x in input().split()] r=[int(en[x])for x in input().split()] print(e) a=1<<n ans=[] for q in r: for i in range(a): s=0 l=[] for j in range(n): if 1<<j&i: s+=e[j] l+=[ne[str(e[j])]] if s==q:ans+=[l];break if len(ans)==m: print('YES') for i in range(m): print('+'.join(ans[i])+'->'+ne[str(r[i])]) else:print('NO') ``` No
87,146
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is the following puzzle popular among nuclear physicists. A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements. You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times. The aim is getting a new pregiven set of k atoms. The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle. Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized. Output If it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line Β«YESΒ», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples. Examples Input 10 3 Mn Co Li Mg C P F Zn Sc K Sn Pt Y Output YES Mn+C+K-&gt;Sn Co+Zn+Sc-&gt;Pt Li+Mg+P+F-&gt;Y Input 2 1 H H He Output YES H+H-&gt;He Input 2 2 Bk Fm Cf Es Output NO Note The reactions from the first example possess the following form (the atomic number is written below and to the left of the element): <image> <image> <image> To find a periodic table of the chemical elements, you may use your favorite search engine. The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints. Submitted Solution: ``` import random from itertools import combinations, product from functools import reduce symbol_value = {'Br': 35, 'Pm': 61, 'At': 85, 'Xe': 54, 'Pu': 94, 'Tl': 81, 'Mg': 12, 'Fe': 26, 'Kr': 36, 'Ar': 18, 'I': 53, 'Ga': 31, 'Sn': 50, 'Pd': 46, 'Fr': 87, 'Lu': 71, 'Dy': 66, 'Ac': 89, 'Gd': 64, 'Nd': 60, 'Bk': 97, 'Sb': 51, 'H': 1, 'Al': 13, 'Mo': 42, 'Sr': 38, 'Re': 75, 'Es': 99, 'Au': 79, 'Ra': 88, 'Cu': 29, 'Ca': 20, 'Am': 95, 'Pa': 91, 'U': 92, 'Ti': 22, 'Y': 39, 'Ag': 47, 'Hg': 80, 'F': 9, 'Cd': 48, 'Cs': 55, 'Rh': 45, 'Os': 76, 'Pr': 59, 'Ni': 28, 'Bi': 83, 'La': 57, 'Ta': 73, 'S': 16, 'Ir': 77, 'Rn': 86, 'Zn': 30, 'Se': 34, 'Li': 3, 'Ge': 32, 'Cr': 24, 'W': 74, 'Cm': 96, 'Hf': 72, 'Fm': 100, 'In': 49, 'Si': 14, 'Cl': 17, 'Sc': 21, 'Tc': 43, 'V': 23, 'O': 8, 'Rb': 37, 'Np': 93, 'Mn': 25, 'Te': 52, 'Ba': 56, 'Tb': 65, 'Po': 84, 'B': 5, 'Ru': 44, 'Eu': 63, 'Na': 11, 'Ce': 58, 'Yb': 70, 'Ho': 67, 'Nb': 41, 'Er': 68, 'Co': 27, 'Zr': 40, 'Ne': 10, 'As': 33, 'Sm': 62, 'Pb': 82, 'K': 19, 'Tm': 69, 'C': 6, 'Cf': 98, 'P': 15, 'Pt': 78, 'Th': 90, 'He': 2, 'N': 7, 'Be': 4} value_symbol = {1: 'H', 2: 'He', 3: 'Li', 4: 'Be', 5: 'B', 6: 'C', 7: 'N', 8: 'O', 9: 'F', 10: 'Ne', 11: 'Na', 12: 'Mg', 13: 'Al', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl', 18: 'Ar', 19: 'K', 20: 'Ca', 21: 'Sc', 22: 'Ti', 23: 'V', 24: 'Cr', 25: 'Mn', 26: 'Fe', 27: 'Co', 28: 'Ni', 29: 'Cu', 30: 'Zn', 31: 'Ga', 32: 'Ge', 33: 'As', 34: 'Se', 35: 'Br', 36: 'Kr', 37: 'Rb', 38: 'Sr', 39: 'Y', 40: 'Zr', 41: 'Nb', 42: 'Mo', 43: 'Tc', 44: 'Ru', 45: 'Rh', 46: 'Pd', 47: 'Ag', 48: 'Cd', 49: 'In', 50: 'Sn', 51: 'Sb', 52: 'Te', 53: 'I', 54: 'Xe', 55: 'Cs', 56: 'Ba', 57: 'La', 58: 'Ce', 59: 'Pr', 60: 'Nd', 61: 'Pm', 62: 'Sm', 63: 'Eu', 64: 'Gd', 65: 'Tb', 66: 'Dy', 67: 'Ho', 68: 'Er', 69: 'Tm', 70: 'Yb', 71: 'Lu', 72: 'Hf', 73: 'Ta', 74: 'W', 75: 'Re', 76: 'Os', 77: 'Ir', 78: 'Pt', 79: 'Au', 80: 'Hg', 81: 'Tl', 82: 'Pb', 83: 'Bi', 84: 'Po', 85: 'At', 86: 'Rn', 87: 'Fr', 88: 'Ra', 89: 'Ac', 90: 'Th', 91: 'Pa', 92: 'U', 93: 'Np', 94: 'Pu', 95: 'Am', 96: 'Cm', 97: 'Bk', 98: 'Cf', 99: 'Es', 100: 'Fm'} def translate_tuple(t): return '+'.join(str(value_symbol[item]) for item in t) + '->' + value_symbol[sum(t)] def get_start_pos(n_values, k, number): pos = None for i, n in enumerate(n_values): if i < k - 1: # can be improved continue if number > k * n: continue tk = 1 total = n while tk < k: total += n_values[i - tk] tk += 1 if total > number: pos = i - k + 1 break return pos def find_valid_answer(alternatives): keys = alternatives.keys() for indices in product(*(range(len(alternatives[a])) for a in keys)): item = [alternatives[k][i] for k,i in zip(keys, indices)] expected_sum = sum(len(a) for a in item) if len(reduce(lambda a,b: a.union(b),item)) == expected_sum: return item return None while True: try: line = input() except: break n, k = map(int, line.split()) n_values = sorted([symbol_value[x] for x in input().strip().split()]) k_values = sorted([symbol_value[x] for x in input().strip().split()]) alternatives = {k:[] for k in k_values} sample = sorted(n_values) desired = set(k_values) stop = max(desired) for i in range(1,len(sample)+1): min = 100000 for comb in combinations(sample, i): current = sum(comb) if current < min: min = current sum_comb = sum(comb) if sum_comb in desired: alternatives[sum_comb].append(set(comb)) if min > stop: break answer = find_valid_answer(alternatives) if answer: print('YES') for i in answer: print(translate_tuple(i)) else: print('NO') ``` No
87,147
Provide tags and a correct Python 3 solution for this coding contest problem. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Tags: dfs and similar, dp, dsu Correct Solution: ``` def ler(): return [int(x) for x in input().split()] def dfs(u, adj, visited, s, Pesos, Belezas): visited[u] = True total_p = Pesos[u] total_b = Belezas[u] s.append(u) for v in adj[u]: if not visited[v]: w, b = dfs(v, adj, visited, s, Pesos, Belezas) total_p += w total_b += b return total_p, total_b n, m, w = ler() Pesos = ler() Belezas = ler() adj = [[] for _ in range(n)] for _ in range(m): x, y = ler() x -= 1 y -= 1 adj[x].append(y) adj[y].append(x) visited = [False] * n f = [0] * (w + 1) for i in range(n): if visited[i]: continue s = [] total_p, total_b = dfs(i, adj, visited, s, Pesos, Belezas) for j in range(w, -1, -1): jw = j + total_p if jw <= w: f[jw] = max(f[jw], f[j] + total_b) for v in s: jw = j + Pesos[v] if jw <= w: f[jw] = max(f[jw], f[j] + Belezas[v]) print(f[w]) ```
87,148
Provide tags and a correct Python 3 solution for this coding contest problem. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Tags: dfs and similar, dp, dsu Correct Solution: ``` from collections import defaultdict class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): group_members = defaultdict(list) for member in range(self.n): group_members[self.find(member)].append(member) return group_members n,m,w=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) uf=UnionFind(n) for _ in range(m): x,y=map(int,input().split()) uf.union(x-1,y-1) l=uf.roots() ll=len(l) dp=[[-10**18]*(w+1) for i in range(ll)] ca,cb=0,0 dp[0][0]=0 for x in uf.members(l[0]): if a[x]<=w: dp[0][a[x]]=max(dp[0][a[x]],b[x]) ca+=a[x] cb+=b[x] if ca<=w: dp[0][ca]=max(dp[0][ca],cb) for i in range(1,ll): ca,cb=0,0 for x in uf.members(l[i]): for j in range(w+1): dp[i][j]=max(dp[i][j],dp[i-1][j]) if j-a[x]>=0: dp[i][j]=max(dp[i][j],dp[i-1][j-a[x]]+b[x]) ca+=a[x] cb+=b[x] for j in range(w+1): if j-ca>=0: dp[i][j]=max(dp[i][j],dp[i-1][j],dp[i-1][j-ca]+cb) ans=0 for j in range(w+1): ans=max(ans,dp[ll-1][j]) print(ans) ```
87,149
Provide tags and a correct Python 3 solution for this coding contest problem. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Tags: dfs and similar, dp, dsu Correct Solution: ``` f = lambda: map(int, input().split()) n, m, w = f() wb = [(0, 0)] + list(zip(f(), f())) t = list(range(n + 1)) def g(x): if x == t[x]: return x t[x] = g(t[x]) return t[x] for i in range(m): x, y = f() x, y = g(x), g(y) if x != y: t[y] = x p = [[] for j in range(n + 1)] for i in range(1, n + 1): p[g(i)].append(i) d = [1] + [0] * w for q in p: if len(q) > 1: WB = [wb[i] for i in q] SW = sum(q[0] for q in WB) SB = sum(q[1] for q in WB) for D in range(w, -1, -1): if d[D]: if D + SW <= w: d[D + SW] = max(d[D + SW], d[D] + SB) for W, B in WB: if D + W <= w: d[D + W] = max(d[D + W], d[D] + B) elif len(q) == 1: W, B = wb[q[0]] for D in range(w - W, -1, -1): if d[D]: d[D + W] = max(d[D + W], d[D] + B) print(max(d) - 1) # Made By Mostafa_Khaled ```
87,150
Provide tags and a correct Python 3 solution for this coding contest problem. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Tags: dfs and similar, dp, dsu Correct Solution: ``` n, m, o = map(int, input().split()) wn = map(int, input().split()) bn = map(int, input().split()) wb = [(0, 0)] + list(zip(wn, bn)) l = list(range(n + 1)) def f(x): if x == l[x]: return x l[x] = f(l[x]) return l[x] for i in range(m): x, y = map(int, input().split()) x, y = f(x), f(y) if x != y: l[y] = x p = [[] for j in range(n + 1)] for i in range(1, n + 1): p[f(i)].append(i) r = (o+1) * [0] r[0] = 1 for i in p: if len(i) > 1: l = [wb[x] for x in i] x0 = sum(x[0] for x in l) x1 = sum(x[1] for x in l) l.append((x0, x1)) l.sort() for j in range(o, -1, -1): if r[j]: for w, b in l: if j + w > o: break r[j + w] = max(r[j + w], r[j] + b) elif len(i) == 1: w, b = wb[i[0]] for j in range(o - w, -1, -1): if r[j]: r[j + w] = max(r[j + w], r[j] + b) res = max(r) - 1 print(res) ```
87,151
Provide tags and a correct Python 3 solution for this coding contest problem. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Tags: dfs and similar, dp, dsu Correct Solution: ``` def g(x): if x == t[x]: return x t[x] = g(t[x]) return t[x] f = lambda: map(int, input().split()) hoses, pairOfFriends, weight = f() weightsAndBeauties = [(0, 0)] + list(zip(f(), f())) t = list(range(hoses + 1)) for i in range(pairOfFriends): f1, f2 = f() f1, f2 = g(f1), g(f2) if f1 != f2: t[f2] = f1 p = [[] for j in range(hoses + 1)] for i in range(1, hoses + 1): p[g(i)].append(i) beauties = [1] + [0] * weight for q in p: if len(q) > 1: t = [weightsAndBeauties[i] for i in q] t.append((sum(f1[0] for f1 in t), sum(f1[1] for f1 in t))) t.sort(key=lambda f1: f1[0]) for j in range(weight, -1, -1): if beauties[j]: for w, b in t: if j + w > weight: break else: beauties[j + w] = max(beauties[j + w], beauties[j] + b) elif len(q) == 1: w, b = weightsAndBeauties[q[0]] for j in range(weight - w, -1, -1): if beauties[j]: beauties[j + w] = max(beauties[j + w], beauties[j] + b) maxBeauty = max(beauties) - 1 print(maxBeauty) ```
87,152
Provide tags and a correct Python 3 solution for this coding contest problem. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Tags: dfs and similar, dp, dsu Correct Solution: ``` n, m, k = map(int, input().split()) a = map(int, input().split()) b = map(int, input().split()) ab = [(0, 0)] + list(zip(a, b)) l = list(range(n + 1)) def f(x): if x == l[x]: return x l[x] = f(l[x]) return l[x] for i in range(m): x, y = map(int, input().split()) x, y = f(x), f(y) if x != y: l[y] = x p = [[] for j in range(n + 1)] for i in range(1, n + 1): p[f(i)].append(i) r = (k+1) * [0] r[0] = 1 for i in p: if len(i) > 1: l = [ab[x] for x in i] x0 = sum(x[0] for x in l) x1 = sum(x[1] for x in l) l.append((x0, x1)) l.sort() for j in range(k, -1, -1): if r[j]: for w, b in l: if j + w > k: break r[j + w] = max(r[j + w], r[j] + b) elif len(i) == 1: w, b = ab[i[0]] for j in range(k - w, -1, -1): if r[j]: r[j + w] = max(r[j + w], r[j] + b) res = max(r) - 1 print(res) ```
87,153
Provide tags and a correct Python 3 solution for this coding contest problem. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Tags: dfs and similar, dp, dsu Correct Solution: ``` R = lambda: map(int, input().split()) n, m, w = R() ws = [0] + list(R()) bs = [0] + list(R()) g = [[] for x in range(n + 1)] for i in range(m): x, y = R() g[x].append(y) g[y].append(x) cs = [0] * (n + 1) cnt = 1 for i in range(1, n + 1): if not cs[i]: cs[i] = cnt q = [] q.append(i) while q: nxt = q.pop() for x in g[nxt]: if not cs[x]: cs[x] = cnt q.append(x) cnt += 1 gs = [[] for i in range(cnt)] for i in range(1, n + 1): gs[cs[i]].append(i) dp = [[0] * (w + 1) for i in range(cnt)] for i in range(1, cnt): tw = sum(ws[k] for k in gs[i]) tb = sum(bs[k] for k in gs[i]) for j in range(1, w + 1): dp[i][j] = max(dp[i][j], dp[i - 1][j], (dp[i - 1][j - tw] + tb if j >= tw else 0)) for k in gs[i]: dp[i][j] = max(dp[i][j], dp[i - 1][j], (dp[i - 1][j - ws[k]] + bs[k] if j >= ws[k] else 0)) print(dp[-1][w]) ```
87,154
Provide tags and a correct Python 3 solution for this coding contest problem. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Tags: dfs and similar, dp, dsu Correct Solution: ``` import math,sys,bisect,heapq,os from collections import defaultdict,Counter,deque from itertools import groupby,accumulate from functools import lru_cache #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 def input(): return sys.stdin.readline().rstrip('\r\n') #input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ aj = lambda: list(map(int, input().split())) def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) def solve(): G = defaultdict(list) def addEdge(a,b): G[a].append(b) G[b].append(a) def dfs(node): d = deque() d.append(node) vis[node] = True T = [] S = [] tot = 0;wt = 0 while d: x = d.pop() S.append(B[x-1]) T.append(W[x-1]) # tot += B[x-1] # wt += W[x-1] for i in G.get(x,[]): if not vis[i]: vis[i] = True d.append(i) # if len(S) > 1: # S.append(tot) # T.append(wt) return S,T n,m,w =aj() W = aj() B = aj() vis = [False]*(n+1) for i in range(m): u,v = aj() addEdge(u,v) A1 = [] A2 = [] Id = 1 for i in range(1,n+1): if not vis[i]: c,d = dfs(i) A1.append(c) A2.append(d) # print(A1) # print(A2) # print(w) # dp = {} # def fun(pos = 0,wt = 0): # if wt > w: # return -float('inf') # if pos >= len(A1): # return 0 # z = dp.get((pos,wt),-1) # if z!= -1: # return z # ans = 0 # c2 = 0 # for i in range(len(A1[pos])): # c2 = max(c2,A1[pos][i] + fun(pos+1,wt + A2[pos][i])) # c3 = fun(pos + 1,wt) # z = max(c2,c3) # dp[(pos,wt)] = z # return z dp = [[0]*(w+1) for i in range(len(A1)+1)] for i in range(len(A1)): weight_sum = sum(x for x in A2[i]) beauty_sum = sum(x for x in A1[i]) for j in range(w + 1): dp[i][j] = max(beauty_sum + dp[i - 1][j - weight_sum] if weight_sum <= j else 0, dp[i - 1][j]) for k in range(len(A1[i])): dp[i][j] = max(dp[i][j], (dp[i - 1][j - A2[i][k]] + A1[i][k] if A2[i][k] <= j else 0)) # print(fun()) print(dp[len(A1)-1][w]) try: #os.system("online_judge.py") sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') except: pass solve() ```
87,155
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Submitted Solution: ``` from sys import stdin, stdout from collections import defaultdict as dd read, write = stdin.readline, stdout.write class DisjointSetUnion: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n def find(self, a): acopy = a while a != self.parent[a]: a = self.parent[a] while acopy != a: self.parent[acopy], acopy = a, self.parent[acopy] return a def union(self, a, b): a, b = self.find(a), self.find(b) if a != b: if self.size[a] < self.size[b]: a, b = b, a self.num_sets -= 1 self.parent[b] = a self.size[a] += self.size[b] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets n, m, w = map(int, read().split()) weights = list(map(int, read().split())) beauties = list(map(int, read().split())) DSU = DisjointSetUnion(n) for _ in range(m): h1, h2 = map(int, read().split()) DSU.union(h1-1, h2-1) groups = dd(list) for i in range(n): DSU.find(i) for hose, parent in enumerate(DSU.parent): groups[parent].append(hose) dp = [0]*(w+1) for friends in groups.values(): dp_aux = dp[:] group_weight = group_beauty = 0 for friend in friends: f_weight, f_beauty = weights[friend], beauties[friend] group_weight += f_weight; group_beauty += f_beauty for weight in range(f_weight, w+1): dp[weight] = max(dp[weight], dp_aux[weight - f_weight] + f_beauty) for weight in range(group_weight, w+1): dp[weight] = max(dp[weight], dp_aux[weight - group_weight] + group_beauty) print(dp[-1]) ``` Yes
87,156
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Submitted Solution: ``` hoses, pairs, total_weight = map(int, input().split()) weight_arr = list(map(int, input().split())) beauty_arr = list(map(int, input().split())) arr = [-1] * hoses def get(hose): if arr[hose] < 0: return hose arr[hose] = get(arr[hose]) return arr[hose] def join(left, right): left, right = get(left), get(right) if left != right: arr[left] = right for i in range(pairs): left, right = map(int, input().split()) join(left - 1, right - 1) groups = [list() for i in range(hoses)] for i in range(hoses): groups[get(i)].append(i) groups = [group for group in groups if group] dp = [[0] * (total_weight + 1) for i in range(len(groups) + 1)] for i in range(len(groups)): weight_sum = sum(weight_arr[x] for x in groups[i]) beauty_sum = sum(beauty_arr[x] for x in groups[i]) for j in range(total_weight + 1): dp[i][j] = max(beauty_sum + dp[i - 1][j - weight_sum] if weight_sum <= j else 0, dp[i - 1][j]) for k in groups[i]: dp[i][j] = max(dp[i][j], (dp[i - 1][j - weight_arr[k]] + beauty_arr[k] if weight_arr[k] <= j else 0)) print(dp[len(groups) - 1][total_weight]) ``` Yes
87,157
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Submitted Solution: ``` n, m, wn = map(int, input().split()) Wi = [(0, 0)] + list(zip(map(int, input().split()), map(int, input().split()))) listaux3 = list(range(n + 1)) def aux(x): if x == listaux3[x]: return x listaux3[x] = aux(listaux3[x]) return listaux3[x] for i in range(m): x, y = map(int, input().split()) x, y = aux(x), aux(y) if x != y: listaux3[y] = x listaux1 = [[] for _ in range(n + 1)] for i in range(1, n + 1): listaux1[aux(i)].append(i) listaux2 = [1] + [0] * wn for k in listaux1: if len(k) > 1: listaux3 = [Wi[i] for i in k] listaux3.append((sum(x[0] for x in listaux3), sum(x[1] for x in listaux3))) listaux3.sort(key=lambda x: x[0]) for j in range(wn, -1, -1): if listaux2[j]: for w, b in listaux3: if j + w > wn: break listaux2[j + w] = max(listaux2[j + w], listaux2[j] + b) elif len(k) == 1: w, b = Wi[k[0]] for j in range(wn - w, -1, -1): if listaux2[j]: listaux2[j + w] = max(listaux2[j + w], listaux2[j] + b) print(max(listaux2) - 1) ``` Yes
87,158
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Submitted Solution: ``` class disjoint: def __init__(self,n): self.rank=[1]*n self.parent=[i for i in range(n)] def find(self,x): if(self.parent[x]!=x): self.parent[x]=self.find(self.parent[x]) return self.parent[x]; def union(self,x,y): xid=self.find(x) yid=self.find(y) if(xid==yid): return; if(self.rank[xid]<self.rank[yid]): self.parent[xid]=yid return; elif(self.rank[xid]>self.rank[yid]): self.parent[yid]=xid # merging y into x return; else: self.parent[yid]=xid self.rank[xid]+=1 return; import sys input=sys.stdin.readline n,m,w=map(int,input().split()) obj=disjoint(n) z=list(map(int,input().split())) be=list(map(int,input().split())) ans=[] for i in range(len(z)): ans.append([i,z[i],be[i]]) for i in range(m): p,q=map(int,input().split()) obj.union(p-1,q-1) from collections import * al=defaultdict(list) for i in range(len(ans)): y=obj.find(ans[i][0]) al[y].append(ans[i][0]) dp=[[0 for i in range(len(al)+1)] for i in range(w+1)] c1=0 maxa=0 for i in al: if(c1==0): q=al[i] total=0 bea=0 for x in q: wei=ans[x][1] if(wei<=w): dp[wei][c1]=max(dp[wei][c1],ans[x][2]) maxa=max(maxa,dp[wei][c1]) total+=wei bea+=ans[x][2] if(total<=w): dp[total][c1]=max(dp[total][c1],bea) maxa=max(maxa,dp[total][c1]) c1+=1 else: q=al[i] total=0 dil=0 bea=0 wei=0 for x in q: wei=ans[x][1] bea=ans[x][2] total+=wei dil+=bea for j in range(w+1): if(wei>j): dp[j][c1]=max(dp[j][c1-1],dp[j][c1]) maxa=max(maxa,dp[j][c1]) continue; else: dp[j][c1]=max(dp[j][c1],dp[j-wei][c1-1]+bea,dp[j][c1-1]) maxa=max(maxa,dp[j][c1]) if(total<=w): dp[total][c1]=max(dp[total][c1-1],dil,dp[total][c1]) maxa=max(maxa,dp[total][c1]) for j in range(w+1): if(j<=total): continue; else: dp[j][c1]=max(dp[j][c1],dil+dp[j-total][c1-1]) maxa=max(maxa,dp[j][c1]) c1+=1 print(maxa) ``` Yes
87,159
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Submitted Solution: ``` class disjoint: def __init__(self,n): self.rank=[1]*n self.parent=[i for i in range(n)] def find(self,x): if(self.parent[x]!=x): self.parent[x]=self.find(self.parent[x]) return self.parent[x]; def union(self,x,y): xid=self.find(x) yid=self.find(y) if(xid==yid): return; if(self.rank[xid]<self.rank[yid]): self.parent[xid]=yid return; elif(self.rank[xid]>self.rank[yid]): self.parent[yid]=xid # merging y into x return; else: self.parent[yid]=xid self.rank[xid]+=1 return; import sys input=sys.stdin.readline n,m,w=map(int,input().split()) obj=disjoint(n) z=list(map(int,input().split())) be=list(map(int,input().split())) ans=[] for i in range(len(z)): ans.append([i,z[i],be[i]]) for i in range(m): p,q=map(int,input().split()) obj.union(p-1,q-1) from collections import * al=defaultdict(list) for i in range(len(ans)): y=obj.find(ans[i][0]) al[y].append(ans[i][0]) dp=[[0 for i in range(len(al)+1)] for i in range(w+1)] c1=0 for i in al: if(c1==0): q=al[i] total=0 bea=0 for x in q: wei=ans[x][1] if(wei<=w): dp[wei][c1]=max(dp[wei][c1],ans[x][2]) total+=wei bea+=ans[x][2] if(total<=w): dp[total][c1]=max(dp[total][c1],bea) c1+=1 else: for j in range(w+1): dp[j][c1]=max(dp[j][c1],dp[j][c1-1]) q=al[i] total=0 dil=0 bea=0 wei=0 for x in q: wei=ans[x][1] bea=ans[x][2] total+=wei dil+=bea for j in range(w+1): if(wei>j): dp[j][c1]=max(dp[j][c1-1],dp[j][c1]) continue; else: dp[j][c1]=max(dp[j][c1],dp[j-wei][c1-1]+bea,dp[j][c1-1]) if(total<=w): dp[total][c1]=max(dp[total][c1-1],dil,dp[total][c1]) c1+=1 maxa=0 for j in range(w+1): maxa=max(maxa,dp[j][c1-1]) print(maxa) ``` No
87,160
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Submitted Solution: ``` import math,sys,bisect,heapq,os from collections import defaultdict,Counter,deque from itertools import groupby,accumulate from functools import lru_cache #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 def input(): return sys.stdin.readline().rstrip('\r\n') #input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ aj = lambda: list(map(int, input().split())) def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) def solve(): G = defaultdict(list) def addEdge(a,b): G[a].append(b) G[b].append(a) def dfs(node): d = deque() d.append(node) vis[node] = True T = [] S = [] tot = 0;wt = 0 while d: x = d.pop() S.append(B[x-1]) T.append(W[x-1]) # tot += B[x-1] # wt += W[x-1] for i in G.get(x,[]): if not vis[i]: vis[i] = True d.append(i) # if len(S) > 1: # S.append(tot) # T.append(wt) return S,T n,m,w =aj() W = aj() B = aj() vis = [False]*(n+1) for i in range(m): u,v = aj() addEdge(u,v) A1 = [] A2 = [] Id = 1 for i in range(1,n+1): if not vis[i]: c,d = dfs(i) A1.append(c) A2.append(d) # print(A1) # print(A2) # print(w) # dp = {} # def fun(pos = 0,wt = 0): # if wt > w: # return -float('inf') # if pos >= len(A1): # return 0 # z = dp.get((pos,wt),-1) # if z!= -1: # return z # ans = 0 # c2 = 0 # for i in range(len(A1[pos])): # c2 = max(c2,A1[pos][i] + fun(pos+1,wt + A2[pos][i])) # c3 = fun(pos + 1,wt) # z = max(c2,c3) # dp[(pos,wt)] = z # return z dp = [[0]*(w+1) for i in range(len(A1)+1)] for i in range(len(A1)): weight_sum = sum(x for x in A1[i]) beauty_sum = sum(x for x in A1[i]) for j in range(w + 1): dp[i][j] = max(beauty_sum + dp[i - 1][j - weight_sum] if weight_sum <= j else 0, dp[i - 1][j]) for k in range(len(A1[i])): dp[i][j] = max(dp[i][j], (dp[i - 1][j - A2[i][k]] + A1[i][k] if A2[i][k] <= j else 0)) # print(fun()) print(dp[len(A1)-1][w]) try: #os.system("online_judge.py") sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') except: pass solve() ``` No
87,161
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Submitted Solution: ``` from collections import defaultdict class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): group_members = defaultdict(list) for member in range(self.n): group_members[self.find(member)].append(member) return group_members n,m,w=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) uf=UnionFind(n) for _ in range(m): x,y=map(int,input().split()) uf.union(x-1,y-1) l=uf.roots() ll=len(l) dp=[[0]*(w+1) for i in range(ll)] ca,cb=0,0 for x in uf.members(l[0]): if a[x]<=w: dp[0][a[x]]=max(dp[0][a[x]],b[x]) ca+=a[x] cb+=b[x] if ca<=w: dp[0][ca]=max(dp[0][ca],cb) for i in range(1,ll): ca,cb=0,0 for x in uf.members(l[i]): for j in range(w+1): if j-a[x]>=0: dp[i][j]=max(dp[i][j],dp[i-1][j],dp[i-1][j-a[x]]+b[x]) ca+=a[x] cb+=b[x] for j in range(w+1): if j-ca>=0: dp[i][j]=max(dp[i-1][j],dp[i-1][j-ca]+cb) ans=0 for j in range(w+1): ans=max(ans,dp[ll-1][j]) print(ans) ``` No
87,162
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. <image> Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w. Input The first line contains integers n, m and w (1 ≀ n ≀ 1000, <image>, 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct. Output Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w. Examples Input 3 1 5 3 2 5 2 4 2 1 2 Output 6 Input 4 2 11 2 4 6 6 6 4 2 1 1 2 2 3 Output 7 Note In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6. In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. Submitted Solution: ``` f = lambda: map(int, input().split()) n, m, w = f() wb = [(0, 0)] + list(zip(f(), f())) t = list(range(n + 1)) def g(x): if x == t[x]: return x t[x] = g(t[x]) return t[x] for i in range(m): x, y = f() x, y = g(x), g(y) if x != y: t[y] = x p = [[] for j in range(n + 1)] for i in range(1, n + 1): p[g(i)].append(i) d = [1] + [0] * w for q in p: if len(q) < 2: continue WB = [wb[i] for i in q] W = sum(q[0] for q in WB) B = sum(q[1] for q in WB) for D in range(w - W, -1, -1): if d[D]: d[D + W] = max(d[D + W], d[D] + B) for W, B in WB: for D in range(w - W, -1, -1): if d[D]: d[D + W] = max(d[D + W], d[D] + B) for q in p: if len(q) != 1: continue W, B = wb[q[0]] for D in range(w - W, -1, -1): if d[D]: d[D + W] = max(d[D + W], d[D] + B) print(max(d) - 1) ``` No
87,163
Provide tags and a correct Python 3 solution for this coding contest problem. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Tags: implementation, math Correct Solution: ``` t = int(input()) if t % 2 == 1: print("contest") else: print("home") ```
87,164
Provide tags and a correct Python 3 solution for this coding contest problem. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Tags: implementation, math Correct Solution: ``` n=int(input()) home=str(input()) k=n l=[] while(n): l.append(str(input())) n-=1 # print(l) chk=l[-1][-3:] # if(chk==home): # print('home') # else: # print('contest') if(k%2==0): print("home") else: print("contest") ```
87,165
Provide tags and a correct Python 3 solution for this coding contest problem. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Tags: implementation, math Correct Solution: ``` print("home" if int(input()) % 2 == 0 else "contest") ```
87,166
Provide tags and a correct Python 3 solution for this coding contest problem. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Tags: implementation, math Correct Solution: ``` import sys raw_data = list() for line in sys.stdin: raw_data.append(line) nr = int(raw_data[0]) home = raw_data[1][0:3] dept = list() dest = list() for idx in range(2, 2 + nr): dept.append(raw_data[idx][0:3]) dest.append(raw_data[idx][5:8]) nxt = home cnt = 0 while cnt != nr: try: idx = dept.index(nxt) nxt = dest[idx] last = nxt except: break dept[idx] = '' cnt += 1 if cnt == nr and last == home: print('home') else: print('contest') ```
87,167
Provide tags and a correct Python 3 solution for this coding contest problem. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Tags: implementation, math Correct Solution: ``` n = int(input()) s = input() c = 0 for i in range(n): mass = input() mass = mass.split("->") if s in mass: c+=1 if(not (c % 2)): print("home") else: print("contest") ```
87,168
Provide tags and a correct Python 3 solution for this coding contest problem. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Tags: implementation, math Correct Solution: ``` #Rohan Bojja #rohan.bojja@gmail.com from collections import defaultdict ####################################### c=1 cases=1 while(c<=cases): n=int(input()) home=input() iten=defaultdict(list) for i in range(0,n): cur=input().split("->") iten[cur[0]].append(cur[1]) ans="home" cur=home while(True): #print(cur,iten) if(cur in iten): if(cur!=home and home in iten[cur]): del iten[cur][iten[cur].index(home)] cur=home elif(cur!=home): ans="contest" break elif(cur==home and len(iten[cur])>0): cur2=iten[cur][0] iten[cur].pop(0) cur=cur2 elif(cur==home): break else: ans="contest" break #print(cur,iten) print(ans) c=c+1 ```
87,169
Provide tags and a correct Python 3 solution for this coding contest problem. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Tags: implementation, math Correct Solution: ``` n = int(input()) a = input() q = [] w = [] for i in range(n): b = input() l = b[:b.find('-')] r = b[b.find('>')+1:] q.append(l) w.append(r) e = q.count(a) t = w.count(a) if e == t: print("home") else: print("contest") ```
87,170
Provide tags and a correct Python 3 solution for this coding contest problem. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Tags: implementation, math Correct Solution: ``` X = int(input()) Home = input() counter = 0 for i in range(X): h, c = list(input().split('->')) if h == Home: counter += 1 elif c == Home: counter -= 1 print("home" if counter == 0 else "contest") ```
87,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Submitted Solution: ``` n=int(input()) h=input() c1,c2=0,0 for i in range(n): x,y=input().split('->') if x==h: c1=c1+1 elif y==h: c2=c2+1 if c1==c2: print('home') else: print('contest') ``` Yes
87,172
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Submitted Solution: ``` if __name__ == "__main__": n = int(input()) home = input() flights = [] while n > 0: s, t = input().split("->") flights.append(s) flights.append(t) n -= 1 count = 0 for flight in flights: if flight == home: count += 1 if count % 2 == 0: print("home") else: print("contest") ``` Yes
87,173
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Submitted Solution: ``` #!/usr/bin/python3 n = int(input()) if n % 2 == 0: print("home") else: print("contest") ``` Yes
87,174
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Submitted Solution: ``` if int(input()) & 1: print('contest') else: print('home') ``` Yes
87,175
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Submitted Solution: ``` n = int(input()) home = input() i = 0 lst = [] while i < n: lst.append(input()) i += 1 last_fly = lst.count(lst[len(lst) - 1]) last = lst[len(lst) - 1][:3] first = lst[len(lst) - 1][-3:] cnt = lst.count(first + "->" + last) if cnt == last_fly: print("home") else: print("contest") ``` No
87,176
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Submitted Solution: ``` x=int(input()) for i in range(x+1): y=input() print(['home','conrest'][x%2]) ``` No
87,177
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Submitted Solution: ``` x = int(input()) a = input() t = [] k = 0 i = 0 t1 = 0 t3 = 1 for i in range(x): a1 = input().split("->") t.append(a1) while i <= x - 1: if t[i][0] == a: k = 1 for j in range(len(t)): if t[j][0] == t[i][1] and t[j][1] == t[i][0]: t.pop(j) i=i-1 t1 = 1 k = 0 break elif i == x-1: print("contest") t3 = 2 k = 1 break if k == 1: break if k == 1: break if t1 != 1: i = i + 1 if k == 0: print("home") elif k == 1 and t3 == 1: print("contest") ``` No
87,178
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are literally dozens of snooker competitions held each year, and team Jinotega tries to attend them all (for some reason they prefer name "snookah")! When a competition takes place somewhere far from their hometown, Ivan, Artsem and Konstantin take a flight to the contest and back. Jinotega's best friends, team Base have found a list of their itinerary receipts with information about departure and arrival airports. Now they wonder, where is Jinotega now: at home or at some competition far away? They know that: * this list contains all Jinotega's flights in this year (in arbitrary order), * Jinotega has only flown from his hometown to a snooker contest and back, * after each competition Jinotega flies back home (though they may attend a competition in one place several times), * and finally, at the beginning of the year Jinotega was at home. Please help them to determine Jinotega's location! Input In the first line of input there is a single integer n: the number of Jinotega's flights (1 ≀ n ≀ 100). In the second line there is a string of 3 capital Latin letters: the name of Jinotega's home airport. In the next n lines there is flight information, one flight per line, in form "XXX->YYY", where "XXX" is the name of departure airport "YYY" is the name of arrival airport. Exactly one of these airports is Jinotega's home airport. It is guaranteed that flights information is consistent with the knowledge of Jinotega's friends, which is described in the main part of the statement. Output If Jinotega is now at home, print "home" (without quotes), otherwise print "contest". Examples Input 4 SVO SVO-&gt;CDG LHR-&gt;SVO SVO-&gt;LHR CDG-&gt;SVO Output home Input 3 SVO SVO-&gt;HKT HKT-&gt;SVO SVO-&gt;RAP Output contest Note In the first sample Jinotega might first fly from SVO to CDG and back, and then from SVO to LHR and back, so now they should be at home. In the second sample Jinotega must now be at RAP because a flight from RAP back to SVO is not on the list. Submitted Solution: ``` n=int(input()) home=str(input()) k=n l=[] while(n): l.append(str(input())) n-=1 print(l) chk=l[-1][-3:] if(chk==home): print('home') else: print('contest') ``` No
87,179
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n, k = map(int, input().split()) d = set(int(x)-n for x in input().split()) q = deque() q.append(0) visited = {i : False for i in range(-1000, 1001)} dist = {i : 0 for i in range(-1000, 1001)} ans = -1 visited[0] = True found = False while q: u = q.popleft() for i in d: if i + u == 0: ans = dist[u] + 1 found = True break if i + u <= 1000 and i + u >= -1000 and not visited[i + u]: visited[i + u] = True dist[i + u] = dist[u] + 1 q.append(i + u) if found: break print (ans) ```
87,180
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() if n < a[0] or n > a[k - 1]: print(-1) else: b = [] b.append(a[0]) for i in a: if i != b[len(b) - 1]: b.append(i) d = {} for i in range(len(b)): b[i] -= n d[b[i]] = 1 ans = 1 while 0 not in d: d1 = {} for i in d: for j in b: if -1001 < i + j < 1001: d1[i + j] = 1 d = d1 ans += 1 print(ans) ```
87,181
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` ## ## ## import sys def line(): return sys.stdin.readline() def numbers(): return list(map(int, line().split())) def number(): return int(line()) adjlist = {} n, k = 0, 0 mark = [False]*2010 edges = [False]*1010 # bfs for "ssph" def bfs(s): i = 0 frontier = [s] while frontier: if mark[s]: break; next_frontier = [] for u in frontier: # check next state for v, isState in enumerate(edges): if isState: # check new node state = u + (n - 1000) - v if state >= 0 and state <= 2000 and not mark[state]: mark[state] = True next_frontier.append(state) frontier = next_frontier i += 1 if mark[s]: return i else: return -1 # main program [n, k] = numbers() concentrations = numbers() # reading edges for x in concentrations: edges[x] = True n = n + 1000 ans = bfs(1000) print(ans) # 1496438704903 # Made By Mostafa_Khaled ```
87,182
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque n, k = map(int, input().split()) conc = set(int(x) - n for x in input().split()) q = deque() q.append(0) visited = {i : False for i in range(-1000, 1001)} dist = {i : 0 for i in range(-1000, 1001)} ans = -1 visited[0] = True found = False while q: u = q.popleft() for c in conc: v = c + u if v == 0: ans=dist[u]+1 found=True break if v<=1000 and v>=-1000 and not visited[v]: visited[v]=True dist[v]=dist[u]+1 q.append(v) if found: break print(ans) ```
87,183
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` ## ## ## import sys def line(): return sys.stdin.readline() def numbers(): return list(map(int, line().split())) def number(): return int(line()) adjlist = {} n, k = 0, 0 mark = [False]*2010 edges = [False]*1010 # bfs for "ssph" def bfs(s): i = 0 frontier = [s] while frontier: if mark[s]: break; next_frontier = [] for u in frontier: # check next state for v, isState in enumerate(edges): if isState: # check new node state = u + (n - 1000) - v if state >= 0 and state <= 2000 and not mark[state]: mark[state] = True next_frontier.append(state) frontier = next_frontier i += 1 if mark[s]: return i else: return -1 # main program [n, k] = numbers() concentrations = numbers() # reading edges for x in concentrations: edges[x] = True n = n + 1000 ans = bfs(1000) print(ans) # 1496438704903 ```
87,184
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Tags: dfs and similar, graphs, shortest paths Correct Solution: ``` from collections import deque MAX_A = 1000 def main(): n, k = map(int, input().split()) a = set(int(x) - n for x in input().split()) visited = [False] * (2 * MAX_A + 1) visited[n] = True Q = deque() Q.append((n, 0)) result = None while Q: u, l = Q.popleft() l += 1 for ai in a: v = u + ai if v == n: result = l break if 0 <= v < len(visited) and not visited[v]: visited[v] = True Q.append((v, l)) if result is not None: break if result is None: result = -1 print(result) if __name__ == '__main__': # import sys # sys.stdin = open("E.txt") main() ```
87,185
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Submitted Solution: ``` from collections import deque Max = 1000 def MainBFS(): n, k = map(int, input().split()) conc = set(int(x) for x in input().split()) visited = [False] * (2 * Max + 1) visited[0] = True Q = deque() Q.append((0, 0)) result = None while Q: u, l = Q.popleft() l += 1 for c in conc: v = u + c hayResult = False if v / l == n: hayResult = True if result is None: result = l elif result is not None and l < result: result = l if v < len(visited) and not visited[v] and not hayResult: visited[v] = True Q.append((v, l)) if result is None: result = -1 print(result) if __name__ == '__main__': MainBFS() ``` No
87,186
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Submitted Solution: ``` ## ## ## import sys def line(): return sys.stdin.readline() def numbers(): return list(map(int, line().split())) def number(): return int(line()) adjlist = {} n, k = 0, 0 mark = [False]*1010 edges = [False]*1010 # bfs for "ssph" def bfs(s): i = 0 frontier = [s] while frontier: if mark[s]: break; next_frontier = [] for u in frontier: # check next state for v, isState in enumerate(edges): if isState: # check new node state = u + n - v if state >= 0 and state <= n and not mark[state]: mark[state] = True next_frontier.append(state) frontier = next_frontier i += 1 if mark[s]: return i else: return -1 # main program [n, k] = numbers() concentrations = numbers() # reading edges for x in concentrations: edges[x] = True ans = bfs(0) print(ans) # 1496437499797 ``` No
87,187
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Submitted Solution: ``` n, k = map(int, input().split()) arr = list(map(int, input().split())) possible = [1000000007]*1001 arr.sort() for i in arr: possible[i] = 1 for i in range(1, 1001): for j in arr: if(i-j < 1): break possible[i] = min(possible[i], 1+possible[i-j]) if(possible[n] == 1000000007): print("-1") for i in range(1, 1001): if(i*n <= 1000 and i == possible[i*n]): print(i) exit(0) print(-1) ``` No
87,188
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass. Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well. Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration <image>. Assume that the friends have unlimited amount of each Coke type. Input The first line contains two integers n, k (0 ≀ n ≀ 1000, 1 ≀ k ≀ 106) β€” carbon dioxide concentration the friends want and the number of Coke types. The second line contains k integers a1, a2, ..., ak (0 ≀ ai ≀ 1000) β€” carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration. Output Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration <image>, or -1 if it is impossible. Examples Input 400 4 100 300 450 500 Output 2 Input 50 2 100 25 Output 3 Note In the first sample case, we can achieve concentration <image> using one liter of Coke of types <image> and <image>: <image>. In the second case, we can achieve concentration <image> using two liters of <image> type and one liter of <image> type: <image>. Submitted Solution: ``` from queue import Queue ins = map(int, input().split()) n, k = next(ins), next(ins) concentrations = list(map(int, input().split())) q = Queue() visited = {} for i in range(len(concentrations)): q.put((concentrations[i], 1)) visited[concentrations[i]] = True done = False while not q.empty(): top = q.get() if top[0] == top[1] * n: print(top[1]) done = True break else: for val in concentrations: new_val = val + top[0] path = top[1] + 1 if new_val in visited or top[0] > 1000: continue visited[new_val] = True q.put((new_val, path)) if not done: print(-1) ``` No
87,189
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Tags: math, number theory Correct Solution: ``` import os import sys from io import BytesIO, IOBase # 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") # ------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) mod = 998244353 INF = float('inf') from math import factorial from collections import Counter, defaultdict, deque from heapq import heapify, heappop, heappush from math import pow # ------------------------------ def main(): for _ in range(N()): a, b = RL() mt = a*b res = round(pow(mt, 1/3)) if res**3==mt and a%res==0 and b%res==0: print('Yes') else: print('No') if __name__ == "__main__": main() ```
87,190
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Tags: math, number theory Correct Solution: ``` import os import sys from io import BytesIO, IOBase from collections import Counter BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def input(): return sys.stdin.readline().rstrip("\r\n") def gcd(a, b): if a == 0: return b return gcd(b % a, a) def lcm(a, b): return (a * b) / gcd(a, b) def main(): for _ in range(int(input())): # n=int(input()) # a=list(map(int, input().split())) a,b=map(int, input().split()) k=a*b f=0 # l=0 # r=k+1 # f=0 # while(l<=r): # mid=(l+r)//2 # tr=mid*mid*mid # if tr==k: # f=mid # break # if tr>k: # r=mid-1 # else: # l=mid+1 root=round(k**(1/3)) if root*root*root==k: f=root if f: if (a%f)==(b%f)==0: print('YES') else: print('NO') else: print('NO') return if __name__=="__main__": main() ```
87,191
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Tags: math, number theory Correct Solution: ``` import os, sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") for _ in range(int(input())): a, b = map(int, input().split()) q = a * b t = round(q ** (1 / 3)) if t * t * t == q and a % t == b % t == 0: print('YES') else: print('NO') ```
87,192
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Tags: math, number theory Correct Solution: ``` import os import sys from math import ceil, pow from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def main(): for _ in range(int(input())): a, b = map(int, input().split()) if (a * b == (ceil(pow(a * b, 1 / 3)) ** 3)): temp = ceil(pow(a * b, 1 / 3)) if ((a % temp) == (b % temp) == 0): print("Yes") continue print("No") if __name__ == "__main__": main() ```
87,193
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Tags: math, number theory Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n avl=AvlTree() #-----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default='z', func=lambda a, b: min(a ,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left)/ 2) # Check if middle element is # less than or equal to key if (arr[mid]<=key): count = mid+1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def countGreater( arr,n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ for i in range(int(input())): a,b=map(int,input().split()) c=a*b l=int(c**(1./3)+0.5) if l**3==a*b and a%l==0 and b%l==0: print("YES") else: print("NO") ```
87,194
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Tags: math, number theory Correct Solution: ``` import sys n = int(input()) ans = [] arr = sys.stdin.read().split() d = {} for i in range(1,1001): d[i**3] = i for i in range(n): a, b = int(arr[i<<1]), int(arr[i<<1|1]) if a == b: if a in d: ans.append('Yes') else: ans.append('No') continue if a > b: a, b = b, a x = d.get(a*a//b,-1) if x == -1: ans.append('No') continue if a % (x*x): ans.append('No') continue y = a //(x*x) if x * x * y == a and x * y * y == b: ans.append('Yes') else: ans.append('No') print('\n'.join(ans)) ```
87,195
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Tags: math, number theory Correct Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction 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") #-------------------game starts now----------------------------------------------------- for t in range (int(input())): a,b=map(int,input().split()) p=a*b #print(p) c=int(round(p**(1./3))) #print (c) if c**3==p and a%c==0 and b%c==0: print("Yes") else: print("No") ```
87,196
Provide tags and a correct Python 3 solution for this coding contest problem. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Tags: math, number theory Correct Solution: ``` import os import sys from io import BytesIO, IOBase from collections import Counter BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) def input(): return sys.stdin.readline().rstrip("\r\n") n = int(input()) output = [] for i in range(1, n + 1): a, b = map(int, input().split()) p = a * b root = round(p ** (1 / 3)) ok = root * root * root == p and a % root == b % root == 0 output.append('Yes' if ok else 'No') print('\n'.join(output)) ```
87,197
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Submitted Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() def PrimeFactors(n): factors=[] while(n%2==0): factors.append(2) n//=2 for i in range(3,int(sqrt(n))+1,2): while(n%i==0): factors.append(i) n//=i if(n>1): factors.append(n) return factors for _ in range(Int()): a,b=value() root=ceil((a*b)**(1/3)) # print(root) ok="No" if(root**3==a*b and a%root==0 and b%root==0): ok="Yes" print(ok) ``` Yes
87,198
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. <image> Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting. The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one. Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not. Input In the first string, the number of games n (1 ≀ n ≀ 350000) is given. Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly. Output For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower). Example Input 6 2 4 75 45 8 8 16 16 247 994 1000000000 1000000 Output Yes Yes Yes No No Yes Note First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won. The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3. Submitted Solution: ``` import sys input = sys.stdin.readline print = sys.stdout.write cbrt = {i**3:i for i in range(1001)} n = int(input()) all_res = [] for _ in range(n): a, b = map(int, input().split()) if a == b: all_res.append('Yes' if a in cbrt else 'No') continue if a > b: a, b = b, a r = cbrt.get(a * a // b, 0) if r == 0 or a % (r * r) > 0: all_res.append('No') continue y = a //(r * r) if r * r * y == a and r * y * y == b: all_res.append('Yes') else: all_res.append('No') print('\n'.join(all_res)) ``` Yes
87,199