text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Tags: binary search, data structures Correct Solution: ``` from sys import stdin, stdout from math import log, sqrt lines = stdin.readlines() n = int(lines[0].split()[0]) m = int(lines[0].split()[1]) p = int(lines[0].split()[2]) a = [int(x) for x in lines[1].split()] b = [int(x) for x in lines[2].split()] hash_map = {} def hash_elem(elem): if hash_map.get(elem, -1) == -1: # elem = int(elem * 1662634645) # elem = int((elem >> 13) + (elem << 19)) # hash_map[elem] = int(elem * 361352451) # hash_map[elem] = int(342153534 + elem + (elem >> 5) + (elem >> 13) + (elem << 17)) if elem < 1000: hash_map[elem] = elem//2 + elem * 1134234546677 + int(elem/3) + int(elem**2) + elem<<2 + elem>>7 + int(log(elem)) + int(sqrt(elem)) + elem&213213 + elem^324234211323 + elem|21319423094023 else: hash_map[elem] = 3 + elem^34 return elem + hash_map[elem] c = [hash_elem(elem) for elem in a] c_new = [sum([c[q + p * i] for i in range(m)]) for q in range(min(p, max(0, n - (m - 1) * p)))] for q in range(p, n - (m - 1) * p): prev = c_new[q - p] # print(len(c_new)-1, q, q + p*(m-1)) c_new.append(prev - c[q - p] + c[q + p * (m - 1)]) b_check = sum([hash_elem(elem) for elem in b]) ans1 = 0 ans = [] for q in range(n - (m - 1) * p): c_check = c_new[q] if b_check != c_check: continue else: ans1 += 1 ans.append(q + 1) print(ans1) stdout.write(' '.join([str(x) for x in ans])) ```
104,000
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Tags: binary search, data structures Correct Solution: ``` from sys import stdin, stdout from math import log, sqrt lines = stdin.readlines() n = int(lines[0].split()[0]) m = int(lines[0].split()[1]) p = int(lines[0].split()[2]) a = [int(x) for x in lines[1].split()] b = [int(x) for x in lines[2].split()] hash_map = {} def hash_elem(elem): if hash_map.get(elem, -1) == -1: if elem < 1000: hash_map[elem] = elem//2 + elem * 1134234546677 + int(elem/3) + int(elem**2) + elem<<2 + elem>>7 + int(log(elem)) + int(sqrt(elem)) + elem&213213 + elem^324234211323 + elem|21319423094023 else: hash_map[elem] = 3 + elem^34# elem<<2 + elem>>7 + elem&243 + elem^324 + elem|434 return elem + hash_map[elem] c = [hash_elem(elem) for elem in a] c_new = [sum([c[q + p*i] for i in range(m)]) for q in range(min(p, max(0,n - (m-1)*p)))] for q in range(p,n - (m-1)*p): prev = c_new[q - p] c_new.append(prev - c[q - p] + c[q + p*(m-1)]) b_check = sum([hash_elem(elem) for elem in b]) ans1 = 0 ans = [] for q in range(n - (m-1)*p): c_check = c_new[q] if b_check != c_check: continue else: ans1 += 1 ans.append(q+1) print(ans1) stdout.write(' '.join([str(x) for x in ans])) ```
104,001
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Tags: binary search, data structures Correct Solution: ``` # import sys, io, os # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline from collections import defaultdict,Counter def solve(n,m,p,a,b): ans=[] cb=Counter(b) for q in range(min(p,n-(m-1)*p)): arr = [a[i] for i in range(q,n,p)] lb=len(cb.keys()) cnt=cb.copy() # print(cnt) # print(arr) for v in arr[:m]: cnt[v]-=1 if cnt[v]==0: lb-=1 elif cnt[v]==-1: lb+=1 j=0 if lb==0: ans.append(q+1) for i,v in enumerate(arr[m:],m): cnt[v]-=1 if cnt[v]==0: lb-=1 elif cnt[v]==-1: lb+=1 cnt[arr[j]]+=1 if cnt[arr[j]]==0: lb-=1 elif cnt[arr[j]]==1: lb+=1 j+=1 # print(cnt,lb,j,q) if lb==0: ans.append(q+j*p+1) print(len(ans)) print(*sorted(ans)) n,m,p=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) solve(n,m,p,a,b) ```
104,002
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Tags: binary search, data structures Correct Solution: ``` from sys import stdin, stdout from math import log, sqrt lines = stdin.readlines() n = int(lines[0].split()[0]) m = int(lines[0].split()[1]) p = int(lines[0].split()[2]) a = [int(x) for x in lines[1].split()] b = [int(x) for x in lines[2].split()] def hash_elem(x): x = (x * 1662634645 + 32544235) & 0xffffffff x = ((x >> 13) + (x << 19)) & 0xffffffff x = (x * 361352451) & 0xffffffff return x c = [hash_elem(elem) for elem in a] c_new = [sum([c[q + p * i] for i in range(m)]) for q in range(min(p, max(0, n - (m - 1) * p)))] for q in range(p, n - (m - 1) * p): prev = c_new[q - p] # print(len(c_new)-1, q, q + p*(m-1)) c_new.append(prev - c[q - p] + c[q + p * (m - 1)]) b_check = sum([hash_elem(elem) for elem in b]) ans1 = 0 ans = [] for q in range(n - (m - 1) * p): c_check = c_new[q] if b_check != c_check: continue else: ans1 += 1 ans.append(q + 1) print(ans1) stdout.write(' '.join([str(x) for x in ans])) ```
104,003
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Tags: binary search, data structures Correct Solution: ``` # import sys, io, os # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline from collections import Counter def solve(n,m,p,a,b): ans=[] cb=Counter(b) for q in range(min(p,n-(m-1)*p)): arr = [a[i] for i in range(q,n,p)] lb=len(cb.keys()) cnt=cb.copy() for v in arr[:m]: cnt[v]-=1 if cnt[v]==0: lb-=1 elif cnt[v]==-1: lb+=1 j=0 if lb==0: ans.append(q+1) for v in arr[m:]: cnt[v]-=1 if cnt[v]==0: lb-=1 elif cnt[v]==-1: lb+=1 cnt[arr[j]]+=1 if cnt[arr[j]]==0: lb-=1 elif cnt[arr[j]]==1: lb+=1 j+=1 if lb==0: ans.append(q+j*p+1) print(len(ans)) print(*sorted(ans)) n,m,p=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) solve(n,m,p,a,b) ```
104,004
Provide tags and a correct Python 3 solution for this coding contest problem. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Tags: binary search, data structures Correct Solution: ``` from collections import defaultdict n, m, p = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) u = defaultdict(int) for i in b: u[i] += 1 ans = [] for q in range(p): c = a[q: n: p] if len(c) < m: break v = defaultdict(int) for i in c[: m]: v[i] += 1 d = q + 1 if u == v: ans.append(d) for j, k in zip(c[: len(c) - m], c[m: ]): v[j] -= 1 if v[j] == 0: v.pop(j) v[k] += 1 d += p if u == v: ans.append(d) ans.sort() print(len(ans)) print(' '.join(map(str, ans))) ```
104,005
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Submitted Solution: ``` from sys import stdin, stdout from math import log, sqrt lines = stdin.readlines() n = int(lines[0].split()[0]) m = int(lines[0].split()[1]) p = int(lines[0].split()[2]) a = [int(x) for x in lines[1].split()] b = [int(x) for x in lines[2].split()] def hash_elem(x): x = (x + (x >> 13) + (x >> 5) + (x << 15)) & 0xffffffff return x c = [hash_elem(elem) for elem in a] c_new = [sum([c[q + p * i] for i in range(m)]) for q in range(min(p, max(0, n - (m - 1) * p)))] for q in range(p, n - (m - 1) * p): prev = c_new[q - p] # print(len(c_new)-1, q, q + p*(m-1)) c_new.append(prev - c[q - p] + c[q + p * (m - 1)]) b_check = sum([hash_elem(elem) for elem in b]) ans1 = 0 ans = [] for q in range(n - (m - 1) * p): c_check = c_new[q] if b_check != c_check: continue else: ans1 += 1 ans.append(q + 1) print(ans1) stdout.write(' '.join([str(x) for x in ans])) ``` No
104,006
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Submitted Solution: ``` from sys import stdin, stdout from math import log, sqrt lines = stdin.readlines() n = int(lines[0].split()[0]) m = int(lines[0].split()[1]) p = int(lines[0].split()[2]) a = [int(x) for x in lines[1].split()] b = [int(x) for x in lines[2].split()] hash_map = {} def hash_elem(elem): if hash_map.get(elem, -1) == -1: x = int(elem * 1662634645 + 32544235) x = int((x >> 13) + (x << 19)) hash_map[elem] = int(x * 361352451) # hash_map[elem] = int(342153534 + elem + (elem >> 5) + (elem >> 13) + (elem << 17)) # if elem < 1000: # hash_map[elem] = elem//2 + elem * 1134234546677 + int(elem/3) + int(elem**2) + elem<<2 + elem>>7 + int(log(elem)) + int(sqrt(elem)) + elem&213213 + elem^324234211323 + elem|21319423094023 # else: # hash_map[elem] = 3 + elem^34 return elem + hash_map[elem] c = [hash_elem(elem) for elem in a] c_new = [sum([c[q + p * i] for i in range(m)]) for q in range(min(p, max(0, n - (m - 1) * p)))] for q in range(p, n - (m - 1) * p): prev = c_new[q - p] # print(len(c_new)-1, q, q + p*(m-1)) c_new.append(prev - c[q - p] + c[q + p * (m - 1)]) b_check = sum([hash_elem(elem) for elem in b]) ans1 = 0 ans = [] for q in range(n - (m - 1) * p): c_check = c_new[q] if b_check != c_check: continue else: ans1 += 1 ans.append(q + 1) print(ans1) stdout.write(' '.join([str(x) for x in ans])) ``` No
104,007
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Submitted Solution: ``` from sys import stdin, stdout lines = stdin.readlines() n = int(lines[0].split()[0]) m = int(lines[0].split()[1]) p = int(lines[0].split()[2]) a = [int(x) for x in lines[1].split()] b = sorted([int(x) for x in lines[2].split()]) def hash_sum(a): ret = 0 for elem in a: ret += elem + elem*117 + elem//3 + elem**(1/2) return ret b_check = hash_sum(b) ans1 = 0 ans = [] for q in range(n - (m-1)*p): cand = [a[q + p*i] for i in range(m)] c_check = hash_sum(cand) if b_check != c_check: continue else: ans1 += 1 ans.append(q+1) print(ans1) stdout.write(' '.join([str(x) for x in ans])) ``` No
104,008
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2 Submitted Solution: ``` class pa: pass n,m,p = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) b_dict = {b[i]:i for i in range(m)} a_split_p = [0]*p for i_list in range(p): a_split_p[i_list] = list() for i_a in range(i_list,n,p): newa = pa() newa.key = a[i_a] newa.nom = i_a a_split_p[i_list].append(newa) cnt = [0]*m for i in range(m): cnt[b_dict.get(b[i])] += 1 ans_cnt = 0 ans_array = list() for i_list in range(p): l = 0 use = [0]*m good = 0 for num, i_a in enumerate(a_split_p[i_list]): if not (i_a.key in b_dict): continue num_b_i = b_dict.get(i_a.key) use[num_b_i] +=1 if use[num_b_i] == cnt[num_b_i]: good += 1 if (num-l+1>m): num_b_l = b_dict.get(a_split_p[i_list][l].key) if (use[num_b_l]==cnt[num_b_l]): good -=1 use[num_b_l] -=1 l +=1 if good==m: ans_cnt += 1 ans_array.append(a_split_p[i_list][l].nom) #print("{} {}".format(use,good)) #print("===") print (ans_cnt) ans = "" for i in ans_array: ans = ans + "{} ".format(i+1) print(ans) ``` No
104,009
Provide tags and a correct Python 3 solution for this coding contest problem. As it has been found out recently, all the Berland's current economical state can be described using a simple table n Γ— m in size. n β€” the number of days in each Berland month, m β€” the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information β€” the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000). The second line contains the integer k (0 ≀ k < max(n, m)) β€” the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≀ a ≀ n) β€” the number of the table row, b (1 ≀ b ≀ m) β€” the number of the column, c β€” the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≀ p ≀ 109 + 7). Output Print the number of different tables that could conform to the preserved data modulo p. Examples Input 2 2 0 100 Output 2 Input 2 2 1 1 1 -1 100 Output 1 Tags: combinatorics Correct Solution: ``` # METO Bot 0.9.9 n,m=map(int,input().split()) k=int(input()) A=[[] for i in range(max(n,m))] for i in range(k): a,b,c=map(int,input().split()) A[b-1 if n<m else a-1].append(c==-1) p=int(input()) if n%2!=m%2: print(0) else: r=k for i in A: if len(i)>=min(n,m): if sum(i)%2: r-=1 else: print(0) break else: print(pow(2,(n-1)*(m-1)-r,p)) ```
104,010
Provide tags and a correct Python 3 solution for this coding contest problem. As it has been found out recently, all the Berland's current economical state can be described using a simple table n Γ— m in size. n β€” the number of days in each Berland month, m β€” the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information β€” the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000). The second line contains the integer k (0 ≀ k < max(n, m)) β€” the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≀ a ≀ n) β€” the number of the table row, b (1 ≀ b ≀ m) β€” the number of the column, c β€” the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≀ p ≀ 109 + 7). Output Print the number of different tables that could conform to the preserved data modulo p. Examples Input 2 2 0 100 Output 2 Input 2 2 1 1 1 -1 100 Output 1 Tags: combinatorics Correct Solution: ``` import itertools import math n, m = [int(x) for x in input().split()] if n%2 != m%2: print(0) else: k = int(input()) S = [[] for i in range(max(n,m))] for i in range(k): a, b, c = [int(x) for x in input().split()] if n<m: S[b-1].append(c==-1) else: S[a-1].append(c==-1) p = int(input()) restrictions = k for string in S: if len(string) >= min(n,m): if sum(string)%2: restrictions -= 1 else: print(0) break else: print(pow(2, (n-1)*(m-1) - restrictions, p)) ```
104,011
Provide tags and a correct Python 3 solution for this coding contest problem. As it has been found out recently, all the Berland's current economical state can be described using a simple table n Γ— m in size. n β€” the number of days in each Berland month, m β€” the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information β€” the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000). The second line contains the integer k (0 ≀ k < max(n, m)) β€” the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≀ a ≀ n) β€” the number of the table row, b (1 ≀ b ≀ m) β€” the number of the column, c β€” the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≀ p ≀ 109 + 7). Output Print the number of different tables that could conform to the preserved data modulo p. Examples Input 2 2 0 100 Output 2 Input 2 2 1 1 1 -1 100 Output 1 Tags: combinatorics Correct Solution: ``` n,m=map(int,input().split()) k=int(input()) A=[[] for i in range(max(n,m))] for i in range(k): a,b,c=map(int,input().split()) A[b-1 if n<m else a-1].append(c==-1) p=int(input()) if n%2!=m%2: print(0) else: r=k for i in A: if len(i)>=min(n,m): if sum(i)%2: r-=1 else: print(0) break else: print(pow(2,(n-1)*(m-1)-r,p)) ```
104,012
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As it has been found out recently, all the Berland's current economical state can be described using a simple table n Γ— m in size. n β€” the number of days in each Berland month, m β€” the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information β€” the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000). The second line contains the integer k (0 ≀ k < max(n, m)) β€” the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≀ a ≀ n) β€” the number of the table row, b (1 ≀ b ≀ m) β€” the number of the column, c β€” the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≀ p ≀ 109 + 7). Output Print the number of different tables that could conform to the preserved data modulo p. Examples Input 2 2 0 100 Output 2 Input 2 2 1 1 1 -1 100 Output 1 Submitted Solution: ``` n,m=map(int,input().split()) k=int(input()) A=[[] for i in range(max(n,m))] for i in range(k): a,b,c=map(int,input().split()) A[b-1 if n<m else a-1].append(c==-1) p=int(input()) if n%2!=m%2: print(0) exit(0) r=k for i in A: if len(i)>=min(n,m): if sum(i)%2: r=-1 else: print(0) break else: print(pow(2,(n-1)*(m-1)-r,p)) ``` No
104,013
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As it has been found out recently, all the Berland's current economical state can be described using a simple table n Γ— m in size. n β€” the number of days in each Berland month, m β€” the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information β€” the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p. Input The first line contains integers n and m (1 ≀ n, m ≀ 1000). The second line contains the integer k (0 ≀ k < max(n, m)) β€” the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≀ a ≀ n) β€” the number of the table row, b (1 ≀ b ≀ m) β€” the number of the column, c β€” the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≀ p ≀ 109 + 7). Output Print the number of different tables that could conform to the preserved data modulo p. Examples Input 2 2 0 100 Output 2 Input 2 2 1 1 1 -1 100 Output 1 Submitted Solution: ``` import itertools import math n, m = [int(x) for x in input().split()] k = int(input()) S = [[] for i in range(max(n,m))] for i in range(k): a, b, c = [int(x) for x in input().split()] if n<m: S[b-1].append(c==-1) else: S[a-1].append(c==-1) p = int(input()) restrictions = k for string in S: if len(string) >= min(n,m): if sum(string)%2: restrictions -= 1 else: print(0) break else: print(pow(2, (n-1)*(m-1) - restrictions, p)) ``` No
104,014
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks. Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array a[1], a[2], ..., a[n]. Then he should perform a sequence of m operations. An operation can be one of the following: 1. Print operation l, r. Picks should write down the value of <image>. 2. Modulo operation l, r, x. Picks should perform assignment a[i] = a[i] mod x for each i (l ≀ i ≀ r). 3. Set operation k, x. Picks should set the value of a[k] to x (in other words perform an assignment a[k] = x). Can you help Picks to perform the whole sequence of operations? Input The first line of input contains two integer: n, m (1 ≀ n, m ≀ 105). The second line contains n integers, separated by space: a[1], a[2], ..., a[n] (1 ≀ a[i] ≀ 109) β€” initial value of array elements. Each of the next m lines begins with a number type <image>. * If type = 1, there will be two integers more in the line: l, r (1 ≀ l ≀ r ≀ n), which correspond the operation 1. * If type = 2, there will be three integers more in the line: l, r, x (1 ≀ l ≀ r ≀ n; 1 ≀ x ≀ 109), which correspond the operation 2. * If type = 3, there will be two integers more in the line: k, x (1 ≀ k ≀ n; 1 ≀ x ≀ 109), which correspond the operation 3. Output For each operation 1, please print a line containing the answer. Notice that the answer may exceed the 32-bit integer. Examples Input 5 5 1 2 3 4 5 2 3 5 4 3 3 5 1 2 5 2 1 3 3 1 1 3 Output 8 5 Input 10 10 6 9 6 7 6 1 10 10 9 5 1 3 9 2 7 10 9 2 5 10 8 1 4 7 3 3 7 2 7 9 9 1 2 4 1 6 6 1 5 9 3 1 10 Output 49 15 23 1 9 Note Consider the first testcase: * At first, a = {1, 2, 3, 4, 5}. * After operation 1, a = {1, 2, 3, 0, 1}. * After operation 2, a = {1, 2, 5, 0, 1}. * At operation 3, 2 + 5 + 0 + 1 = 8. * After operation 4, a = {1, 2, 2, 0, 1}. * At operation 5, 1 + 2 + 2 = 5. Submitted Solution: ``` def get_sum(v, v1, vr, l_, r): if r <= v1 or vr <= l_: return 0 if l_ <= v1 and vr <= r: return sums[v] vm = (v1 + vr) // 2 return get_sum(v * 2, v1, vm, l_, r) + get_sum(v * 2 + 1, vm, vr, l_, r) def do_mod(v, v1, vr, l_, r, x): if r <= v1 or vr <= l_: return if maxes[v] < x: return if v >= n1: sums[v] = maxes[v] = sums[v] % x return vm = (v1 + vr) // 2 va = v * 2 vb = va + 1 do_mod(va, v1, vm, l_, r, x) do_mod(vb, vm, vr, l_, r, x) sums[v] = sums[va] + sums[vb] maxes[v] = max(maxes[va], maxes[vb]) def main(): n1m1 = n1 - 1 for i in range(n + n1, 1, -1): sums[i // 2] += sums[i] maxes[i // 2] = max(maxes[i // 2], maxes[i]) for _ in range(m): typ, data = input().split(maxsplit=1) if typ == '1': l_, r = map(int, data.split()) print(get_sum(1, 0, n1, l_ - 1, r)) elif typ == '2': l_, r, x = map(int, data.split()) do_mod(1, 0, n1, l_ - 1, r, x) elif typ == '3': k, x = map(int, data.split()) v = n1m1 + k x1 = x - sums[v] while v: sums[v] += x1 v //= 2 maxes[v] = max(maxes[v * 2], maxes[v * 2 + 1]) n, m = map(int, input().split()) n1 = 2 ** n.bit_length() while n1 > n: n1 //= 2 while n1 < n: n1 *= 2 sums = [0] * n1 sums.extend(map(int, input().split())) sums.append(0) maxes = sums[:] main() ``` No
104,015
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Tags: brute force, implementation, math Correct Solution: ``` row = input() n = int(row.split()[0]) m = int(row.split()[1]) rem = int(n/m) + int(n%m) x = int(n/m) while rem >= m: x = x + int(rem/m) rem = int(rem/m) + int(rem%m) print(n + x) ```
104,016
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Tags: brute force, implementation, math Correct Solution: ``` n, m = map(int, input().split()) d = 0 i = 1 while n != 0: n -= 1 d += 1 if d == i * m: n += 1 i += 1 print(d) ```
104,017
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Tags: brute force, implementation, math Correct Solution: ``` n, m = map(int, input().split()) count = 0 i = 1 while i*m <= n: i += 1 n += 1 while n > 0: count += 1 n -= 1 print(count) ```
104,018
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Tags: brute force, implementation, math Correct Solution: ``` n,m = map(int,input().split(" ")) days=0 if n>=m: while n>=m: days+=(n-n%m) n=int(n/m)+int(n%m) days+=n else: days=n print(days) ```
104,019
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Tags: brute force, implementation, math Correct Solution: ``` (n,m)=map(int,input().strip().split()) days=1 while n!=0: n-=1 if days%m==0: n+=1 days+=1 print(days-1) ```
104,020
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Tags: brute force, implementation, math Correct Solution: ``` __author__ = 'Gamoool' import sys n,m = map(int,sys.stdin.readline().split()) u = n+ ((n-1)//(m-1)) print(u) ```
104,021
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Tags: brute force, implementation, math Correct Solution: ``` n,m = map(int,input().split()) s,q = 0,0 i = 1 for i in range(1,n+1): s+=1 if i % m == 0: q+=1 while q!=0: i+=1 s+=1 q-=1 if s % m == 0: q+=1 print(s) ```
104,022
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Tags: brute force, implementation, math Correct Solution: ``` n, m = map(int, input().split()) print(n + ~- n // ~- m) ```
104,023
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Submitted Solution: ``` a=list(map(int,input().split())) n=a[0] m=a[1] i=0 dias=0 j=1 while True: i+=1 if n>0: dias+=1 n-=1 if i==j*m: j+=1 n+=1 if n==0: break print(dias) ``` Yes
104,024
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Submitted Solution: ``` a,b = map(int, input().split()) c = a while a >= b: c = c + a//b a = a//b +a%b print(c) ``` Yes
104,025
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Submitted Solution: ``` n,m = map(int, input().split()) k = 0 while n > 0: k += 1 n -= 1 if k%m == 0: n += 1 print(k) ``` Yes
104,026
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Submitted Solution: ``` n, m = input().split() n = eval(n) m = eval(m) k = 0 for i in range(1, 100000): #print(n) if (not n): break n -= 1 k += 1 if (i % m == 0): n += 1 print(k) ``` Yes
104,027
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Submitted Solution: ``` n,m = map(int, input().split()) ans = n k = 0 while(n >= m): n = n // m k = k + n ans = ans + k print(ans) ``` No
104,028
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Submitted Solution: ``` n, m = map(int, input().split()) col = 0 while n > 0: col += 1 n -= 1 if n == 0: break if col % m == 0: n += 1 print(col + 1) ``` No
104,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Submitted Solution: ``` ln = input().split(" ") n = int(ln[0]) m = int(ln[1]) res = n k = int(n/m) while k > 0: res += k k = int(k/m) print(res) ``` No
104,030
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day. Submitted Solution: ``` def vasya(): c = list(map(int, input().split())) if c==[10,3]: print(19) return d = c[0] f = c[1] while c[0]>=c[1]: e=c[0]/c[1] f=c[0]%c[1] c[0]=e+f d+=e print(int(d)) print(vasya()) ``` No
104,031
Provide tags and a correct Python 3 solution for this coding contest problem. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? Input The first line of input contains two integers n, m (2 ≀ n ≀ 105, <image>), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. Output In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. Examples Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 Note In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` f = lambda: map(int, input().split()) g = lambda: (a.i, b.i) if a.i < b.i else (b.i, a.i) class T: def __init__(t, i): t.i = i t.s = t.v = t.u = 0 t.p = [] n, m = f() t = [T(i) for i in range(n + 1)] d, l = [], [] for k in range(m): i, j, q = f() a, b = t[i], t[j] a.p.append(b) b.p.append(a) if q: d += [g()] d = set(d) x, y = [], [] a = t[1] a.u = 1 while a.i < n: for b in a.p: v = a.v + (g() in d) if not b.u or b.u > a.u and v > b.v: b.v, b.s = v, a.i if not b.u: b.u = a.u + 1 y.append(b.i) if not x: x, y = y, x x.reverse() a = t[x.pop()] while a.i > 1: b = t[a.s] a.p.remove(b) b.p.remove(a) if g() in d: d.remove(g()) else: l += [(a.i, b.i)] a = b print(len(l) + len(d)) for a, b in l: print(a, b, 1) for a, b in d: print(a, b, 0) ```
104,032
Provide tags and a correct Python 3 solution for this coding contest problem. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? Input The first line of input contains two integers n, m (2 ≀ n ≀ 105, <image>), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. Output In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. Examples Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 Note In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` from sys import * from collections import * s = stdin.read().split() d = list(map(int, s)) n, m = d[:2] g = [[] for i in range(n + 1)] for j in range(m): i = 3 * j + 2 g[d[i]].append((d[i + 1], d[i + 2], j)) g[d[i + 1]].append((d[i], d[i + 2], j)) u, v = [-1] * n + [0], [1e9] * n + [0] x, y = [0] * (n + 1), [0] * (n + 1) q = deque([n]) while q: a = q.popleft() for b, k, i in g[a]: if v[b] == 1e9: q.append(b) if v[b] > v[a] and u[b] < u[a] + k: v[b] = v[a] + 1 u[b] = u[a] + k x[b], y[b] = a, i a, t = 1, [0] * m while a != n: t[y[a]], a = 1, x[a] l = [] for j in range(m): i = 3 * j + 2 if d[i + 2] != t[j]: l.append(' '.join([s[i], s[i + 1], str(t[j])])) print(len(l)) print('\n'.join(l)) ```
104,033
Provide tags and a correct Python 3 solution for this coding contest problem. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? Input The first line of input contains two integers n, m (2 ≀ n ≀ 105, <image>), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. Output In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. Examples Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 Note In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` from collections import deque def bfs(n, v, s, t): dis = [n] * n load = [n] * n path = [None] * n q = deque([s]) dis[s] = 0 load[s] = 0 while (q): node = q.popleft() for i in range(len(v[node])): nb = v[node][i][0] status = v[node][i][1] tmp_dis = dis[node] + 1 tmp_load = load[node] + (status != 1) if ((tmp_dis, tmp_load) < (dis[nb], load[nb])): dis[nb] = tmp_dis load[nb] = tmp_load path[nb] = node if (node != t): q.append(nb) if (node == t): break node = t opt = set() while (node != s): opt.add((min(node, path[node]), max(node, path[node]))) node = path[node] return dis[t], load[t], opt #def sp(s, t): ## dijkstra #global m, n, v, st, l_min, w_min, opt #current = s #visited = set([s]) #dis = {} #dis[s] = 0 #path = [[] for _ in xrange(n)] #path[s] = [[]] #load = [[] for _ in xrange(n)] #load[s] = [0] #while (current != t): #if (debug >= 2): #print 'current=%d' % current #for i in xrange(len(v[current])): #nb = v[current][i] #status = st[current][i] #if (debug >= 2): #print ' nb=%d, st=%d:' % (nb, status), #if (not dis.has_key(nb) or dis[nb] > 1 + dis[current]): ## update #dis[nb] = 1 + dis[current] #load[nb] = [] #path[nb] = [] #for j in xrange(len(load[current])): #path[nb].append(path[current][j][:]) #path[nb][j].append((current, nb)) #if (status == 0): #load[nb].append(load[current][j] + 1) #else: #load[nb].append(load[current][j]) #if (debug >= 2): #print 'Updated' #elif (dis[nb] == 1 + dis[current]): ## append #for j in xrange(len(load[current])): #path[nb].append(path[current][j][:]) #path[nb][len(path[nb]) - 1].append((current, nb)) #if (status == 0): load[nb].append(1 + load[current][j]) #else: load[nb].append(load[current][j]) #if (debug >= 2): #print 'Appended' #else: #if (debug >= 2): #print 'Passed' #sorted_idx = sorted(dis, key = dis.get) #if (debug >= 2): print sorted_idx #idx = 0 #while (sorted_idx[idx] in visited): idx += 1 #current = sorted_idx[idx] #visited.add(current) #w_min = min(load[t]) #l_min = dis[t] #opt = tuple(path[t][load[t].index(w_min)]) #return 0 #def dfs(s, t, visited, path, l, w): #global m, n, v, st, l_min, w_min, opt ##print path #if (s == t): #if (l < l_min): #l_min = l #w_min = w #opt = tuple(path) #else: #if (w < w_min): #w_min = w #opt = tuple(path) #return 0 #if (l >= l_min): return 0 ##if (w >= w_min): return 0 #for i in xrange(len(v[s])): #if (v[s][i] in visited): continue #visited.add(v[s][i]) #path.append((s, v[s][i])) #if (st[s][i] == 1): #dfs(v[s][i], t, visited, path, l + 1, w) #else: #dfs(v[s][i], t, visited, path, l + 1, w + 1) #visited.remove(v[s][i]) #path.pop(len(path) - 1) #return 0 global debug debug = 0 #global m, n, v, st, l_min, w_min n, m = list(map(int, input().split())) #e = [] v = [[] for _ in range(n)] a = 0 # bad count b = 0 # good count #l_min = n #w_min = n #opt = () for i in range(m): v1, v2, status = list(map(int, input().split())) if (status == 0): a += 1 else: b += 1 v[v1 - 1].append((v2 - 1, status)) v[v2 - 1].append((v1 - 1, status)) #e.append((v1, v2, status)) if (debug >= 1): t0 = time.time() #dfs(0, n - 1, set(), [], 0, 0) #sp(n - 1, 0) #sp(0, n - 1) l_min, w_min, opt = bfs(n, v, 0, n - 1) #l_min, w_min, opt = bfs(n, v, st, n - 1, 0) print(b - l_min + 2 * w_min) #print opt #for i in xrange(len(e)): # if ((e[i][0] - 1, e[i][1] - 1) in opt or (e[i][1] - 1, e[i][0] - 1) in opt): # if (e[i][2] == 0): print '%d %d 1' % (e[i][0], e[i][1]) # else: # if (e[i][2] == 1): print '%d %d 0' % (e[i][0], e[i][1]) #for i in xrange(len(e)): # if ((min(e[i][0] - 1, e[i][1] - 1), max(e[i][0] - 1, e[i][1] - 1)) in opt): # if (e[i][2] == 0): print '%d %d 1' % (e[i][0], e[i][1]) # else: # if (e[i][2] == 1): print '%d %d 0' % (e[i][0], e[i][1]) for v1 in range(n): for v2, status in v[v1]: if (v2 < v1): continue if ((v1, v2) in opt): if (status == 0): print('%d %d 1' % (v1 + 1, v2 + 1)) else: if (status == 1): print('%d %d 0' % (v1 + 1, v2 + 1)) if (debug >= 1): print('%f' % (time.time() - t0)) ```
104,034
Provide tags and a correct Python 3 solution for this coding contest problem. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? Input The first line of input contains two integers n, m (2 ≀ n ≀ 105, <image>), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. Output In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. Examples Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 Note In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` f = lambda: map(int, input().split()) g = lambda: (a.i, b.i) if a.i < b.i else (b.i, a.i) class T: def __init__(t, i): t.i = i t.s = t.v = t.u = 0 t.p = set() n, m = f() t = [T(i) for i in range(n + 1)] d, l = [], [] for k in range(m): i, j, q = f() a, b = t[i], t[j] a.p.add(b) b.p.add(a) if q: d += [g()] d = set(d) x, y = [], [] a = t[1] a.u = 1 while a.i < n: for b in a.p: v = a.v + (g() in d) if not b.u or b.u > a.u and v > b.v: b.v, b.s = v, a.i if not b.u: b.u = a.u + 1 y.append(b.i) if not x: x, y = y, x x.reverse() a = t[x.pop()] while a.i > 1: b = t[a.s] a.p.remove(b) b.p.remove(a) if g() in d: d.remove(g()) else: l += [(a.i, b.i)] a = b print(len(l) + len(d)) for a, b in l: print(a, b, 1) for a, b in d: print(a, b, 0) ```
104,035
Provide tags and a correct Python 3 solution for this coding contest problem. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? Input The first line of input contains two integers n, m (2 ≀ n ≀ 105, <image>), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. Output In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. Examples Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 Note In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Tags: dfs and similar, dp, graphs, shortest paths Correct Solution: ``` import collections import heapq if __name__ == '__main__': n, m = [int(x) for x in input().split()] G = collections.defaultdict(list) road = [] for i in range(m): s, e, f = [int(x) for x in input().split()] road.append((s, e, f)) G[s].append((e, f)) G[e].append((s, f)) def dijkstra(s, e): d = [(float('inf'), float('inf')) for _ in range(n + 1)] pre = [-1 for _ in range(n + 1)] d[s] = (0, 0) hq = [(0, 0, s)] while hq: dis, cost, p = heapq.heappop(hq) if d[p] < (dis, cost): continue for e, f in G[p]: cost_e = cost + (1 if not f else 0) dis_e = dis + 1 if (dis_e, cost_e) < d[e]: d[e] = (dis_e, cost_e) pre[e] = p heapq.heappush(hq, (dis_e, cost_e, e)) return pre pre = dijkstra(1, n) q = n path = [] while q != -1: path.append(q) q = pre[q] pairs = set() for i in range(len(path) - 1): pairs.add((path[i], path[i + 1])) k = 0 ans = [] for s, e, f in road: if ((s, e) in pairs or (e, s) in pairs) and f == 0: k += 1 ans.append((s, e, 1)) elif ((s, e) not in pairs and (e, s) not in pairs) and f == 1: k += 1 ans.append((s, e, 0)) print(k) for s, e, f in ans: print(s, e, f) ```
104,036
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? Input The first line of input contains two integers n, m (2 ≀ n ≀ 105, <image>), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. Output In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. Examples Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 Note In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Submitted Solution: ``` n, k = map(int, input().split()) a = [(value, index) for index, value in enumerate(map(int, input().split()), 1)] a.sort() result = [ ] i = 0 while i < len(a) and k >= a[i][0]: result.append(a[i][1]) k -= a[i][0] i += 1 print(len(result)) print(' '.join(map(str, result))) ``` No
104,037
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? Input The first line of input contains two integers n, m (2 ≀ n ≀ 105, <image>), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. Output In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. Examples Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 Note In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Submitted Solution: ``` def main(): global graph global ways global to_repair ways = [] n, m = list(map(int,input().split())) graph = [0]*n broken = 0 edges = [] for i in range(n): graph[i] = [0]*n for i in range(m): rdl = list(map(int,input().split())) edges.append([min(rdl[0],rdl[1]), max(rdl[0],rdl[1]),rdl[2]]) if rdl[2] == 0: graph[rdl[0]-1][rdl[1]-1] = 2 graph[rdl[1]-1][rdl[0]-1] = 2 broken += 1 else: graph[rdl[0]-1][rdl[1]-1] = 1 graph[rdl[1]-1][rdl[0]-1] = 1 to_repair = [] global cur_min_steps cur_min_steps = 100000000000 obx(n-1, 0, []) min_uses = 10000000000 indexofmin = 0 for i in range(len(ways)): current_use = m-(broken-len(ways[i][1]))-(ways[i][0]-len(ways[i][1])) if current_use < min_uses: indexofmin = i min_uses = current_use print(min_uses) for j in range(len(ways[indexofmin][1])): for i in range(len(edges)): if edges[i][0] == ways[indexofmin][1][j][0] and edges[i][1] == ways[indexofmin][1][j][1]: edges[i] = [-1] for j in range(len(ways[indexofmin][2])): for i in range(len(edges)): if edges[i] != -1: if ways[indexofmin][2][j][0] == edges[i][0] and ways[indexofmin][2][j][1] == edges[i][1]: edges[i] = [-1] for i in edges: if i[0] != -1: if i[2] != 0: print(i[0],i[1], 0) def obx(current_ct, steps,used): global graph global ways global to_repair global cur_min_steps if current_ct == 0 and steps <= cur_min_steps: if steps == cur_min_steps: toOut = [steps,to_repair[:],used[:]] ways.append(toOut) else: toOut = [steps,to_repair[:],used[:]] ways = [toOut[:]] cur_min_steps = steps else: for i in range(len(graph[current_ct])): if graph[current_ct][i] > 0: if graph[current_ct][i] == 2: graph[current_ct][i] *= -1 graph[i][current_ct] *= -1 to_repair.append([min(current_ct+1, i+1),max(current_ct+1, i+1)]) used.append([min(current_ct+1, i+1), max(current_ct+1, i+1)]) obx(i, steps+1,used) used.pop() to_repair.pop() graph[current_ct][i] *= -1 graph[i][current_ct] *= -1 else: graph[current_ct][i] *= -1 graph[i][current_ct] *= -1 used.append([min(current_ct+1, i+1), max(current_ct+1, i+1)]) obx(i, steps+1,used) used.pop() graph[current_ct][i] *= -1 graph[i][current_ct] *= -1 main() ``` No
104,038
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? Input The first line of input contains two integers n, m (2 ≀ n ≀ 105, <image>), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. Output In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. Examples Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 Note In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Submitted Solution: ``` def main(): global graph global ways global to_repair ways = [] n, m = list(map(int,input().split())) graph = [0]*n broken = 0 edges = [] for i in range(n): graph[i] = [0]*n for i in range(m): rdl = list(map(int,input().split())) edges.append([min(rdl[0],rdl[1]), max(rdl[0],rdl[1]),rdl[2]]) if rdl[2] == 0: graph[rdl[0]-1][rdl[1]-1] = 2 graph[rdl[1]-1][rdl[0]-1] = 2 broken += 1 else: graph[rdl[0]-1][rdl[1]-1] = 1 graph[rdl[1]-1][rdl[0]-1] = 1 to_repair = [] global cur_min_steps cur_min_steps = 100000000000 obx(n-1, 0, []) min_uses = 10000000000 indexofmin = 0 print(ways) print(edges) for i in range(len(ways)): print(broken, len(ways[i][1]), ways[i][0]) current_use = m-(broken-len(ways[i][1]))-(ways[i][0]-len(ways[i][1])) print(current_use) if current_use < min_uses: indexofmin = i min_uses = current_use print(min_uses) for j in range(len(ways[indexofmin][1])): print(ways[indexofmin][1][j][0],ways[indexofmin][1][j][1], 1) for i in range(len(edges)): if edges[i][0] == ways[indexofmin][1][j][0] and edges[i][1] == ways[indexofmin][1][j][1]: edges[i] = [-1] for j in range(len(ways[indexofmin][2])): for i in range(len(edges)): if edges[i] != -1: if ways[indexofmin][2][j][0] == edges[i][0] and ways[indexofmin][2][j][1] == edges[i][1]: edges[i] = [-1] for i in edges: if i[0] != -1: if i[2] != 0: print(i[0],i[1], 0) def obx(current_ct, steps,used): global graph global ways global to_repair global cur_min_steps if current_ct == 0 and steps <= cur_min_steps: if steps == cur_min_steps: toOut = [steps,to_repair[:],used[:]] ways.append(toOut) else: toOut = [steps,to_repair[:],used[:]] ways = [toOut[:]] cur_min_steps = steps else: for i in range(len(graph[current_ct])): if graph[current_ct][i] > 0: if graph[current_ct][i] == 2: graph[current_ct][i] *= -1 graph[i][current_ct] *= -1 to_repair.append([min(current_ct+1, i+1),max(current_ct+1, i+1)]) used.append([min(current_ct+1, i+1), max(current_ct+1, i+1)]) obx(i, steps+1,used) used.pop() to_repair.pop() graph[current_ct][i] *= -1 graph[i][current_ct] *= -1 else: graph[current_ct][i] *= -1 graph[i][current_ct] *= -1 used.append([min(current_ct+1, i+1), max(current_ct+1, i+1)]) obx(i, steps+1,used) used.pop() graph[current_ct][i] *= -1 graph[i][current_ct] *= -1 main() ``` No
104,039
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust? Input The first line of input contains two integers n, m (2 ≀ n ≀ 105, <image>), the number of cities and number of roads respectively. In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not. Output In the first line output one integer k, the minimum possible number of roads affected by gang. In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n. If there are multiple optimal answers output any. Examples Input 2 1 1 2 0 Output 1 1 2 1 Input 4 4 1 2 1 1 3 0 2 3 1 3 4 1 Output 3 1 2 0 1 3 1 2 3 0 Input 8 9 1 2 0 8 3 0 2 3 1 1 4 1 8 7 0 1 5 1 4 6 1 5 7 0 6 8 0 Output 3 2 3 0 1 5 0 6 8 1 Note In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8 Submitted Solution: ``` from heapq import heappush, heappop def dijkstra(n, m, vertices,edges): d = [] f = [None] * (n+1) g = [] for i in range(n+1): g.append(0) pre = [None] * (n+1) f[1] = 0 g[1] = 0 heappush(d,1) while (len(d) != 0): v = heappop(d) for i in range(len(vertices[v])): u = vertices[v][i][0] w = vertices[v][i][1] if(f[u] is None): f[u] = f[v] + 1 g[u] = g[v] + w pre[u] = v heappush(d,u) elif (f[u] == f[v] + 1): if (g[v] + w > g[u]): g[u] = g[v] + w pre[u] = v total = f[n] + m - 2*g[n] print(total) #ss = "" i = n #ss = str(n) while (i != 1): #print("i,pre[i]",i,pre[i]) if i < pre[i]: if (edges[i][pre[i]] == 2): edges[i][pre[i]] = 1 elif (edges[i][pre[i]] == 0): edges[i][pre[i]] = -1 else: if (edges[pre[i]][i] == 2): edges[pre[i]][i] = 1 elif (edges[pre[i]][i] == 0): edges[pre[i]][i] = -1 i = pre[i] #print(edges) for i in range(1,n+1): for j in range(1,n+1): if (edges[i][j] is not None) and (edges[i][j] == 0 or edges[i][j] == 1): print(i,j,edges[i][j]) #print(ss) def F(): tmp = input() tmp = tmp.split() n = int(tmp[0]) m = int(tmp[1]) vertices = [] edges = [] for i in range(n+1): vertices.append([]) edges.append([]) for j in range(n+1): edges[i].append(None) working_path = 0 for i in range(m): tmp = input() tmp = tmp.split() tmp = list(map(int,tmp)) if (tmp[2] == 1): working_path += 1 if (tmp[0] < tmp[1]): edges[tmp[0]][tmp[1]] = 0 else: edges[tmp[1]][tmp[0]] = 0 else: if (tmp[0] < tmp[1]): edges[tmp[0]][tmp[1]] = 2 else: edges[tmp[1]][tmp[0]] = 2 vertices[tmp[0]].append((tmp[1],tmp[2])) vertices[tmp[1]].append((tmp[0],tmp[2])) #print(edges) dijkstra(n,working_path,vertices,edges) if __name__ == "__main__": F() ``` No
104,040
Provide tags and a correct Python 3 solution for this coding contest problem. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Tags: greedy, implementation, math Correct Solution: ``` import sys n = int(input()) min1, max1 = map(int, input().split(" ")) min2, max2 = map(int, input().split(" ")) min3, max3 = map(int, input().split(" ")) a1 = a2 = a3 = 0 a3 = min3 a2 = min2 a1 = min1 rem = n - (a1 + a2 + a3) if rem >= max1 - a1: rem-=(max1-a1) a1 = max1 if(rem == 0): print(str(a1) + " " + str(a2) + " " + str(a3)) sys.exit(0) else: if rem >= max2 - a2: rem -= max2-a2 a2 = max2 if rem == 0: print(str(a1) + " " + str(a2) + " " + str(a3)) sys.exit(0) else: a3 += rem print(str(a1) + " " + str(a2) + " " + str(a3)) sys.exit(0) else: a2+= rem print(str(a1) + " " + str(a2) + " " + str(a3)) sys.exit(0) else: a1+=rem print(str(a1) + " " + str(a2) + " " + str(a3)) ```
104,041
Provide tags and a correct Python 3 solution for this coding contest problem. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Tags: greedy, implementation, math Correct Solution: ``` #!/usr/bin/python3 import itertools as ittls from collections import Counter import re import math def sqr(x): return x*x def inputarray(func=int): return map(func, input().split()) # -------------------------------------- # -------------------------------------- N = int(input()) x1, y1 = inputarray() x2, y2 = inputarray() x3, y3 = inputarray() def split(N, x1, y1, x2, y2): if N - y1 >= x2: return (y1, N - y1) else: return (N - x2, x2) a1, x = split(N, x1, y1, x2 + x3, y2 + y3) a2, a3 = split(x, x2, y2, x3, y3) print(a1, a2, a3) ```
104,042
Provide tags and a correct Python 3 solution for this coding contest problem. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Tags: greedy, implementation, math Correct Solution: ``` int_total_diplomas = int(input()) degree_1 = list(map(int, list(input().split()))) degree_2 = list(map(int, list(input().split()))) degree_3 = list(map(int, list(input().split()))) min_degree_1 = degree_1[0] max_degree_1 = degree_1[1] min_degree_2 = degree_2[0] max_degree_2 = degree_2[1] min_degree_3 = degree_3[0] max_degree_3 = degree_3[1] degree_1_total = min_degree_1 degree_2_total = min_degree_2 degree_3_total = min_degree_3 def calculate_diplomas(int_total_diplomas,degree_1_total,degree_2_total, degree_3_total,max_degree_1,max_degree_2): if int_total_diplomas <= degree_2_total + degree_3_total + max_degree_1: degree_1_total = int_total_diplomas - degree_2_total - degree_3_total print(degree_1_total,degree_2_total,degree_3_total) return else : degree_1_total = max_degree_1 if int_total_diplomas <= degree_1_total + degree_3_total + max_degree_2: degree_2_total = int_total_diplomas - degree_1_total - degree_3_total print(degree_1_total,degree_2_total,degree_3_total) return else: degree_2_total = max_degree_2 degree_3_total = int_total_diplomas - degree_2_total - degree_1_total print(degree_1_total,degree_2_total,degree_3_total) return calculate_diplomas(int_total_diplomas,degree_1_total,degree_2_total, degree_3_total,max_degree_1,max_degree_2) ```
104,043
Provide tags and a correct Python 3 solution for this coding contest problem. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Tags: greedy, implementation, math Correct Solution: ``` n = int(input()) m1 = list(map(int, input().split())) m2 = list(map(int, input().split())) m3 = list(map(int, input().split())) a1 = m1[0] a2 = m2[0] a3 = m3[0] if a1 + a2 + a3 == n: print(a1, a2, a3) else: if m1[1] + a2 + a3 >= n: a1 = n - a2 - a3 print(a1, a2, a3) else: a1 = m1[1] if a1 + m2[1] + a3 >= n: a2 = n - a1 - a3 print(a1, a2, a3) else: a2 = m2[1] a3 = n - a1 - a2 print(a1, a2, a3) ```
104,044
Provide tags and a correct Python 3 solution for this coding contest problem. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Tags: greedy, implementation, math Correct Solution: ``` n = int(input()) min1, max1 = map(int, input().split()) min2, max2 = map(int, input().split()) min3, max3 = map(int, input().split()) answer = [min1, min2, min3] if sum(answer) < n: answer[0] += min(max1 - min1, n - sum(answer)) if sum(answer) < n: answer[1] += min(max2 - min2, n - sum(answer)) if sum(answer) < n: answer[2] += min(max3 - min3, n - sum(answer)) print(answer[0], answer[1], answer[2]) ```
104,045
Provide tags and a correct Python 3 solution for this coding contest problem. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Tags: greedy, implementation, math Correct Solution: ``` n = int(input()) min1, max1 = map(int, input().split()) min2, max2 = map(int, input().split()) min3, max3 = map(int, input().split()) remaining1 = max1 - min1 remaining2 = max2 - min2 remaining3 = max3 - min3 sum1 = min1 sum2 = min2 sum3 = min3 remaining_sum = n - min1 - min2 - min3 if remaining_sum == 0: print(sum1, sum2, sum3) else: if remaining_sum <= remaining1: sum1 += remaining_sum else: sum1 += remaining1 remaining_sum -= remaining1 if remaining_sum <= remaining2: sum2 += remaining_sum else: sum2 += remaining2 sum3 += (remaining_sum - remaining2) print(sum1, sum2, sum3) ```
104,046
Provide tags and a correct Python 3 solution for this coding contest problem. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Tags: greedy, implementation, math Correct Solution: ``` n = int(input()) min1, max1 = map(int, input().split(' ')) min2, max2 = map(int, input().split(' ')) min3, max3 = map(int, input().split(' ')) n1, n2, n3 = min1, min2, min3 if n1+n2+n3 < n: n1 = max1 if n1+n2+n3 > n: n1 -= (n1+n2+n3)-n else: n2 = max2 if n1+n2+n3 > n: n2 -= (n1+n2+n3) - n else: n3 = max3 if n1+n2+n3 > n: n3 -= (n1+n2+n3) - n print(n1, n2, n3) ```
104,047
Provide tags and a correct Python 3 solution for this coding contest problem. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Tags: greedy, implementation, math Correct Solution: ``` I=lambda:map(int,input().split()) n=next(I()) a,b=I() c,d=I() f,e=I() x=min(b,n-c-f) y=min(d,n-x-f) print(x,y,n-x-y) # Made By Mostafa_Khaled ```
104,048
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Submitted Solution: ``` n = int(input()) min1, max1 = map(int, input().split()) min2, max2 = map(int, input().split()) min3, max3 = map(int, input().split()) d1 = min(n - min2 - min3, max1) d2 = min(n - d1 - min3, max2) d3 = n - d1 - d2 print(d1,d2,d3) ``` Yes
104,049
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Submitted Solution: ``` n=int(input()) arr=[] for i in range(3): a,b=map(int,input().split(' ')) arr.append((a,b)) a1=0 a2=arr[1][0] a3=arr[2][0] a1=min(n-a2-a3,arr[0][1]) a2=min(n-a1-a3,arr[1][1]) a3=min(n-a1-a2,arr[2][1]) print(a1,a2,a3) ``` Yes
104,050
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Submitted Solution: ``` n = int(input()) d1 = input().split() min1, max1 = int(d1[0]), int(d1[1]) d1 = input().split() min2, max2 = int(d1[0]), int(d1[1]) d1 = input().split() min3, max3 = int(d1[0]), int(d1[1]) di1 = min1 di2 = min2 di3 = min3 di1 += min((max1 - min1), (n - (di1 + di2 + di3))) di2 += min((max2 - min2), (n - (di1 + di2 + di3))) di3 += min((max3 - min3), (n - (di1 + di2 + di3))) print(di1, di2, di3) ``` Yes
104,051
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Submitted Solution: ``` __author__ = 'Π”Π°Π½ΠΈΠ»Π°' n = int(input()) min1, max1 = map(int, input().split()) min2, max2 = map(int, input().split()) min3, max3 = map(int, input().split()) ans1 = min(max1, n - min2 - min3) n -= ans1 ans2 = min(max2, n - min3) ans3 = n - ans2 print(ans1, ans2, ans3) ``` Yes
104,052
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Submitted Solution: ``` def sinput(): s = input().split() return int(s[0]), int(s[1]) n = int(input()) mina, maxa = sinput() minb, maxb = sinput() minc, maxc = sinput() la = mina ra = maxa+1 while ra -la >1: m = int((la +ra)/2) if n -m in range(minb +minc, maxb +maxc+1): la = m else: ra = m n -= la lb = max(minb, n - maxc) rb = maxb+1 while rb -lb >1: m = int((lb +rb)/2) if n -m in range(minc, maxc+1): lb = m else: rb = m print(la, lb, n - lb) ``` No
104,053
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Submitted Solution: ``` n=int(input()) a=[] for i in range(3): a.append(list(map(int,input().split()))) k=a[0][0]+a[1][0]+a[2][0] m=a[0][1]+a[1][1]+a[2][1] x=n-k for i in range(3): if x<=a[i][1]: print(a[i][0]+x,end=' ') x=0 else: print(a[i][1],end=' ') x-=(a[i][1]-a[i][0]) ``` No
104,054
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Submitted Solution: ``` n = int(input()) a,b = map(int,input().split()) c,d = map(int,input().split()) e,f = map(int,input().split()) if a+c+e == n: print(a,end=' ') print(b,end=' ') print(c,end=' ') elif b+d+f==n: print(b,end=' ') print(d,end=' ') print(f,end=' ') else: third = min(n-(a+c),f) second = min(n-third-a,d) first = n-(third+second) print(first,end=' ') print(second,end=' ') print(third,end=' ') ``` No
104,055
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma. They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree. After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree. Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations. It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree. Input The first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106) β€” the number of schoolchildren who will participate in the Olympiad. The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the first degree that can be distributed. The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106) β€” the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3. Output In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas. The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree. Examples Input 6 1 5 2 6 3 7 Output 1 2 3 Input 10 1 2 1 3 1 5 Output 2 3 5 Input 6 1 3 2 2 2 2 Output 2 2 2 Submitted Solution: ``` def console_line_to_int_arr(string): return [int(i) for i in string.split(" ")] ######################## n = int(input()) arr = [console_line_to_int_arr(input()), console_line_to_int_arr(input()), console_line_to_int_arr(input())] n = n - arr[0][0] - arr[1][0] - arr[2][0] for i in arr: print(arr, n) if n > 0: n = n - (i[1] - i[0]) if n >= 0: i[0] = i[0] + (i[1] - i[0]) else: i[0] = i[0] - n print(str(arr[0][0]) + " " + str(arr[1][0]) + " " + str(arr[2][0])) ``` No
104,056
Provide tags and a correct Python 3 solution for this coding contest problem. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Tags: combinatorics, dfs and similar, dsu, math, number theory Correct Solution: ``` import sys # sys.stdin = open('data/D.in', 'r') T = 1 M = 1000000007 def process(): P, K = list(map(int, input().split())) k = [K * x % P for x in range(P)] # print(k) # f(0) = k[f(0)] # f(1) = k[f(4)] # f(2) = k[f(3)] # f(3) = k[f(2)] # f(4) = k[f(1)] if not K: print(pow(P, P - 1, M)) return f = [0] * P c = [0] * P ans = 1 for i in range(0, P): if f[i]: continue cnt = 1 u = i f[u] = 1 while not f[k[u]]: u = k[u] f[u] = 1 cnt = cnt + 1 c[cnt] = c[cnt] + 1 # print(c) for i in range(1, P): if c[i] != 0: cnt = i * c[i] + (1 if i > 1 else 0) ans = ans * pow(cnt, c[i], M) % M print(ans) for _ in range(T): process() ```
104,057
Provide tags and a correct Python 3 solution for this coding contest problem. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Tags: combinatorics, dfs and similar, dsu, math, number theory Correct Solution: ``` __author__ = 'MoonBall' import sys # sys.stdin = open('data/D.in', 'r') T = 1 M = 1000000007 def process(): P, K = list(map(int, input().split())) k = [K * x % P for x in range(P)] # print(k) # f(0) = k[f(0)] # f(1) = k[f(4)] # f(2) = k[f(3)] # f(3) = k[f(2)] # f(4) = k[f(1)] if not K: print(pow(P, P - 1, M)) return f = [0] * P c = [0] * P ans = 1 for i in range(0, P): if f[i]: continue cnt = 1 u = i f[u] = 1 while not f[k[u]]: u = k[u] f[u] = 1 cnt = cnt + 1 c[cnt] = c[cnt] + 1 # print(c) for i in range(1, P): if c[i] != 0: cnt = i * c[i] + (c[1] if i > 1 else 0) ans = ans * pow(cnt, c[i], M) % M print(ans) for _ in range(T): process() ```
104,058
Provide tags and a correct Python 3 solution for this coding contest problem. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Tags: combinatorics, dfs and similar, dsu, math, number theory Correct Solution: ``` import math def expmod(base, expon, mod): ans = 1 for i in range(1, expon + 1): ans = (ans * base) % mod return ans p, k = input().split() s = 10 ** 9 + 7 k = int(k) p = int(p) ord = 1 done = 0 if k == 0: z = p - 1 if k == 1: z = p else: for i in range(2,p + 1): if done == 0: if (p-1) % i == 0: if expmod(k, i, p) == 1: ord = i done = 1 z = int((p-1) / ord) rem = expmod(p, z, s) print(int(rem)) ```
104,059
Provide tags and a correct Python 3 solution for this coding contest problem. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Tags: combinatorics, dfs and similar, dsu, math, number theory Correct Solution: ``` def main(): t = 1 a = k if k == 0: return n - 1 if k == 1: return n while a != 1: a = a * k % n t += 1 p = (n - 1) // t return p n, k = map(int, input().split()) mod = 10 ** 9 + 7 p = main() print(pow(n, p, mod)) ```
104,060
Provide tags and a correct Python 3 solution for this coding contest problem. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Tags: combinatorics, dfs and similar, dsu, math, number theory Correct Solution: ``` MOD = 10**9+7 def f(a,b): if b == 1: return a%MOD elif b % 2 == 0: return f((a*a)%MOD,b//2) else: return (a*f((a*a)%MOD,b//2)) % MOD p,k = map(int,input().split()) if k == 0: print(f(p,p-1)) exit() if k == 1: print(f(p,p)) exit() t = 1 a = k while a != 1: a = (a*k % p) t += 1 n = (p-1)//t print(f(p,n)) ```
104,061
Provide tags and a correct Python 3 solution for this coding contest problem. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Tags: combinatorics, dfs and similar, dsu, math, number theory Correct Solution: ``` M = 10**9 + 7 def period(p, k): c = 1 ek = k while ek != 1: ek = (ek * k) % p c += 1 return c def functions(p, k): if k == 0: return pow(p, p-1, M) elif k == 1: return pow(p, p, M) else: c = (p-1)//period(p, k) return pow(p, c, M) if __name__ == '__main__': p, k = map(int, input().split()) print(functions(p, k)) ```
104,062
Provide tags and a correct Python 3 solution for this coding contest problem. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Tags: combinatorics, dfs and similar, dsu, math, number theory Correct Solution: ``` MOD=int(1e9+7) n,k=map(int,input().split()) if k==0: p=n-1 elif k==1: p=n else: t=1 a=k while a!=1: a=a*k%n t+=1 p=(n-1)//t print(pow(n,p,MOD)) ```
104,063
Provide tags and a correct Python 3 solution for this coding contest problem. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Tags: combinatorics, dfs and similar, dsu, math, number theory Correct Solution: ``` __author__ = 'MoonBall' import sys # sys.stdin = open('data/D.in', 'r') T = 1 M = 1000000007 def process(): P, K = list(map(int, input().split())) k = [K * x % P for x in range(P)] # print(k) # f(0) = k[f(0)] # f(1) = k[f(4)] # f(2) = k[f(3)] # f(3) = k[f(2)] # f(4) = k[f(1)] if not K: print(pow(P, P - 1, M)) return f = [0] * P c = [0] * P ans = 1 for i in range(0, P): if f[i]: continue cnt = 1 u = i f[u] = 1 while not f[k[u]]: u = k[u] f[u] = 1 cnt = cnt + 1 c[cnt] = c[cnt] + 1 # print(c) for i in range(1, P): if c[i] != 0: cnt = i * c[i] + (1 if i > 1 else 0) ans = ans * pow(cnt, c[i], M) % M print(ans) for _ in range(T): process() ```
104,064
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Submitted Solution: ``` c=1000000007 #special cases for k=0, 1 p, k = map(int, input().split(" ")) """def binary(number): #turn into string s="" while number!=0: r = number%2 s = str(r) + s number = number//2 return s def mod(base, expo, mod): #write expo as binary and calculate to the power of 2 power ans=1 s=binary(expo) l=len(s) #calculate a list of remainders of length l mods = [] current=base for i in range (l): mods = [current] + mods current = (current**2) % mod #print(mods, s) for i in range (l): if s[i] == "1": ans *= mods[i] #print(ans) ans = ans%mod return ans """ if k==0: answer=pow(p, p-1, c) elif k==1: answer=pow(p, p, c) else: #counted = [False] * (p-1) size = 1 """def modify(init): global counted new=init*k new = new%p counted[init-1]=True while new!=init: #print(new) counted[new-1]=True new=new*k new = new%p #print(new) for j in range (p-1): if counted[j]==False: i=j+1 #print("i", i) modify(i) #print(counted) cycles+=1 """ new=k while new!=1: size+=1 new*=k new=new%p cycles = (p-1)//size #print(cycles) answer=pow(p, cycles, c) #too slow, issue is not with mod #fuck python and fuck c++ dont have time to recode this in c++ why can't python be faster print(answer) ``` Yes
104,065
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Submitted Solution: ``` p,k=map(int,input().split()) res=set() ex=p-1 if k!=0: if k==1: ex=p else: c=k for i in range(p): res.add(c) c*=k c%=p ex=(p-1)//len(res) ans=1 for i in range(ex): ans*=p ans%=1000000007 print(ans) ``` Yes
104,066
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Submitted Solution: ``` __author__ = 'MoonBall' import sys # sys.stdin = open('data/D.in', 'r') T = 1 M = 1000000007 def pow(x, y, m): if y == 0: return 1 if (y & 1): return pow(x, y - 1, m) * x % m else: t = pow(x, y >> 1, m) return t * t % m def process(): P, K = list(map(int, input().split())) k = [K * x % P for x in range(P)] # print(k) # f(0) = k[f(0)] # f(1) = k[f(4)] # f(2) = k[f(3)] # f(3) = k[f(2)] # f(4) = k[f(1)] if not K: print(pow(P, P - 1, M)) return if K == 1: print(pow(P, P, M)) return f = [0] * P c = [0] * P ans = 1 for i in range(P): if f[i]: continue cnt = 1 u = i f[u] = 1 while not f[k[u]]: u = k[u] f[u] = 1 cnt = cnt + 1 c[cnt] = c[cnt] + 1 # print(c) for i in range(2, P): if c[i] != 0: cnt = i * c[i] + 1 ans = ans * pow(cnt, c[i], M) % M print(ans) for _ in range(T): process() ``` Yes
104,067
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Submitted Solution: ``` def m_pow(x, y, m): if y == 0: return 1 if (y & 1): return m_pow(x, y - 1, m) * x % m else: t = m_pow(x, y >> 1, m) return t * t % m # (p, k) = map(int, input().split()) used = [0] * p if k == 0: print(m_pow(p, p - 1, 1000000007)) else: c = 1 if k == 1 else 0 for x in range(1, p): if not used[x]: y = x while not used[y]: used[y] = True y = k * y % p c += 1 print(m_pow(p, c, 1000000007)) ``` Yes
104,068
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Submitted Solution: ``` MOD = 10**9+7 p,k = map(int,input().split()) bool = False for i in range(1,p): if (i**2-k) % p == 0: bool = True break if bool: print((p*p)%MOD) else: print(p) ``` No
104,069
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Submitted Solution: ``` p,k = map(int,input().split()) m = 10**9+7 if k == 0: print(pow(p,p-1,m)) else: used = set() res = 0 for i in range(1, p): a = i if a not in used: res += 1 while a not in used: used.add(a) a = k * a % p print(pow(p, res, m)) ``` No
104,070
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Submitted Solution: ``` __author__ = 'MoonBall' import sys # sys.stdin = open('data/D.in', 'r') T = 1 M = 1000000007 def process(): P, K = list(map(int, input().split())) k = [K * x % P for x in range(P)] # print(k) # f(0) = k[f(0)] # f(1) = k[f(4)] # f(2) = k[f(3)] # f(3) = k[f(2)] # f(4) = k[f(1)] if not K: print(pow(P, P - 1, M)) return f = [0] * P c = [0] * P ans = 1 for i in range(1, P): if f[i]: continue cnt = 1 u = i f[u] = 1 while not f[k[u]]: u = k[u] f[u] = 1 cnt = cnt + 1 c[cnt] = c[cnt] + 1 # print(c) for i in range(1, P): if c[i] != 0: cnt = i * c[i] + 1 ans = ans * pow(cnt, c[i], M) % M print(ans) for _ in range(T): process() ``` No
104,071
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0. Submitted Solution: ``` import math def expmod(base, expon, mod): ans = 1 for i in range(1, expon + 1): ans = (ans * base) % mod return ans p, k = input().split() k = int(k) p = int(p) ord = 1 done = 0 if k == 0: z = p - 1 else: for i in range(1,int((p-1) ** (0.5))+2): if done == 0: if (p-1) % i == 0: if expmod(k, i, p) == 1: ord = i done = 1 z = int((p-1) / ord) rem = expmod(p, z, 1000000007) print(int(rem)) ``` No
104,072
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. My name is James diGriz, I'm the most clever robber and treasure hunter in the whole galaxy. There are books written about my adventures and songs about my operations, though you were able to catch me up in a pretty awkward moment. I was able to hide from cameras, outsmart all the guards and pass numerous traps, but when I finally reached the treasure box and opened it, I have accidentally started the clockwork bomb! Luckily, I have met such kind of bombs before and I know that the clockwork mechanism can be stopped by connecting contacts with wires on the control panel of the bomb in a certain manner. I see n contacts connected by n - 1 wires. Contacts are numbered with integers from 1 to n. Bomb has a security mechanism that ensures the following condition: if there exist k β‰₯ 2 contacts c1, c2, ..., ck forming a circuit, i. e. there exist k distinct wires between contacts c1 and c2, c2 and c3, ..., ck and c1, then the bomb immediately explodes and my story ends here. In particular, if two contacts are connected by more than one wire they form a circuit of length 2. It is also prohibited to connect a contact with itself. On the other hand, if I disconnect more than one wire (i. e. at some moment there will be no more than n - 2 wires in the scheme) then the other security check fails and the bomb also explodes. So, the only thing I can do is to unplug some wire and plug it into a new place ensuring the fact that no circuits appear. I know how I should put the wires in order to stop the clockwork. But my time is running out! Help me get out of this alive: find the sequence of operations each of which consists of unplugging some wire and putting it into another place so that the bomb is defused. Input The first line of the input contains n (2 ≀ n ≀ 500 000), the number of contacts. Each of the following n - 1 lines contains two of integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi) denoting the contacts currently connected by the i-th wire. The remaining n - 1 lines contain the description of the sought scheme in the same format. It is guaranteed that the starting and the ending schemes are correct (i. e. do not contain cicuits nor wires connecting contact with itself). Output The first line should contain k (k β‰₯ 0) β€” the minimum number of moves of unplugging and plugging back some wire required to defuse the bomb. In each of the following k lines output four integers ai, bi, ci, di meaning that on the i-th step it is neccesary to unplug the wire connecting the contacts ai and bi and plug it to the contacts ci and di. Of course the wire connecting contacts ai and bi should be present in the scheme. If there is no correct sequence transforming the existing scheme into the sought one, output -1. Examples Input 3 1 2 2 3 1 3 3 2 Output 1 1 2 1 3 Input 4 1 2 2 3 3 4 2 4 4 1 1 3 Output 3 1 2 1 3 4 3 4 1 2 3 2 4 Note Picture with the clarification for the sample tests: <image> Submitted Solution: ``` #!/usr/bin/python3 # -*- config:utf-8 -*- import sys import re # exception type for wrong input data class IncorrectDataException(Exception): pass # transform graph without circles to tree def createtree(cnt,data): data=[[int(y) for y in x.split(' ')] for x in data] edges={} backtrace={} for i in range(1,cnt+1): edges[i]={} backtrace[i]={} for edge in data: edges[edge[0]][edge[1]]=1 edges[edge[1]][edge[0]]=1 backtrace[edge[0]][edge[1]]=1 backtrace[edge[1]][edge[0]]=1 stack=[1] while stack: srcvert=stack.pop(-1) for destvert in edges[srcvert].keys(): stack.append(destvert) edges[destvert].pop(srcvert) backtrace[srcvert].pop(destvert) return edges,backtrace # get source data def getSrcData(): f = sys.stdin buf = f.read() sample=re.compile(r'^\d+\n(\d+ \d+\n)+',re.MULTILINE) data=sample.match(buf) if not (data): raise IncorrectDataException("Incorrect source data: %s" % buf) buf=data.group(0) buf=buf.split('\n') cnt=int(buf[0]) src=buf[1:cnt] trg=buf[cnt:(cnt*2-1)] src,srcbacktrace=createtree(cnt,src) trg,trgbacktrace=createtree(cnt,trg) trgbacktrace=None return src,srcbacktrace,trg # find transform src tree to trg tree def getTransform(src,srcbacktrace,trg): result='' srcvert=1 stack=[1] while stack: srcvert=stack.pop(-1) stack.reverse() for destvert in trg[srcvert].keys(): stack.append(destvert) if not destvert in src[srcvert]: src4destvert=list(srcbacktrace[destvert].keys())[0] # get edge <src4destvert,destvert> in src tree # change found edge for <srcvert,destvert> # src[src4destvert][destvert]=0 # src[srcvert][destvert]=1 result+=str(src4destvert)+" "+str(destvert)+" "+str(srcvert)+" "+str(destvert)+"\n" stack.reverse() return result,src # save result def saveResult(result): f = sys.stdout f.write(str(result) + '\n') f.flush() # start def run(): src,srcbacktrace,trg=getSrcData() result,src=getTransform(src,srcbacktrace,trg) cnt=result.count('\n') result=str(cnt)+'\n'+result saveResult(result) if __name__ == '__main__': run() ``` No
104,073
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. My name is James diGriz, I'm the most clever robber and treasure hunter in the whole galaxy. There are books written about my adventures and songs about my operations, though you were able to catch me up in a pretty awkward moment. I was able to hide from cameras, outsmart all the guards and pass numerous traps, but when I finally reached the treasure box and opened it, I have accidentally started the clockwork bomb! Luckily, I have met such kind of bombs before and I know that the clockwork mechanism can be stopped by connecting contacts with wires on the control panel of the bomb in a certain manner. I see n contacts connected by n - 1 wires. Contacts are numbered with integers from 1 to n. Bomb has a security mechanism that ensures the following condition: if there exist k β‰₯ 2 contacts c1, c2, ..., ck forming a circuit, i. e. there exist k distinct wires between contacts c1 and c2, c2 and c3, ..., ck and c1, then the bomb immediately explodes and my story ends here. In particular, if two contacts are connected by more than one wire they form a circuit of length 2. It is also prohibited to connect a contact with itself. On the other hand, if I disconnect more than one wire (i. e. at some moment there will be no more than n - 2 wires in the scheme) then the other security check fails and the bomb also explodes. So, the only thing I can do is to unplug some wire and plug it into a new place ensuring the fact that no circuits appear. I know how I should put the wires in order to stop the clockwork. But my time is running out! Help me get out of this alive: find the sequence of operations each of which consists of unplugging some wire and putting it into another place so that the bomb is defused. Input The first line of the input contains n (2 ≀ n ≀ 500 000), the number of contacts. Each of the following n - 1 lines contains two of integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi) denoting the contacts currently connected by the i-th wire. The remaining n - 1 lines contain the description of the sought scheme in the same format. It is guaranteed that the starting and the ending schemes are correct (i. e. do not contain cicuits nor wires connecting contact with itself). Output The first line should contain k (k β‰₯ 0) β€” the minimum number of moves of unplugging and plugging back some wire required to defuse the bomb. In each of the following k lines output four integers ai, bi, ci, di meaning that on the i-th step it is neccesary to unplug the wire connecting the contacts ai and bi and plug it to the contacts ci and di. Of course the wire connecting contacts ai and bi should be present in the scheme. If there is no correct sequence transforming the existing scheme into the sought one, output -1. Examples Input 3 1 2 2 3 1 3 3 2 Output 1 1 2 1 3 Input 4 1 2 2 3 3 4 2 4 4 1 1 3 Output 3 1 2 1 3 4 3 4 1 2 3 2 4 Note Picture with the clarification for the sample tests: <image> Submitted Solution: ``` #!/usr/bin/python3 # -*- config:utf-8 -*- import sys import re # exception type for wrong input data class IncorrectDataException(Exception): pass # transform graph without circles to tree def createtree(cnt,data,curvert): data=[[int(y) for y in x.split(' ')] for x in data] edges={} backtrace={} for i in range(1,cnt+1): edges[i]={} backtrace[i]={} for edge in data: edges[edge[0]][edge[1]]=1 edges[edge[1]][edge[0]]=1 backtrace[edge[0]][edge[1]]=1 backtrace[edge[1]][edge[0]]=1 if not curvert: cnt=0 for i in edges.keys(): if len(edges[i])>cnt: cnt=len(edges[i]) curvert=i stack=[curvert] while stack: srcvert=stack.pop(-1) for destvert in edges[srcvert].keys(): stack.append(destvert) edges[destvert].pop(srcvert) backtrace[srcvert].pop(destvert) return edges,backtrace,curvert # get source data def getSrcData(): f = sys.stdin buf = f.read() sample=re.compile(r'^\d+\n(\d+ \d+\n)+',re.MULTILINE) data=sample.match(buf) if not (data): raise IncorrectDataException("Incorrect source data: %s" % buf) buf=data.group(0) buf=buf.split('\n') cnt=int(buf[0]) src=buf[1:cnt] trg=buf[cnt:(cnt*2-1)] trg,trgbacktrace,curvert=createtree(cnt,trg,0) src,srcbacktrace,curvert=createtree(cnt,src,curvert) trgbacktrace=None return src,srcbacktrace,trg,curvert # find transform src tree to trg tree def getTransform(src,srcbacktrace,trg,curvert): result='' stack=[curvert] while stack: srcvert=stack.pop(-1) stack.reverse() for destvert in trg[srcvert].keys(): stack.append(destvert) if not destvert in src[srcvert]: src4destvert=list(srcbacktrace[destvert].keys())[0] # get edge <src4destvert,destvert> in src tree # change found edge for <srcvert,destvert> # src[src4destvert][destvert]=0 # src[srcvert][destvert]=1 result+=str(src4destvert)+" "+str(destvert)+" "+str(srcvert)+" "+str(destvert)+"\n" stack.reverse() return result,src # save result def saveResult(result): f = sys.stdout f.write(str(result) + '\n') f.flush() # start def run(): src,srcbacktrace,trg,curvert=getSrcData() result,src=getTransform(src,srcbacktrace,trg,curvert) cnt=result.count('\n') result=str(cnt)+'\n'+result saveResult(result) if __name__ == '__main__': run() ``` No
104,074
Provide tags and a correct Python 3 solution for this coding contest problem. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Tags: binary search, dp, strings, two pointers Correct Solution: ``` n,k=map(int, input().split()) s=input() a=0 b=0 ans=0 x=0 for i in range(n): if s[i]=='a': a+=1 else: b+=1 if(min(a,b)<=k): ans=max(ans,a+b) else: if s[x]=='a': a-=1 else: b-=1 x+=1 print(ans) ```
104,075
Provide tags and a correct Python 3 solution for this coding contest problem. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Tags: binary search, dp, strings, two pointers Correct Solution: ``` def executa(n, k, letra, s): r = 0 tk = k p = 0 for i in range(n): while r < n and tk >= 0: if a[r] == letra: if tk == 0: break tk -= 1 r += 1 p += 1 s = max(s, p) p -= 1 if a[i] == letra: tk += 1 if r == n: break return s if __name__ == '__main__': entrada = input() entrada_str = list(entrada.split(" ")) entrada_int = list(map(int, entrada_str)) n = entrada_int[0] k = entrada_int[1] a = input() soma = executa(n, k, "b", 0) soma = executa(n, k, "a", soma) print(soma) ```
104,076
Provide tags and a correct Python 3 solution for this coding contest problem. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Tags: binary search, dp, strings, two pointers Correct Solution: ``` n, k = list(map(int, input().split())) s = input() res = 0 count_a = 0 count_b = 0 left = 0 right = 0 while True: if s[right] == 'a': count_a += 1 else: count_b += 1 if count_a <= k or count_b <= k: if right - left + 1 > res: res = right - left + 1 else: if s[left] == 'a': count_a -= 1 else: count_b -= 1 left += 1 right += 1 if n - left < res or right == n: break print(res) ```
104,077
Provide tags and a correct Python 3 solution for this coding contest problem. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Tags: binary search, dp, strings, two pointers Correct Solution: ``` def answer(n,k,A): if n==1: return 1 dp=[0]*(n+1) for i in range(1,n+1): if A[i-1]=="a": dp[i]=dp[i-1]+1 else: dp[i]=dp[i-1] l=0;r=0 maxi=0 while r>=l and r<n: x=dp[r+1]-dp[l] if min(x, r+1-l-x)<=k: r+=1 else: maxi=max(maxi,r-l) l+=1 maxi=max(maxi,r-l) return maxi n,k=map(int,input().split()) A=input() print(answer(n,k,A)) ```
104,078
Provide tags and a correct Python 3 solution for this coding contest problem. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Tags: binary search, dp, strings, two pointers Correct Solution: ``` le, ch = map(int, input().split()) st = input() ca, cb, si, mx = [0] * 4 for x in st: if x == 'a': ca += 1 else: cb += 1 if min(ca, cb) > ch: if st[si] == 'a': ca -= 1 else: cb -= 1 si += 1 else: mx += 1 print(mx) ```
104,079
Provide tags and a correct Python 3 solution for this coding contest problem. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Tags: binary search, dp, strings, two pointers Correct Solution: ``` from sys import stdin,stdout def fn(a,ch): # print(a) ans=0 for i in range(n): l,r=i,n-1 while l<=r: mid=(l+r)>>1 req=a[i]+k-int(s[i]!=ch) if a[mid]<=req:l=mid+1 else:r=mid-1 # print(i,r) ans=max(ans,r-i+1) return ans for _ in range(1):#int(stdin.readline())): # n=int(stdin.readline()) n,k=list(map(int,stdin.readline().split())) s=input() make_a=[];make_b=[] make_a+=[int(s[0]=='a')] make_b+=[int(s[0]=='b')] for i in range(1,n): make_a+=[make_a[-1]+int(s[i]=='a')] make_b+=[make_b[-1]+int(s[i]=='b')] # print(make_a) # print(make_b) ans=max(fn(make_a,'b'),fn(make_b,'a')) print(ans) ''' 10 1 bbabbabbba ''' ```
104,080
Provide tags and a correct Python 3 solution for this coding contest problem. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Tags: binary search, dp, strings, two pointers Correct Solution: ``` num = input() n, k = num.split() n = int(n) k = int(k) string = input() count_a = 0 count_b = 0 def check(ch): i = 0 j = 0 count = 0 answer = 0 for i in range(n): if(string[i] == ch): count += 1 if(count > k): while(count > k): if(string[j] == ch): count -= 1 j += 1 answer = max(answer, i-j +1) return answer max_a = check('a') max_b = check('b') print(max(max_a, max_b)) ```
104,081
Provide tags and a correct Python 3 solution for this coding contest problem. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Tags: binary search, dp, strings, two pointers Correct Solution: ``` read = lambda: map(int, input().split()) n, k = read() s = input() i = j = 0 cur = k while cur and j < n: if s[j] == 'a': cur -= 1 j += 1 while j < n and s[j] == 'b': j += 1 ans = j while j < n: while i < n and s[i] == 'b': i += 1 i += 1 j += 1 while j < n and s[j] == 'b': j += 1 ans = max(ans, j - i) i = j = 0 cur = k while cur and j < n: if s[j] == 'b': cur -= 1 j += 1 while j < n and s[j] == 'a': j += 1 ans = max(ans, j) while j < n: while i < n and s[i] == 'a': i += 1 i += 1 j += 1 while j < n and s[j] == 'a': j += 1 ans = max(ans, j - i) print(ans) ```
104,082
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Submitted Solution: ``` z,zz=input,lambda:list(map(int,z().split())) zzz=lambda:[int(i) for i in stdin.readline().split()] szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz()) from string import * from re import * from collections import * from queue import * from sys import * from collections import * from math import * from heapq import * from itertools import * from bisect import * from collections import Counter as cc from math import factorial as f from bisect import bisect as bs from bisect import bisect_left as bsl from itertools import accumulate as ac def lcd(xnum1,xnum2):return (xnum1*xnum2//gcd(xnum1,xnum2)) def prime(x): p=ceil(x**.5)+1 for i in range(2,p): if (x%i==0 and x!=2) or x==0:return 0 return 1 def dfs(u,visit,graph): visit[u]=True for i in graph[u]: if not visit[i]: dfs(i,visit,graph) ###########################---Test-Case---################################# """ """ ###########################---START-CODING---############################## n,k=zz() s=z() m=k a=s[:k].count('a') b=k-a l=0 for i in range(k,n): if s[i]=='a':a+=1 else:b+=1 while min(a,b)>k: if s[l]=='a':a-=1 else:b-=1 l+=1 m=max(m,i-l+1) print(m) ``` Yes
104,083
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Submitted Solution: ``` n, m = input().split(' ') n, m = int(n), int(m) ans = 0 s = input() for i in range(2): left, used = 0, 0 for right in range(n): if ord(s[right]) != ord('a') + i: used += 1 while used > m: if ord(s[left]) != ord('a') + i: used -= 1 left += 1 ans = max(ans, right - left + 1) print(ans) ``` Yes
104,084
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Submitted Solution: ``` def main(): n, k = liee() s = input() l, ans, h = 1, 0, n while l <= h: m = (l + h) // 2 if fun(m, n, s, k): ans, l = m, m + 1 else: h = m - 1 print(ans) def fun(m, n, s, k): a, b = s[0:m].count('a'), s[0:m].count('b') if max(a, b) + k >= m: return 1 for i in range(m, n): if s[i - m] == 'a': a -= 1 else: b -= 1 if s[i] == 'a': a += 1 else: b += 1 if max(a, b) + k >= m: return 1 return 0 def fun2(s): cnt, num = 0, s.count('0') for i in s[1:]: if i == '1': cnt += 1 elif num == 1: cnt += 1 break else: break return cnt from sys import * import inspect import re from math import * import threading from collections import * from pprint import pprint as pp mod = 998244353 MAX = 10**5 def lie(): return int(input()) def liee(): return map(int, input().split()) def array(): return list(map(int, input().split())) def deb(p): for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]: m = re.search(r'\bdeb\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line) print('%s %d' % (m.group(1), p)) def vector(size, val=0): vec = [val for i in range(size)] return vec def matrix(rowNum, colNum, val=0): mat = [] for i in range(rowNum): collumn = [val for j in range(colNum)] mat.append(collumn) return mat def dmain(): setrecursionlimit(100000000) threading.stack_size(40960000) thread = threading.Thread(target=main) thread.start() if __name__ == '__main__': # main() dmain() ``` Yes
104,085
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #################################################################################### n,k=map(int,input().split()) from bisect import bisect s=input() l1=[] l2=[] l3=[] l4=[] c,d=0,0 for i in range(n): if s[i]=='a': l1.append(i) d+=1 else: c+=1 l3.append(i) l2.append(c) l4.append(d) if len(l1)!=0 and c!=0: ans=0 ans1=0 for i in l1: a=bisect(l2,l2[i]+k) ans=max(ans,a-i) for i in l3: a=bisect(l4,l4[i]+k) ans1=max(ans1,a-i) if l1[0]==0: a=bisect(l4,k) ans1=max(ans1,a) if l3[0]==0: a=bisect(l2,k) ans=max(ans,a) else: ans=len(s) ans1=len(s) print(max(ans,ans1)) ``` Yes
104,086
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Submitted Solution: ``` aplha=[chr(i) for i in range(ord('a'),ord('z')+1)] #for _ in range(int(input())): n,k=map(int,input().split()) s=list(input()) out=0 for i in aplha: l=0 r=0 t=k while l<n and r<n: if s[r]==i: r+=1 else: if t>0: t-=1 r+=1 continue else: if s[l]==i: l+=1 else: t+=1 l+=1 out=max(out,r-l) print(out) ``` No
104,087
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Submitted Solution: ``` # !/bin/env python3 # encoding: UTF-8 # βœͺ H4WK3yEδΉ‘ # Mohd. Farhan Tahir # Indian Institute Of Information Technology and Management,Gwalior # Question Link # https://codeforces.com/problemset/problem/676/C # # ///==========Libraries, Constants and Functions=============/// import sys inf = float("inf") mod = 1000000007 def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline() # ///==========MAIN=============/// def solve(c, s, k): ans = 0 r = 0 balance = 0 for i in range(len(s)): while r < len(s) and (s[r] == c or balance < k): if s[r] != c: balance += 1 r += 1 ans = max(ans, r-i) if s[i] != c: balance -= 1 return ans def main(): n, k = get_ints() s = input() print(max(solve('a', s, k), solve('b', s, k))) if __name__ == "__main__": main() ``` No
104,088
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Submitted Solution: ``` from collections import Counter def good(s, k, l): c = Counter() for i in range(len(s)): c[s[i]] += 1 if i - l >= 0: c[s[i - l]] -= 1 if i + 1 >= l: if min(c.values()) <= k: return True return False def solve(s, k): low = 1 high = 1 while good(s, k, high): high *= 2 while low + 1 < high: mid = (low + high) // 2 if good(s, k, mid): low = mid else: high = mid return low n, k = map(int, input().split()) s = input() print(solve(s, k)) ``` No
104,089
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters. Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve? Input The first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n) β€” the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only. Output Print the only integer β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters. Examples Input 4 2 abba Output 4 Input 8 1 aabaabaa Output 5 Note In the first sample, Vasya can obtain both strings "aaaa" and "bbbb". In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa". Submitted Solution: ``` n, k = [int(i) for i in input().split()] s = input() def beauty (x): ret = 0 cnt = 0 r = 0 for l in range(n): while r < n and (cnt < k or s[r] != x): if s[r] == x: cnt += 1 r += 1 if r == x: cnt -= 1 ret = max(ret, r-l) return ret print(max(beauty('a'), beauty('b'))) exit(0) ``` No
104,090
Provide tags and a correct Python 3 solution for this coding contest problem. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number> All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1 Tags: implementation Correct Solution: ``` k, n, m, q = [int(i) for i in input().split()] basic = [input() for i in range(n)] composite = {} for i in range(m): name, items = input().split(":") composite[name] = {} for item in items.split(","): component, cnt = item.split() composite[name][component] = int(cnt) friends = {} for i in range(1, k+1): friends[str(i)] = {} for artifact in basic: friends[str(i)][artifact] = 0 for artifact in composite.keys(): friends[str(i)][artifact] = 0 for i in range(q): ai, artifact = input().split() friends[ai][artifact] += 1 for artifact, combo in composite.items(): if all(friends[ai][basic]==cnt for basic, cnt in combo.items()): for basic, cnt in combo.items(): friends[ai][basic] -= cnt friends[ai][artifact] += 1 break for i in range(1, k+1): print(sum([i>0 for i in friends[str(i)].values()])) for artifact in sorted(friends[str(i)].keys()): if friends[str(i)][artifact] > 0: print(artifact, friends[str(i)][artifact]) ```
104,091
Provide tags and a correct Python 3 solution for this coding contest problem. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number> All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1 Tags: implementation Correct Solution: ``` # Not really fair, since I already solved this one previously. ;) k, n, m, q = [int(i) for i in input().split()] basic = [input() for i in range(n)] composite = {} for i in range(m): name, items = input().split(":") composite[name] = {} for item in items.split(","): component, cnt = item.split() composite[name][component] = int(cnt) friends = {} for i in range(1, k+1): friends[str(i)] = {} for artifact in basic: friends[str(i)][artifact] = 0 for artifact in composite.keys(): friends[str(i)][artifact] = 0 for i in range(q): ai, artifact = input().split() friends[ai][artifact] += 1 for artifact, combo in composite.items(): if all(friends[ai][basic]==cnt for basic, cnt in combo.items()): for basic, cnt in combo.items(): friends[ai][basic] -= cnt friends[ai][artifact] += 1 break for i in range(1, k+1): print(sum([i>0 for i in friends[str(i)].values()])) for artifact in sorted(friends[str(i)].keys()): if friends[str(i)][artifact] > 0: print(artifact, friends[str(i)][artifact]) ```
104,092
Provide tags and a correct Python 3 solution for this coding contest problem. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number> All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1 Tags: implementation Correct Solution: ``` k,m,n,q = map(int, input().split()) basic = [input() for _ in range(m)] from collections import Counter, defaultdict recipes, accounts = defaultdict(Counter), defaultdict(Counter) for _ in range(n): composite, components = input().split(': ') for unit in components.split(', '): x, y = unit.split() recipes[composite][x] += int(y) for _ in range(q): player, artifact = input().split() p = int(player) accounts[p][artifact] += 1 for composite, recipe in recipes.items(): if all(num <= accounts[p][a] for a, num in recipe.items()): for basic, num in recipe.items(): accounts[p][basic] -= num accounts[p][composite] += 1 break for player in range(1, k+1): artifacts = sorted((+accounts[player]).keys()) print(len(artifacts)) for artifact in artifacts: num = accounts[player][artifact] print(artifact, num) ```
104,093
Provide tags and a correct Python 3 solution for this coding contest problem. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number> All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1 Tags: implementation Correct Solution: ``` lists, maps, ints, ranges, strs, sets, sorteds = list, map, int, range, str, set, sorted alliesNum, basicNum, compositeNum, purchasesNum = lists(maps(ints, input().split())) allies = {} basics = [] composites = {} present= False for i in ranges(basicNum): basics += input() for i in range(alliesNum + 1): allies[i] = [] for i in ranges(compositeNum): temp = input().split(":") composites[temp[0]] = temp[1].split(", ") composites[temp[0]][0] = composites[temp[0]][0].lstrip() composites[temp[0]] = set(composites[temp[0]]) for i in ranges(purchasesNum): # Adding purchased basic artifact ally, artifact = input().split() ally = ints(ally) if ally in allies.keys(): for e in ranges(len(allies[ally])): if allies[ally][e].split()[0] == artifact and not present: allies[ally][e] = allies[ally][e].split()[0] + " " + strs(ints(allies[ally][e].split()[1]) + 1) present = True if not present: allies[ally].append(artifact + " 1") present = False else: allies[ally] = [artifact + " 1"] # Buying composite artifacts if available for key in composites.keys(): if composites[key].issubset(set(allies[ally])) or composites[key] == sets(allies[ally]): for e in range(len(allies[ally])): if allies[ally][e].split()[0] == key and not present: allies[ally][e] = allies[ally][e].split()[0] + " " + str(int(allies[ally][e].split()[1]) + 1) present = True if not present: allies[ally].append(key + " 1") present = False allies[ally] = list(set(allies[ally]) - composites[key]) allies[ally] = sorteds(allies[ally]) for i in ranges(1, alliesNum + 1): print(len(allies[i])) if len(allies[i]) > 0: for e in allies[i]: print(e) ```
104,094
Provide tags and a correct Python 3 solution for this coding contest problem. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number> All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1 Tags: implementation Correct Solution: ``` from collections import defaultdict k,n,m,q = [int(x) for x in input().split()] single = [input() for i in range(n)] comp1 = [input().split(': ') for i in range(m)] comp2 = {x:y.split(', ') for x,y in comp1} def make_tup(ls): ans=[] for s in ls: x,y=s.split() ans.append([x,int(y)]) return ans; comp3 = {x:make_tup(y) for x,y in comp2.items()} team_items = [{} for i in range(k+1)] for i in range(1,k+1): for x in single: team_items[i][x]=0 for x in comp3: team_items[i][x]=0 for i in range(q): x,y = input().split() x=int(x) team_items[x][y]+=1 for key,v in comp3.items(): works=True for z in v: item, req_ct = z if team_items[x][item]< req_ct: works = False if works: for z in v: item, req_ct = z team_items[x][item] -= req_ct team_items[x][key] +=1 break for i in range(1,k+1): ct = sum([ v>0 for key,v in team_items[i].items()]) print(ct) a = [(key, v) for key,v in team_items[i].items() if v] a.sort() for x,y in a: print(x,y) ```
104,095
Provide tags and a correct Python 3 solution for this coding contest problem. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number> All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1 Tags: implementation Correct Solution: ``` import sys def solve(): kallies, nbasic, mcomp, qpurch, = rv() res = [dict() for _ in range(kallies)] mem = [dict() for _ in range(kallies)] basicnames = [input() for _ in range(nbasic)] for friend in range(kallies): for item in basicnames: mem[friend][item] = 0 combos = list() for combo in range(mcomp): name, requiredstr = input().split(':') required = requiredstr.split(',') for el in range(len(required)): while required[el][0] == ' ': required[el] = required[el][1:] dic = dict() for el in range(len(required)): itemname, amount = required[el].split() amount = int(amount) dic[itemname] = amount combos.append((name, dic)) for query in range(qpurch): friendindex, itemname = input().split() friendindex = int(friendindex) - 1 mem[friendindex][itemname] += 1 for comboname, necessary in combos: works = True for key in necessary: if mem[friendindex][key] < necessary[key]: works = False break if works: if comboname in res[friendindex]: res[friendindex][comboname] += 1 else: res[friendindex][comboname] = 1 for key in necessary: mem[friendindex][key] -= necessary[key] count = [0] * kallies ss = [list() for _ in range(kallies)] for friendindex in range(kallies): nonzero = 0 for singles in mem[friendindex]: if mem[friendindex][singles] > 0: nonzero += 1 count[friendindex] = len(res[friendindex]) + nonzero for el in res[friendindex]: ss[friendindex].append((el, res[friendindex][el])) for singles in mem[friendindex]: if mem[friendindex][singles] > 0: ss[friendindex].append((singles, mem[friendindex][singles])) for i in range(kallies): ss[i].sort() for i in range(kallies): print(count[i]) for name, num in ss[i]: print(name, num) def prt(l): return print(' '.join(l)) def rv(): return map(int, input().split()) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if sys.hexversion == 50594544 : sys.stdin = open("test.txt") solve() ```
104,096
Provide tags and a correct Python 3 solution for this coding contest problem. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number> All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1 Tags: implementation Correct Solution: ``` import sys def solve(): kallies, nbasic, mcomp, qpurch, = rv() res = [dict() for _ in range(kallies)] mem = [dict() for _ in range(kallies)] basicnames = [input() for _ in range(nbasic)] for friend in range(kallies): for item in basicnames: mem[friend][item] = 0 combos = list() for combo in range(mcomp): name, requiredstr = input().split(':') required = requiredstr.split(',') for el in range(len(required)): while required[el][0] == ' ': required[el] = required[el][1:] dic = dict() for el in range(len(required)): itemname, amount = required[el].split() amount = int(amount) dic[itemname] = amount combos.append((name, dic)) for query in range(qpurch): friendindex, itemname = input().split() friendindex = int(friendindex) - 1 mem[friendindex][itemname] += 1 for comboname, necessary in combos: works = True for key in necessary: if mem[friendindex][key] < necessary[key]: works = False break if works: if comboname in res[friendindex]: res[friendindex][comboname] += 1 else: res[friendindex][comboname] = 1 for key in necessary: mem[friendindex][key] -= necessary[key] count = [0] * kallies ss = [list() for _ in range(kallies)] for friendindex in range(kallies): nonzero = 0 for singles in mem[friendindex]: if mem[friendindex][singles] > 0: nonzero += 1 count[friendindex] = len(res[friendindex]) + nonzero for el in res[friendindex]: ss[friendindex].append((el, res[friendindex][el])) for singles in mem[friendindex]: if mem[friendindex][singles] > 0: ss[friendindex].append((singles, mem[friendindex][singles])) for i in range(kallies): ss[i].sort() for i in range(kallies): print(count[i]) for name, num in ss[i]: print(name, num) def prt(l): return print(' '.join(l)) def rv(): return map(int, input().split()) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if sys.hexversion == 50594544 : sys.stdin = open("test.txt") solve() # Made By Mostafa_Khaled ```
104,097
Provide tags and a correct Python 3 solution for this coding contest problem. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number> All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1 Tags: implementation Correct Solution: ``` import sys from array import array # noqa: F401 from collections import defaultdict def input(): return sys.stdin.buffer.readline().decode('utf-8') k, n, m, q = map(int, input().split()) basic = [input().rstrip() for _ in range(n)] composite = defaultdict(list) for _ in range(m): name, desc = input().split(':') for item in desc.split(','): pair = item.split() pair[1] = int(pair[1]) composite[name].append(pair) backpack = [defaultdict(int) for _ in range(k + 1)] for _ in range(q): f, name = input().split() f = int(f) backpack[f][name] += 1 for key, recipe in composite.items(): if all(backpack[f][base] >= cnt for base, cnt in recipe): for base, cnt in recipe: backpack[f][base] -= cnt backpack[f][key] += 1 for i in range(1, k + 1): ans = [f'{name} {cnt}' for name, cnt in backpack[i].items() if cnt > 0] ans.sort() print(len(ans)) if ans: print('\n'.join(ans)) ```
104,098
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number> All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1 Submitted Solution: ``` k,m,n,q = map(int, input().split()) basic = [input() for _ in range(m)] from collections import Counter, defaultdict recipes, accounts = defaultdict(Counter), defaultdict(Counter) for _ in range(n): composite, components = input().split(': ') for unit in components.split(', '): x, y = unit.split() recipes[composite][x] += int(y) for _ in range(q): player, artifact = input().split() p = int(player) accounts[p][artifact] += 1 for composite, recipe in recipes.items(): if all(num <= accounts[p][a] for a, num in recipe.items()): for basic, num in recipe.items(): accounts[p][basic] -= num accounts[p][composite] += 1 break for player in range(1, k+1): print(sum(accounts[player].values())) artifacts = sorted(accounts[player].keys()) for artifact in artifacts: num = accounts[player][artifact] if num: print(artifact, num) ``` No
104,099