text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Tags: brute force, greedy, implementation, math, strings Correct Solution: ``` s,ans=input(),0 for i in range(len(s)): f=s.find("bear",i) if f!=-1: ans+=len(s)-f-3 print(ans) ```
2,800
Provide tags and a correct Python 3 solution for this coding contest problem. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Tags: brute force, greedy, implementation, math, strings Correct Solution: ``` from math import ceil s=input();n=len(s);ans=0 last_idx=-1 for i in range(n-3): if s[i:i+4]=='bear': if i==0:ans+=(n-1)-(i+3)+1;last_idx=i else: k=i-last_idx-1 k1=(n-1)-(i+3)+1 ans+=k*k1 ans+=k1 last_idx=i print(ans) ```
2,801
Provide tags and a correct Python 3 solution for this coding contest problem. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Tags: brute force, greedy, implementation, math, strings Correct Solution: ``` s=input() if(len(s)<=3): print(0) else: n=len(s) ans=0 A=0 for i in range(3,n): if(s[i-3]+s[i-2]+s[i-1]+s[i]=='bear'): ans+=((i-3)-A+1)*(n-i) A=i-2 print(ans) ```
2,802
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Submitted Solution: ``` s = input() k = 0 for i in range(len(s)): c = s.find('bear', i) if c >= 0: k += len(s) - c - 3 print(k) ``` Yes
2,803
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Submitted Solution: ``` s=input().rstrip() x=list(s) if len(x)<4: print(0) else: l=[] q=[] for i in range(0,len(x)-4+1): V=x[i:i+4] if ''.join(V)=="bear": l.append(i+1) q.append(i+4) total=0; for i in range(0,len(l)): if i==0: A=l[i]-0 B=q[i] total+=(A * (len(x)-B+1)); else: A=l[i]; B=q[i]; C=l[i-1]; D=A-C E=len(x)-B+1 total+=(E*D) print(total) ``` Yes
2,804
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Submitted Solution: ``` s=str(input()) i=0 n=len(s) ans=0 count=0 while(i<n): if s[i:i+4]=="bear": if count==0: ans=ans+n-i-4+1 ans=ans+(i-0)*(n-(i+3)) k=i+1 # print(ans) else: p=i-k ans=ans+(p)*(n-i-3) # print(ans) ans=ans+n-i-4+1 # print(ans) k=i+1 count+=1 i=i+4 else: i+=1 print(ans) ``` Yes
2,805
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Submitted Solution: ``` s = input().strip() p = "bear" l = len(s) start = 0 total = 0 while True: i = s.find(p, start) if i==-1: break prev = (i-start)+1 multiplier = l - (i+3) total += prev * multiplier start = i+1 print(total) ``` Yes
2,806
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Submitted Solution: ``` a=input() b=0 for i in range(len(a)): c=a.find('bear',i) if(c>0): b+=len(a)-c-3 print(b) ``` No
2,807
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Submitted Solution: ``` ######### ## ## ## #### ##### ## # ## # ## # # # # # # # # # # # # # # # # # # # # # # # ### # # # # # # # # # # # # # ##### # # # # ### # # # # # # # # ##### # # # # # # # # # # # # # # # # # # ######### # # # # ##### # ##### # ## # ## # # """ PPPPPPP RRRRRRR OOOO VV VV EEEEEEEEEE PPPPPPPP RRRRRRRR OOOOOO VV VV EE PPPPPPPPP RRRRRRRRR OOOOOOOO VV VV EE PPPPPPPP RRRRRRRR OOOOOOOO VV VV EEEEEE PPPPPPP RRRRRRR OOOOOOOO VV VV EEEEEEE PP RRRR OOOOOOOO VV VV EEEEEE PP RR RR OOOOOOOO VV VV EE PP RR RR OOOOOO VV VV EE PP RR RR OOOO VVVV EEEEEEEEEE """ """ Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away. """ import sys input = sys.stdin.readline # from bisect import bisect_left as lower_bound; # from bisect import bisect_right as upper_bound; # from math import ceil, factorial; def ceil(x): if x != int(x): x = int(x) + 1 return x def factorial(x, m): val = 1 while x>0: val = (val * x) % m x -= 1 return val def fact(x): val = 1 while x > 0: val *= x x -= 1 return val # swap_array function def swaparr(arr, a,b): temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; ## gcd function def gcd(a,b): if b == 0: return a; return gcd(b, a % b); ## nCr function efficient using Binomial Cofficient def nCr(n, k): if k > n: return 0 if(k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## upper bound function code -- such that e in a[:i] e < x; def upper_bound(a, x, lo=0, hi = None): if hi == None: hi = len(a); while lo < hi: mid = (lo+hi)//2; if a[mid] < x: lo = mid+1; else: hi = mid; return lo; ## prime factorization def primefs(n): ## if n == 1 ## calculating primes primes = {} while(n%2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n//2 for i in range(3, int(n**0.5)+2, 2): while(n%i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n//i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): res = 1 x = x % p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## DISJOINT SET UNINON FUNCTIONS def swap(a,b): temp = a a = b b = temp return a,b; # find function with path compression included (recursive) # def find(x, link): # if link[x] == x: # return x # link[x] = find(link[x], link); # return link[x]; # find function with path compression (ITERATIVE) def find(x, link): p = x; while( p != link[p]): p = link[p]; while( x != p): nex = link[x]; link[x] = p; x = nex; return p; # the union function which makes union(x,y) # of two nodes x and y def union(x, y, link, size): x = find(x, link) y = find(y, link) if size[x] < size[y]: x,y = swap(x,y) if x != y: size[x] += size[y] link[y] = x ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n+1)] prime[0], prime[1] = False, False p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 return prime #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e5 + 5) def spf_sieve(): spf[1] = 1; for i in range(2, MAXN): spf[i] = i; for i in range(4, MAXN, 2): spf[i] = 2; for i in range(3, ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i*i, MAXN, i): if spf[j] == j: spf[j] = i; ## function for storing smallest prime factors (spf) in the array ################## un-comment below 2 lines when using factorization ################# spf = [0 for i in range(MAXN)] # spf_sieve(); def factoriazation(x): res = [] for i in range(2, int(x ** 0.5) + 1): while x % i == 0: res.append(i) x //= i if x != 1: res.append(x) return res ## this function is useful for multiple queries only, o/w use ## primefs function above. complexity O(log n) ## taking integer array input def int_array(): return list(map(int, input().strip().split())); def float_array(): return list(map(float, input().strip().split())); ## taking string array input def str_array(): return input().strip().split(); #defining a couple constants MOD = int(1e9)+7; CMOD = 998244353; INF = float('inf'); NINF = -float('inf'); ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### from itertools import permutations import math from bisect import bisect_left def solve(): s = input() if s[-1] == "\n": s = s[:-1] c = 0 a = "" ans = 0 last = 0 for i in range(len(s)): a = a + s[i] # print(a) if a == "b" or a == "be" or a == "bea": continue elif a != "bear": a = "" if a == "bear": # print(len(s), i) last = i c += 1 m = (len(s) - i) * (i - 2) # print(m) ans += m a = "" # print(last, ans) print(ans - (len(s) - last) * (c - 1)) if __name__ == '__main__': for _ in range(1): solve() # fin_time = datetime.now() # print("Execution time (for loop): ", (fin_time-init_time)) ``` No
2,808
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Submitted Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # from __future__ import print_function # for PyPy2 import io import os from collections import Counter, OrderedDict from itertools import permutations as perm from fractions import Fraction from collections import deque from sys import stdin from bisect import * from heapq import * from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] mod = int(1e9)+7 inf = float("inf") # range = xrange def nc2(x): print(x) v = x*(x-1) return v//2 s = g() n = len(s) r = "bear" ans = 0 p = [] for i in range(n-3): if s[i:i+4] == r: p.append(i) if len(p) == 0: print(-1) exit() ans += nc2(p[0]+3) for i in range(1, len(p)): ans += nc2(p[i]-p[i-1]+2) ans += nc2(n-1-p[-1]) ans -= len(p)*nc2(2) ans = nc2(n) - ans print(ans) ``` No
2,809
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r. Help the bear cope with the given problem. Input The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters. Output Print a single number — the answer to the problem. Examples Input bearbtear Output 6 Input bearaabearc Output 20 Note In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9). In the second sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (2, 10), (2, 11), (3, 10), (3, 11), (4, 10), (4, 11), (5, 10), (5, 11), (6, 10), (6, 11), (7, 10), (7, 11). Submitted Solution: ``` from sys import stdin ,stdout from os import path if(path.exists('input.txt')): stdin = open("input.txt","r") x=stdin.readline() k=0 for i in range(len(x)): t=x.find('bear',i) if t>=0: k+=len(x)-t-3 stdout.write(str(k)+'\n') ``` No
2,810
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Tags: implementation, math Correct Solution: ``` from sys import stdin test = stdin.readlines() n = int(test[0]) matrix = [test[i+1].split() for i in range(n)] dot = 0 for i in range(n): dot ^= matrix[i][i] == '1' out = [] for q in range(int(test[n + 1])): query = test[n + q + 2].split() if len(query) == 1: out.append(dot) else: dot ^= 1 print(''.join(map(str, out))) ```
2,811
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Tags: implementation, math Correct Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- n = int(input()) lis=list(list(map(int, input().split())) for _ in range(n)) u=0 for i in range(n): for j in range(n): if i==j: u^=lis[i][j] ans =[] k = int(input()) for i in range(k): s = input() if s[0]=='3': ans.append(str(u)) else: u^=1 print(''.join(ans)) ```
2,812
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Tags: implementation, math Correct Solution: ``` def main(): from sys import stdin, stdout from functools import reduce from operator import xor n = int(int(input())) mat = [list(map(int, input().split())) for _ in range(n)] ans, q, a = reduce(xor, [mat[i][i] for i in range(n)]), int(input()), [] queries = [stdin.readline() for i in range(q)] for query in queries: if query[0] == '3': a.append(str(ans)) else: ans ^= 1 print(''.join(a)) if __name__ == '__main__': main() ```
2,813
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Tags: implementation, math Correct Solution: ``` from sys import stdin, stdout from functools import reduce from operator import xor def main(): n = int(int(input())) mat = [list(map(int, input().split())) for _ in range(n)] ans, q, a = reduce(xor, [mat[i][i] for i in range(n)]), int(input()), [] queries = [stdin.readline() for i in range(q)] for query in queries: if query[0] == '3': a.append(str(ans)) else: ans ^= 1 print(''.join(a)) if __name__ == '__main__': main() ```
2,814
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Tags: implementation, math Correct Solution: ``` from sys import stdin test = stdin.readlines() n = int(test[0]) dot = 0 j = 0 for i in range(n): if test[i+1][j] == '1': dot ^= 1 j += 2 out = [] for q in range(int(test[n + 1])): query = test[n + q + 2].split() if len(query) == 1: out.append(dot) else: dot ^= 1 print(''.join(map(str, out))) ```
2,815
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Tags: implementation, math Correct Solution: ``` def main(): from sys import stdin from operator import xor from functools import reduce x, res = reduce(xor, (input()[i] == '1' for i in range(0, int(input()) * 2, 2))), [] input() for s in stdin.read().splitlines(): if s == '3': res.append("01"[x]) else: x ^= True print(''.join(res)) if __name__ == "__main__": main() ```
2,816
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Tags: implementation, math Correct Solution: ``` from sys import stdin, stdout from functools import reduce from operator import xor def arr_inp(n): return [int(x) for x in input().split()] class Matrix: def __init__(self, r, c, mat=None): self.r, self.c = r, c if mat != None: self.mat = mat else: self.mat = [[0 for i in range(c)] for j in range(r)] def __add__(self, other): mat0 = Matrix(self.r, self.c) for i in range(self.r): for j in range(self.c): mat0.mat[i][j] = self.mat[i][j] + other.mat[i][j] return mat0.mat def __mul__(self, other): mat0 = Matrix(self.r, other.c) for i in range(self.r): for j in range(other.c): for k in range(self.c): mat0.mat[i][j] += self.mat[i][k] * other.mat[k][j] return mat0.mat def trace(self): res = 0 for i in range(self.r): res += self.mat[i][i] return res % 2 def dot_mul(self, other): res = 0 for i in range(self.r): for j in range(self.c): res += self.mat[i][j] * other.mat[j][i] return res % 2 def rotate(self): mat0 = Matrix(self.c, self.r) for i in range(self.r): for j in range(self.c): mat0.mat[j][self.r - (i + 1)] = self.mat[i][j] self.mat, self.r, self.c = mat0.mat.copy(), self.c, self.r return self.mat def reflect(self): mat0 = Matrix(self.r, self.c) for i in range(self.r): for j in range(self.c): mat0.mat[i][self.c - (j + 1)] = self.mat[i][j] self.mat = mat0.mat.copy() return self.mat n = int(int(input())) mat = Matrix(n, n, [arr_inp(1) for _ in range(n)]) ans, q, a = mat.trace(), int(input()), [] queries = [stdin.readline() for i in range(q)] for query in queries: if query[0] == '3': a.append(str(ans)) else: ans ^= 1 print(''.join(a)) ```
2,817
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Tags: implementation, math Correct Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# #vsInput() n=Int() ans=0 for i in range(n): a=array() ans+=a[i] #print(ans) for _ in range(Int()): s=input() if(s=='3'): print(ans%2,end="") else: t,c=map(int,s.split()) ans+=1 ```
2,818
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Submitted Solution: ``` from sys import stdin,stdout cnt = 0 arr = [] for i in range(int(stdin.readline())): if stdin.readline().split()[i]=='1': arr.append(1) cnt += 1 else: arr.append(0) stdin.readline() for i in stdin: if len(i)<3: stdout.write(str(cnt%2)) else: _,j = map(int,i.split()) j -= 1 if arr[j]: arr[j] = 0 cnt -= 1 else: arr[j] = 1 cnt += 1 ``` Yes
2,819
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Submitted Solution: ``` from sys import stdin input = stdin.readline n = int(input()) lis=list(list(map(int, input().split())) for _ in range(n)) u=0 for i in range(n): for j in range(n): if i==j: u^=lis[i][j] ans =[] k = int(input()) for i in range(k): s = input() if s[0]=='3': ans.append(str(u)) else: u^=1 print(''.join(ans)) ``` Yes
2,820
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Submitted Solution: ``` from sys import stdin, stdout from functools import reduce from operator import xor from threading import Thread, stack_size def arr_inp(n): return [int(x) for x in input().split()] def main(): n = int(int(input())) mat = [list(map(int, input().split())) for _ in range(n)] ans, q, a = reduce(xor, [mat[i][i] for i in range(n)]), int(input()), [] queries = [stdin.readline() for i in range(q)] for query in queries: if query[0] == '3': a.append(str(ans)) else: ans ^= 1 print(''.join(a)) if __name__ == '__main__': stack_size(102400000) thread = Thread(target=main) thread.start() ``` Yes
2,821
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Submitted Solution: ``` import os,sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") n=int(input()) mat=[] for i in range(n): l=list(map(int,input().split())) mat.append(l) summ=0 for i in range(n): for j in range(n): if(i==j): summ+=mat[i][j] q=int(input()) for i in range(q): p=list(map(int,input().split())) if(p[0]==3): print(summ%2,end="") else: summ+=1 ``` Yes
2,822
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Submitted Solution: ``` from operator import and_, xor from functools import reduce from itertools import chain from sys import stdin input = stdin.readline n = int(input()) l = list(chain(*list(list(map(int, input().split())) for _ in range(n)))) q = int(input()) commands = list(list(map(int, input().split())) for _ in range(q)) output = [] for i in range(q): if commands[i][0] == 3: ans = 0 for i in range(n): ans += sum([*map(and_, l[i*n:(1+i)*n], l[i::n])]) % 2 ans %= 2 output.append(ans) if commands[i][0] == 2: col = commands[i][1] - 1 l[col::n] = [*map(lambda v : 1 - v, l[col::n])] if commands[i][0] == 1: row = commands[i][1] - 1 l[row*n:(row+1)*n] = [*map(lambda v : 1 - v, l[row*n:(row+1)*n])] print(''.join([*map(str, output)])) ``` No
2,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Submitted Solution: ``` from operator import and_, xor from functools import reduce from itertools import chain from sys import stdin input = stdin.readline n = int(input()) l = list(chain(*list(list(map(int, input().split())) for _ in range(n)))) q = int(input()) commands = list(list(map(int, input().split())) for _ in range(q)) output = list() for i in range(q): if commands[i][0] == 3: ans = 0 for i in range(n): ans += sum([*map(and_, l[i*n:(1+i)*n], l[i::n])]) % 2 ans %= 2 output += [ans] if commands[i][0] == 2: col = commands[i][1] - 1 l[col::n] = [*map(lambda v : 1 - v, l[col::n])] if commands[i][0] == 1: row = commands[i][1] - 1 l[row*n:(row+1)*n] = [*map(lambda v : 1 - v, l[row*n:(row+1)*n])] print(''.join([*map(str, l)])) ``` No
2,824
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Submitted Solution: ``` def main(): from sys import stdin from operator import xor from functools import reduce x, res = reduce(xor, (input()[i] == '1' for i in range(0, int(input()) * 2, 2))), [] for s in stdin.read().splitlines(): if s == '3': res.append("01"[x]) else: x ^= True print(''.join(res)) if __name__ == "__main__": main() ``` No
2,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A. Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: <image> The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0. However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: 1. given a row index i, flip all the values in the i-th row in A; 2. given a column index i, flip all the values in the i-th column in A; 3. find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1. Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework? Input The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: * 1 i — flip the values of the i-th row; * 2 i — flip the values of the i-th column; * 3 — output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input. Examples Input 3 1 1 1 0 1 1 1 0 0 12 3 2 3 3 2 2 2 2 1 3 3 3 1 2 2 1 1 1 3 Output 01001 Submitted Solution: ``` current = False n = int(input()) for i in range(n): v = [bool for i in input().split()] if v[i] == True: current = not current output = "" q = int(input()) for i in range(q): query = [int(x) for x in input().split()] if query[0] == 3: output += str(int(current)) # print(int(current)) else: current = not current print(output) ``` No
2,826
Provide tags and a correct Python 3 solution for this coding contest problem. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Tags: dp, implementation, sortings Correct Solution: ``` # Input n = int(input()) v = list(map(int, input().split())) # Sorting V sorted_v = sorted(v) # Prefix Sum Arrays prefix_v = [0] sorted_prefix = [0] sum_v = 0 sums = 0 # Prefix For Unsorted Values for x in v: sums += x prefix_v.append(sums) # Prefix For Sorted Values for x in sorted_v: sum_v += x sorted_prefix.append(sum_v) for _ in range(int(input())): question = list(map(int, input().split())) q = question[0] # For Question 2 if q == 2: point1 = question[1] - 1 point2 = question[2] sums = 0 print(sorted_prefix[point2] - sorted_prefix[point1]) # For Question 1 else: point1 = question[1] - 1 point2 = question[2] print(prefix_v[point2] - prefix_v[point1]) ```
2,827
Provide tags and a correct Python 3 solution for this coding contest problem. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Tags: dp, implementation, sortings Correct Solution: ``` import sys input = sys.stdin.readline I = lambda:map(int,input().split()) n = int(input()) v = [0] + list(I()) u = sorted(v) for i in range(1,n + 1): v[i] += v[i-1] u[i] += u[i-1] for _ in range(int(input())): t,l,r = I() if t == 1: print(v[r] - v[l-1]) else: print(u[r] - u[l-1]) ```
2,828
Provide tags and a correct Python 3 solution for this coding contest problem. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Tags: dp, implementation, sortings Correct Solution: ``` from itertools import accumulate n = int(input()) v = [0]+list(map(int,input().split())) ls = sorted(v) v = list(accumulate(v)) ls = list(accumulate(ls)) m = int(input()) for i in range(m): s = 0 t,l,r = map(int,input().split()) if t==1: print(v[r]-v[l-1]) elif t==2: print(ls[r]-ls[l-1]) ```
2,829
Provide tags and a correct Python 3 solution for this coding contest problem. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Tags: dp, implementation, sortings Correct Solution: ``` n = int(input()) v = list(map(int, input().split(' '))) u = sorted(v) s_v = [0] s_u = [0] for i in range(1, n + 1): s_v.append(s_v[i - 1] + v[i - 1]) s_u.append(s_u[i - 1] + u[i - 1]) ans = [] for _ in range(int(input())): t, l, r = map(int, input().split(' ')) if t == 1: tt = s_v[r] - s_v[l - 1] else: tt = s_u[r] - s_u[l - 1] ans.append(str(tt)) print('\n'.join(ans)) ```
2,830
Provide tags and a correct Python 3 solution for this coding contest problem. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Tags: dp, implementation, sortings Correct Solution: ``` n=int(input()) arr=list(map(int, input().split())) arranged=sorted(arr) sum1=sum(arr) sum2=sum(arranged) prefix_sum1=[arr[0]] for i in range(1,n): prefix_sum1.append(arr[i]+prefix_sum1[-1]) suffix_sum1=[arr[-1]] for i in range(n-2,-1,-1): suffix_sum1.append(arr[i]+suffix_sum1[-1]) prefix_sum2=[arranged[0]] for i in range(1,n): prefix_sum2.append(arranged[i]+prefix_sum2[-1]) suffix_sum2=[arranged[-1]] for i in range(n-2,-1,-1): suffix_sum2.append(arranged[i]+suffix_sum2[-1]) m=int(input()) for i in range(m): type, l, r = map(int, input().split()) if type==1: if r-l+1==n: print(sum1) elif l==1: print(sum1-(suffix_sum1[n-r-1])) elif r==n: print(sum1-(prefix_sum1[l-2])) elif r==n: print(sum1-(prefix_sum1[l-2]+suffix_sum1[n-r-1])) else: print(sum1-(prefix_sum1[l-2]+suffix_sum1[n-r-1])) else: if r-l+1==n: print(sum2) elif l==1: print(sum2-(suffix_sum2[n-r-1])) elif r==n: print(sum2-(prefix_sum2[l-2])) elif r==n: print(sum2-(prefix_sum2[l-2]+suffix_sum2[n-r-1])) else: print(sum2-(prefix_sum2[l-2]+suffix_sum2[n-r-1])) ```
2,831
Provide tags and a correct Python 3 solution for this coding contest problem. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Tags: dp, implementation, sortings Correct Solution: ``` n=int(input()) v=list(map(int,input().split())) l1=[0]*(n+1) l2=[0]*(n+1) l1[1]=v[0] for i in range(2,n+1): l1[i]=l1[i-1]+v[i-1] v.sort() l2[1]=v[0] for i in range(2,n+1): l2[i]=l2[i-1]+v[i-1] m=int(input()) for i in range(m): t,l,r=map(int,input().split()) if t==1: print(l1[r]-l1[l-1]) else: print(l2[r]-l2[l-1]) ```
2,832
Provide tags and a correct Python 3 solution for this coding contest problem. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Tags: dp, implementation, sortings Correct Solution: ``` n=int(input()) v=list(map(int,input().split())) u=[] for i in range(n): u.append(v[i]) u.sort() for i in range(1,n): v[i]+=v[i-1] for i in range(1,n): u[i]+=u[i-1] c=[0] d=[0] for i in range(n): c.append(v[i]) d.append(u[i]) q=int(input()) for i in range(q): a,l,r=map(int,input().split()) if a==1: print(c[r]-c[l-1]) else: print(d[r]-d[l-1]) ```
2,833
Provide tags and a correct Python 3 solution for this coding contest problem. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Tags: dp, implementation, sortings Correct Solution: ``` # Kuriyama mari stones from typing import List class Solution: @classmethod def sum_array(cls, numbers: List[int]) -> List[int]: sum_numbers = [0] for index, num in enumerate(numbers): prev = sum_numbers[index] next = numbers[index] sum_numbers.append(prev + next) return sum_numbers @classmethod def sorted_sum_array(cls, numbers: List[int]) -> List[int]: sorted_numbers = sorted(numbers) sorted_sum_numbers = cls.sum_array(sorted_numbers) return sorted_sum_numbers @classmethod def query( cls, sum_numbers: List[int], sorted_sum_numbers: List[int], qtype: int, low: int, high: int, ) -> int: if qtype == 1: return sum_numbers[high] - sum_numbers[low - 1] else: return sorted_sum_numbers[high] - sorted_sum_numbers[low - 1] if __name__ == "__main__": num = int(input()) numbers = list(map(lambda x: int(x), input().split())) sum_numbers = Solution.sum_array(numbers) sorted_sum_numbers = Solution.sorted_sum_array(numbers) num_questions = int(input()) for i in range(num_questions): [qtype, low, high] = list(map(lambda x: int(x), input().split())) answer = Solution.query(sum_numbers, sorted_sum_numbers, qtype, low, high) print(answer) ```
2,834
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Submitted Solution: ``` "Codeforces Round #339 (Div. 2)" "B. Gena's Code" # y=int(input()) # # a=list(map(int,input().split())) # a=list(input().split()) # nz=0 # nb='' # z=0 # # print(len(str(z))) # for i in a: # if i=='0': # z=1 # break # else: # s='1' # l=(len(i)-1) # qz='0'*l # s+=qz # if s==i: # nz+=l # else: # nb=i # if nb=='': # nb='1' # ans=nb+('0'*nz) # if z==1: # ans='0' # print(ans) "Codeforces Round #177 (Div. 2)" "B. Polo the Penguin and Matrix" # n,m,d=map(int,input().split()) # a=[] # for i in range(n): # b=list(map(int,input().split())) # a.extend(b) # a.sort() # fa=a[0] # f=0 # c=(a[len(a)//2]-fa)//d # moves=0 # for i in a: # if (i-fa)%d>0: # f=-1 # moves+=abs(int((i-fa)/d)-c) # if f==-1: # print(-1) # else: # print(moves) "Codeforces Round #264 (Div. 2)" "B. Caisa and Pylons" # y=int(input()) # a=list(map(int,input().split())) # mini=0 # p=-a[0] # for i in range(1,y): # if p<mini: # mini=p # p=p+a[i-1]-a[i] # if p<mini: # mini=p # if mini<0: # print(-1*mini) # else: # print(0) "Codeforces Beta Round #79 (Div. 2 Only)" "B. Sum of Digits" # y=input() # def sumofdigits(s): # ans=0 # for i in s: # ans+=int(i) # return ans # n=0 # while len(y)>1: # n+=1 # y=str(sumofdigits(y)) # print(n) "Codeforces Beta Round #70 (Div. 2)" "B. Easter Eggs" # y=int(input()) # y=y-7 # s="ROYGBIV" # sq=["G","B","I","V"] # i=0 # while y>0: # if i==4: # i=0 # s+=sq[i] # i+=1 # y-=1 # print(s) "Codeforces Round #386 (Div. 2)" "B. Decoding" # y=int(input()) # sq=input() # i=y%2 # s="" # s+=sq[0] # for j in range(1,y): # if i==0: # s+=sq[j] # else: # s=sq[j]+s # i=1-i # print(s) "Codeforces Round #280 (Div. 2)" "B. Vanya and Lanterns" # n,l=map(int,input().split()) # a=list(map(int,input().split())) # a.sort() # max=float(a[0]) # for i in range(1,n): # m=(a[i]-a[i-1])/2 # if max<m: # max=m # m=l-a[-1] # if max<m: # max=m # print(max) "Codeforces Round #248 (Div. 2)" "B. Kuriyama Mirai's Stones" y=int(input()) a=list(map(int,input().split())) t1=int(input()) a1=[0] for i in range(y): a1.append(a1[-1]+a[i]) a.sort() a2=[0] for i in range(y): a2.append(a2[-1]+a[i]) for i in range(t1): t,l,r=map(int,input().split()) if t==1: print(a1[r]-a1[l-1]) else: print(a2[r]-a2[l-1]) ``` Yes
2,835
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Submitted Solution: ``` n=int(input()) arr=input().split() brr=sorted(arr,key=int) for i in range(1,n): arr[i]=int(arr[i-1])+int(arr[i]) for i in range(1,n): brr[i]=int(brr[i-1])+int(brr[i]) m=int(input()) for i in range(m): ty,l,r=map(int,input().split()) if ty==1: if l-2>=0: print(int(arr[r-1])-int(arr[l-2])) else: print(int(arr[r-1])) else: if l-2>=0: print(int(brr[r-1])-int(brr[l-2])) else: print(int(brr[r-1])) ``` Yes
2,836
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Submitted Solution: ``` n= int(input()) mas1 = list(map(int,input().split(" "))) mas2 = sorted(mas1) for i in range(1,n): mas1[i]+=mas1[i-1] mas2[i]+=mas2[i-1] m = int(input()) mas1.append(0) mas2.append(0) print("\n".join(map(str, (mas1[b-1]-mas1[a-2] if s==1 else mas2[b-1]-mas2[a-2] for s, a, b in (map(int,input().split(" ")) for i in range(m)))))) ``` Yes
2,837
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Submitted Solution: ``` n = int(input()) arr = [0] for x in input().split(): arr.append(int(x)) ac = [0] for i in range(1,n+1): ac.append(arr[i] + ac[i-1]) arr.sort() acSorted = [0] for i in range(1,n+1): acSorted.append(arr[i] + acSorted[i-1]) m = int(input()) for i in range(m): op, l, r = map(int, input().split()) if (op == 1): print(ac[r] - ac[l-1]) else: print(acSorted[r] - acSorted[l-1]) # 1481936527735 ``` Yes
2,838
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Submitted Solution: ``` n = int(input()) data1 = input().split(); x = 0 for x in range(len(data1)): data1[x] = int(data1[x]) data2 = data1[:] data2.sort(); k = int(input()) def query1(fr, to): sum = 0 for x in data1[fr:to+1]: sum += x print("outs: ",sum) x = 0 def query2(fr, to): sum = 0 for x in data2[fr:to+1]: sum += x print("outs: ",sum) while x < k: data3 = input().split(); if(int(data3[0]) is 1): query1(int(data3[1])-1, int(data3[2])-1) else: query2(int(data3[1])-1, int(data3[2])-1) x+=1 ``` No
2,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Submitted Solution: ``` def rat(b,x,y):print(b[y]-b[x-1]) a=int(input()) b=[0]+list(map(int,input().split())) c=sorted(b.copy()) for i in range(1,a+1):b[i]+=b[i-1];c[i]+=c[i-1] for _ in " "*int(input()): x,y,z=map(int,input().split()) if x==1:rat(b,y,z) else:rat(c,x,y) ``` No
2,840
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Submitted Solution: ``` def lista_acumulada(lista): lista[0] = int(lista[0]) i = 1 while i < len(lista): lista[i] = int(lista[i]) + int(lista[i - 1]) i += 1 return lista n = int(input()) entrada = input() m = int(input()) questoes = [] res = [] i = 0 while i < m: questoes.append(input().split()) i += 1 acumulada1 = lista_acumulada(entrada.split()) acumulada2 = lista_acumulada(sorted(entrada.split())) for e in questoes: l = int(e[1]) r = int(e[2]) if e[0] == '1': if l == 1: res.append(acumulada1[r - 1]) else: res.append(acumulada1[r - 1] - acumulada1[l - 2]) # na entrada os indices (l, r) são contados a partir do 1 else: if l == 1: res.append(acumulada2[r - 1]) else: res.append(acumulada2[r - 1] - acumulada2[l - 2]) for e in res: print(e) ``` No
2,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. 2. Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her <image>. For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy. Input The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones. The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one. Output Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input. Examples Input 6 6 4 2 7 2 7 3 2 3 6 1 3 4 1 1 6 Output 24 9 28 Input 4 5 5 2 3 10 1 2 4 2 1 4 1 1 1 2 1 4 2 1 2 1 1 1 1 3 3 1 1 3 1 4 4 1 2 2 Output 10 15 5 15 5 5 2 12 3 5 Note Please note that the answers to the questions may overflow 32-bit integer type. Submitted Solution: ``` def sumLisNum(lis): sumLis = [0] * len(lis) sumLis[0] = lis[0] for i in range(1, len(lis)): sumLis[i] = sumLis[i - 1] + lis[i] return sumLis n = int(input()) v = list(map(int, input().split())) u = v[:] u.sort() sumV = sumLisNum(v) sumU = sumLisNum(u) m = int(input()) print(sumV) print(sumU) for i in range(m): t, l, r = map(int, input().split()) if t == 1: print(sumV[r - 1] - sumV[l - 1] + v[l - 1]) else: print(sumU[r - 1] - sumU[l - 1] + u[l - 1]) ``` No
2,842
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Serega loves fun. However, everyone has fun in the unique manner. Serega has fun by solving query problems. One day Fedor came up with such a problem. You are given an array a consisting of n positive integers and queries to it. The queries can be of two types: 1. Make a unit cyclic shift to the right on the segment from l to r (both borders inclusive). That is rearrange elements of the array in the following manner:a[l], a[l + 1], ..., a[r - 1], a[r] → a[r], a[l], a[l + 1], ..., a[r - 1]. 2. Count how many numbers equal to k are on the segment from l to r (both borders inclusive). Fedor hurried to see Serega enjoy the problem and Serega solved it really quickly. Let's see, can you solve it? Input The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of the array. The second line contains n integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ n). The third line contains a single integer q (1 ≤ q ≤ 105) — the number of queries. The next q lines contain the queries. As you need to respond to the queries online, the queries will be encoded. A query of the first type will be given in format: 1 l'i r'i. A query of the second type will be given in format: 2 l'i r'i k'i. All the number in input are integer. They satisfy the constraints: 1 ≤ l'i, r'i, k'i ≤ n. To decode the queries from the data given in input, you need to perform the following transformations: li = ((l'i + lastans - 1) mod n) + 1; ri = ((r'i + lastans - 1) mod n) + 1; ki = ((k'i + lastans - 1) mod n) + 1. Where lastans is the last reply to the query of the 2-nd type (initially, lastans = 0). If after transformation li is greater than ri, you must swap these values. Output For each query of the 2-nd type print the answer on a single line. Examples Input 7 6 6 2 7 4 2 5 7 1 3 6 2 2 4 2 2 2 4 7 2 2 2 5 1 2 6 1 1 4 2 1 7 3 Output 2 1 0 0 Input 8 8 4 2 2 7 7 8 8 8 1 8 8 2 8 1 7 1 8 1 1 7 3 2 8 8 3 1 1 4 1 2 7 1 4 5 Output 2 0 Submitted Solution: ``` n =int(input()) arr = [int(x) for x in input().split()] big = 10**5 freq = [0]*(big + 1) for i in arr: freq[i] += 1 dp = {} for a in range(big+1): if(a==0): val = 0 elif(a==1): val = freq[1] else: val = max(dp[a-1], dp[a-2]+a*freq[a]) dp[a] = val print(dp[big]) ``` No
2,843
Provide tags and a correct Python 3 solution for this coding contest problem. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Tags: combinatorics, constructive algorithms, greedy, math Correct Solution: ``` def f(k): return k*(k-1)//2 n,m=map(int,input().split()) print(f(n//m+1)*(n%m)+f(n//m)*(m-n%m),f(n-m+1)) ```
2,844
Provide tags and a correct Python 3 solution for this coding contest problem. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Tags: combinatorics, constructive algorithms, greedy, math Correct Solution: ``` n, m = tuple(map(int, input().split())) n1 = int(n / m) mod = n % m print((n1 + 1) * n1 // 2 * mod + n1 * (n1 - 1) // 2 * (m - mod), (n - m + 1) * (n - m) // 2) ```
2,845
Provide tags and a correct Python 3 solution for this coding contest problem. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Tags: combinatorics, constructive algorithms, greedy, math Correct Solution: ``` # coding: utf-8 n, m = [int(i) for i in input().split()] if n%m==0: kmin = (n//m)*(n//m-1)//2*m kmax = (n-m+1)*(n-m)//2 else: t = n//m kmin = t*(t+1)//2*(n%m)+t*(t-1)//2*(m-n%m) kmax = (n-m+1)*(n-m)//2 print(kmin,kmax) ```
2,846
Provide tags and a correct Python 3 solution for this coding contest problem. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Tags: combinatorics, constructive algorithms, greedy, math Correct Solution: ``` w=input().split(" ") n=int(w[0]) m=int(w[1]) formax=n-m maxx=int((formax)*(formax+1)//2) a=n//m b=n%m minn=int((b*(a*(a+1)/2))+((m-b)*(a*(a-1)/2))) print(str(minn)+" "+str(maxx)) ```
2,847
Provide tags and a correct Python 3 solution for this coding contest problem. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Tags: combinatorics, constructive algorithms, greedy, math Correct Solution: ``` n, m = map(int, input().split()) print(((n // m) * (n // m - 1)) // 2 * (m - n % m) + (n % m) * ((n // m + 1) * (n // m)) // 2, (n - m + 1) * (n - m) // 2) ```
2,848
Provide tags and a correct Python 3 solution for this coding contest problem. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Tags: combinatorics, constructive algorithms, greedy, math Correct Solution: ``` n, m = map(int, input().split()) #pentru doua gramezi este optim sa muti dintr-una in cealalta pentru a maximiza C(a,2)+C(b,2) #a+b == n. graficul apare ca al unei functii de gradul 2 cu fundul in jos #cum treci la 3/4.. variabile? def P(x): return x*(x-1)//2 print(P(n//m)*(m - n%m) + P(n//m+1)*(n%m), end = ' ') print(P(n-m+1)) ```
2,849
Provide tags and a correct Python 3 solution for this coding contest problem. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Tags: combinatorics, constructive algorithms, greedy, math Correct Solution: ``` n, m = (int(s) for s in input().split(" ")) res2 = (n-m+1) * (n-m) // 2 res1 = (n//m - 1) * (n//m) * (m - n%m) //2 + (n//m ) * (n//m + 1) * (n%m)//2 print(res1, res2) ```
2,850
Provide tags and a correct Python 3 solution for this coding contest problem. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Tags: combinatorics, constructive algorithms, greedy, math Correct Solution: ``` n,k=map(int,input().split()) x=n-(k-1) kmax = (x*(x-1))//2 t = n//k y = n%k kmin = (k-y)*((t*(t-1))//2) + y*(((t+1)*t)//2) print(kmin,kmax) ```
2,851
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Submitted Solution: ``` n,m=map(int,input().split()) mxc=n%m mnc=m-mxc mn=n//m mx=mn+1 print(mxc*mx*(mx-1)//2 + mnc*mn*(mn-1)//2, (n-m)*(n-m+1)//2) ``` Yes
2,852
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Submitted Solution: ``` n,m=map(int,input().split()) av=n//m mi=av*(av-1)//2 mi*=m mi+=av*(n%m) ma=(n-m)*(n-m+1)//2 print(mi,ma) ``` Yes
2,853
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Submitted Solution: ``` def friends_in_team(amount): if amount <= 1: return 0 return (amount * (amount - 1)) // 2 n, m = (int(x) for x in input().split()) a = friends_in_team(n // m) * (m - n % m) a += friends_in_team(n // m + 1) * (n % m) b = friends_in_team(n - m + 1) print('{} {}'.format(min(a, b), max(a, b))) ``` Yes
2,854
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Submitted Solution: ``` n, m = (int(x) for x in input().split()) q, r = n // m, n % m kmin = r * (q + 1) * q // 2 + (m - r) * q * (q - 1) // 2 kmax = (n - m + 1) * (n - m) // 2 print(kmin, kmax) ``` Yes
2,855
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Submitted Solution: ``` n, m = map(int, input().split()) div = n//m mod = n%m mini = ((div-1) * (m-mod) + (div + 1) * (mod))*div/2 maxi = (n-(m+1)) * (n-m) / 2 print(int(mini), int(maxi)) ``` No
2,856
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Submitted Solution: ``` w=input().split(" ") n=int(w[0]) m=int(w[1]) formax=n-m maxx=int((formax)*(formax+1)/2) a=n//m b=n%m minn=int((b*(a*(a+1)/2))+((m-b)*(a*(a-1)/2))) print(str(minn)+" "+str(maxx)) ``` No
2,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Submitted Solution: ``` def comb(p): return ((p/2)*(p-1)) if (p%2==0) else (((p-1)/2)*p) def max_pair(n,m): print(int(comb(n-m+1)),end=""); def min_pair(n,m): val,mod,sm=n//m,n%m,0 for i in range(m): if mod: sm+=comb(val+1) mod-=1 else: sm+=comb(val) print(int(sm),end=" ") n,m=input().split(" ") n,m=int(n),int(m) if n==m: print("0 0") else: min_pair(n,m) max_pair(n,m) ``` No
2,858
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition. Input The only line of input contains two integers n and m, separated by a single space (1 ≤ m ≤ n ≤ 109) — the number of participants and the number of teams respectively. Output The only line of the output should contain two integers kmin and kmax — the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively. Examples Input 5 1 Output 10 10 Input 3 2 Output 1 1 Input 6 3 Output 3 6 Note In the first sample all the participants get into one team, so there will be exactly ten pairs of friends. In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one. In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people. Submitted Solution: ``` import math def combine(x,y): if x==y: return 1 elif y>x: return 0 else: ans = math.factorial(x)/(math.factorial(x-y)*math.factorial(y)) return ans n,m=map(int,input().split()) #min group=[] check=n later=m a=n%m while a!=0: check-=a later-=1 group.append(a) a=check%later group.append(a) k=check//later v=combine(k,2) ans=0 ans+=(v*later) for t in group: v=combine(t,2) ans+=(v) print (int(ans),end=' ') #max x=n-(m-1) v=combine(x,2) print (int(v)) ``` No
2,859
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` from queue import Queue import sys cost = [] #coo def readarray(): return map(int, input().split(' ')) n = int(input()) graph = [[] for i in range(n)] for i in range(n - 1): u, v, c = readarray() u, v = u - 1, v - 1 cost.append(c) graph[u].append((v, i)) graph[v].append((u, i)) order = [] used = [0] * n q = [0] * (n + n) qh = qt = 0 used[qh] = 1 qh += 1 while qt < qh: v = q[qt] qt += 1 order.append(v) for (to, e) in graph[v]: if used[to]: continue used[to] = 1 q[qh] = to qh += 1 order.reverse() sz = [0 for x in range(n)] for v in order: sz[v] = 1 for (to, e) in graph[v]: sz[v] += sz[to] """ sz = [0] * n sys.setrecursionlimit(100505) def dfs(v, p): sz[v] = 1 for (to, e) in graph[v]: if to != p: dfs(to, v) sz[v] += sz[to] dfs(0, -1) """ distanceSum = 0.0 edgeMult = [0] * n for v in range(n): for (to, e) in graph[v]: x = min(sz[v], sz[to]) edgeMult[e] = x distanceSum += 1.0 * cost[e] * x * (n - x) distanceSum /= 2.0 queryCnt = int(input()) ans = [] for i in range(queryCnt): x, y = readarray() x -= 1 distanceSum -= 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x]) cost[x] = y distanceSum += 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x]) ans.append('%.10lf' % (distanceSum / n / (n - 1) * 6.0)) print('\n'.join(ans)) ```
2,860
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa=ifa[::-1] def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def linc(f,t,l,r): while l<r: mid=(l+r)//2 if t>f(mid): l=mid+1 else: r=mid return l def rinc(f,t,l,r): while l<r: mid=(l+r+1)//2 if t<f(mid): r=mid-1 else: l=mid return l def ldec(f,t,l,r): while l<r: mid=(l+r)//2 if t<f(mid): l=mid+1 else: r=mid return l def rdec(f,t,l,r): while l<r: mid=(l+r+1)//2 if t>f(mid): r=mid-1 else: l=mid return l def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def binfun(x): c=0 for w in arr: c+=ceil(w/x) return c def lowbit(n): return n&-n def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans class SMT: def __init__(self,arr): self.n=len(arr)-1 self.arr=[0]*(self.n<<2) self.lazy=[0]*(self.n<<2) def Build(l,r,rt): if l==r: self.arr[rt]=arr[l] return m=(l+r)>>1 Build(l,m,rt<<1) Build(m+1,r,rt<<1|1) self.pushup(rt) Build(1,self.n,1) def pushup(self,rt): self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1] def pushdown(self,rt,ln,rn):#lr,rn表区间数字数 if self.lazy[rt]: self.lazy[rt<<1]+=self.lazy[rt] self.lazy[rt<<1|1]=self.lazy[rt] self.arr[rt<<1]+=self.lazy[rt]*ln self.arr[rt<<1|1]+=self.lazy[rt]*rn self.lazy[rt]=0 def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间 if r==None: r=self.n if L<=l and r<=R: self.arr[rt]+=c*(r-l+1) self.lazy[rt]+=c return m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) if L<=m: self.update(L,R,c,l,m,rt<<1) if R>m: self.update(L,R,c,m+1,r,rt<<1|1) self.pushup(rt) def query(self,L,R,l=1,r=None,rt=1): if r==None: r=self.n #print(L,R,l,r,rt) if L<=l and R>=r: return self.arr[rt] m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) ans=0 if L<=m: ans+=self.query(L,R,l,m,rt<<1) if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1) return ans class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]<self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)] class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue for v in graph[u]: if v not in d or d[v]>d[u]+graph[u][v]: d[v]=d[u]+graph[u][v] heappush(heap,(d[v],v)) return d def GP(it): return [(ch,len(list(g))) for ch,g in groupby(it)] class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None @bootstrap def dfs(r,p): if len(g[r])==1 and p!=-1: yield 1 res=1 for child in g[r]: if child!=p: tmp=yield(dfs(child,r)) cnt[d[tuple(sorted([r,child]))]]=tmp*(n-tmp) res+=tmp yield res t=1 for i in range(t): n=N() edg=[] d={} cnt=[0]*(n-1) g=[[] for i in range(n)] for i in range(n-1): a,b,l=RL() a-=1 b-=1 g[a].append(b) g[b].append(a) if a>b: a,b=b,a d[a,b]=i edg.append(l) dfs(0,-1) #print(cnt) ans=sum(edg[i]*cnt[i] for i in range(n-1)) ans=ans*6/(n*(n-1)) #print(ans) q=N() for i in range(q): c,l=RL() dec=edg[c-1]-l edg[c-1]=l #print(dec) ans-=dec*cnt[c-1]*6/((n-1)*n) print(ans) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thread(target=main) t.start() t.join() ''' ```
2,861
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` import sys sys.setrecursionlimit(1500) MAX = 100005; g = [[] for _ in range(MAX)] vis = [False] * MAX dp = [0] * MAX prod = [0] * MAX edges = [] order = [] def dfs(st): stack = [] stack.append((st, -1)) vis[st] = True while stack: st, parent = stack.pop() order.append(st) vis[st] = True if (st == parent): continue; for i in g[st]: if (vis[i[0]]): continue; stack.append((i[0], st)) n = int(input()) for i in range(n-1): a, b, w = map(int, sys.stdin.readline().split(' ')) g[a].append([b, w]) g[b].append([a,w]) edges.append([[a, b], w]) dfs(1); order.reverse() for st in order: dp[st] = 1; for i in g[st]: dp[st] += dp[i[0]]; tot = 0; curr = 1; div = n * (n-1) / 2; for i in edges: a = i[0][0]; b = i[0][1]; sa = dp[a]; sb = dp[b]; tot += min(sa, sb) * (n - min(sa, sb)) * i[1]; prod[curr] = min(sa, sb) * (n - min(sa, sb)); curr += 1; q = int(input()) for i in range(q): q1, q2 = map(int, sys.stdin.readline().split(' ')) tot -= prod[q1] * edges[q1-1][1]; edges[q1-1][1] = q2; tot += prod[q1] * edges[q1-1][1]; sys.stdout.write(str(tot*3/div)+"\n") ```
2,862
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(10**5) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def dfs(u,p): global ans for j in adj[u]: if j!=p: yield dfs(j,u) sub[u]+=sub[j] p1=sub[u] p2=n-sub[u] d1[(u,p)]=p1*p2*(p1+p2-2) d1[(p, u)] = p1 * p2 * (p1 + p2 - 2) ans+=(p1*p2*(p1+p2-2))*d[(u,p)] yield n=int(input()) adj=[[] for i in range(n+1)] edges=[] d=defaultdict(lambda:0) d1=defaultdict(lambda:0) ans=0 for i in range(n-1): u,v,l=map(int,input().split()) d[(u,v)]=l d[(v,u)]=l edges.append([u,v]) adj[u].append(v) adj[v].append(u) sub=[1 for i in range(n+1)] dfs(1,0) val=n*(n-1)*(n-2) for q in range(int(input())): nu,new=map(int,input().split()) edge=edges[nu-1] u,v=edge[0],edge[1] old=d[(u,v)] tot=d1[(u,v)] ans+=tot*(new-old) d[(u,v)]=new d[(v,u)]=new print((6*ans)/val) ```
2,863
Provide tags and a correct Python 3 solution for this coding contest problem. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Tags: combinatorics, dfs and similar, graphs, trees Correct Solution: ``` from queue import Queue import sys cost = [] def readarray(): return map(int, input().split(' ')) n = int(input()) graph = [[] for i in range(n)] for i in range(n - 1): u, v, c = readarray() u, v = u - 1, v - 1 cost.append(c) graph[u].append((v, i)) graph[v].append((u, i)) order = [] used = [0] * n q = [0] * (n + n) qh = qt = 0 used[qh] = 1 qh += 1 while qt < qh: v = q[qt] qt += 1 order.append(v) for (to, e) in graph[v]: if used[to]: continue used[to] = 1 q[qh] = to qh += 1 order.reverse() sz = [0 for x in range(n)] for v in order: sz[v] = 1 for (to, e) in graph[v]: sz[v] += sz[to] """ sz = [0] * n sys.setrecursionlimit(100505) def dfs(v, p): sz[v] = 1 for (to, e) in graph[v]: if to != p: dfs(to, v) sz[v] += sz[to] dfs(0, -1) """ distanceSum = 0.0 edgeMult = [0] * n for v in range(n): for (to, e) in graph[v]: x = min(sz[v], sz[to]) edgeMult[e] = x distanceSum += 1.0 * cost[e] * x * (n - x) distanceSum /= 2.0 queryCnt = int(input()) ans = [] for i in range(queryCnt): x, y = readarray() x -= 1 distanceSum -= 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x]) cost[x] = y distanceSum += 1.0 * cost[x] * edgeMult[x] * (n - edgeMult[x]) ans.append('%.10lf' % (distanceSum / n / (n - 1) * 6.0)) print('\n'.join(ans)) ```
2,864
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Submitted Solution: ``` import sys MAX = 100005; g = [[] for _ in range(MAX)] vis = [False] * MAX dp = [0] * MAX prod = [0] * MAX edges = [] def dfs(st, parent = -1): vis[st] = True if (st == parent): return; for i in g[st]: if (vis[i[0]]): continue; dfs(i[0], st) dp[st] = 1; for i in g[st]: dp[st] += dp[i[0]]; n = int(input()) for i in range(n-1): a, b, w = map(int, sys.stdin.readline().split(' ')) g[a].append([b, w]) g[b].append([a,w]) edges.append([[a, b], w]) dfs(1); tot = 0; curr = 1; div = n * (n-1) / 2; for i in edges: a = i[0][0]; b = i[0][1]; sa = dp[a]; sb = dp[b]; tot += min(sa, sb) * (n - min(sa, sb)) * i[1]; prod[curr] = min(sa, sb) * (n - min(sa, sb)); curr += 1; q = int(input()) for i in range(q): q1, q2 = map(int, sys.stdin.readline().split(' ')) tot -= prod[q1] * edges[q1-1][1]; edges[q1-1][1] = q2; tot += prod[q1] * edges[q1-1][1]; sys.stdout.write(str(tot*3/div)) ``` No
2,865
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Submitted Solution: ``` n = int(input()) ni = [list(map(int,input().split())) for i in range(n-1)] q = int(input()) qi = [list(map(int,input().split())) for i in range(q)] summ = 0 for num in range(n-1): summ += ni[num][2]*(n-1) for num in range(q): summ -= (ni[qi[num][0]-1][2] - qi[num][1])*(n-1) ni[qi[num][0]-1][2] = qi[num][1] print(float(summ)/((n)*(n-1)*(n-2))) ``` No
2,866
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Submitted Solution: ``` import sys sys.setrecursionlimit(1500) MAX = 100005; g = [[] for _ in range(MAX)] vis = [False] * MAX dp = [0] * MAX prod = [0] * MAX edges = [] def dfs(st): stack = [] stack.append((st, -1)) vis[st] = True while stack: st, parent = stack.pop() vis[st] = True if (st == parent): continue; for i in g[st]: if (vis[i[0]]): continue; stack.append((i[0], st)) dp[st] = 1; for i in g[st]: dp[st] += dp[i[0]]; n = int(input()) for i in range(n-1): a, b, w = map(int, sys.stdin.readline().split(' ')) g[a].append([b, w]) g[b].append([a,w]) edges.append([[a, b], w]) dfs(1); tot = 0; curr = 1; div = n * (n-1) / 2; for i in edges: a = i[0][0]; b = i[0][1]; sa = dp[a]; sb = dp[b]; tot += min(sa, sb) * (n - min(sa, sb)) * i[1]; prod[curr] = min(sa, sb) * (n - min(sa, sb)); curr += 1; q = int(input()) for i in range(q): q1, q2 = map(int, sys.stdin.readline().split(' ')) tot -= prod[q1] * edges[q1-1][1]; edges[q1-1][1] = q2; tot += prod[q1] * edges[q1-1][1]; sys.stdout.write(str(tot*3/div)+"\n") ``` No
2,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v. As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1. Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck. It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network. However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value. Input The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times. Output Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6. Examples Input 3 2 3 5 1 3 3 5 1 4 2 2 1 2 2 1 1 1 Output 14.0000000000 12.0000000000 8.0000000000 6.0000000000 4.0000000000 Input 6 1 5 3 5 3 2 6 1 7 1 4 4 5 2 3 5 1 2 2 1 3 5 4 1 5 2 Output 19.6000000000 18.6000000000 16.6000000000 13.6000000000 12.6000000000 Note Consider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 1). Submitted Solution: ``` n = int(input()) g, l, e = [[] for x in range(n+1)], [0] * n, [0] * n for i in range(1,n): x, y, e[i] = map(int,input().split()) g[x] += [[y, i]] g[y] += [[x, i]] print(g) def dfs(i,p): d = 1 for z in g[i]: if z[0] != p: u = dfs(z[0],i) d += u l[z[1]] = u * (n-u) return d dfs(1,0) s = 0 for i in range(1,n): s += l[i] * e[i] m = int(input()) while m > 0: m -= 1 r, w = map(int,input().split()) s += (w - e[r]) * l[r] e[r] = w print("%.17f"%float(6*s/n/(n-1))) ``` No
2,868
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Tags: dfs and similar, greedy, implementation Correct Solution: ``` n = int(input()) arr = list(map(int, input().split())) ans = 0 b = 2 ** (n + 1) - 3 while n != 0: n -= 1 #print(n) p = 2 ** (n + 1) - 3 while b != p: ans += abs(arr[b] - arr[b - 1]) arr[b // 2 - 1] += max(arr[b], arr[b - 1]) #print(arr) b -= 2 print(ans) ```
2,869
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Tags: dfs and similar, greedy, implementation Correct Solution: ``` def main(): n, l, res = 2 ** (int(input()) + 1) - 2, [0, 0], 0 l.extend(map(int, input().split())) while n: a, b = l[n], l[n + 1] if a < b: l[n // 2] += b res += b - a else: l[n // 2] += a res += a - b n -= 2 print(res) if __name__ == '__main__': main() ```
2,870
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Tags: dfs and similar, greedy, implementation Correct Solution: ``` # fin = open("input.txt") # n = int(fin.readline()) # A = [0] + list(map(int, fin.readline().split())) n = int(input()) A = [0] + list(map(int, input().split())) C = 0 for i in range(2 ** n - 2, -1, -1): C += abs(A[i * 2 + 1] - A[i * 2 + 2]) A[i] += max(A[i * 2 + 1], A[i * 2 + 2]) print(C) ```
2,871
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Tags: dfs and similar, greedy, implementation Correct Solution: ``` s = 0 n = int(input()) k = (1 << (n + 1)) - 1 a = [0, 0] + list(map(int, input().split())) for i in range(k, 1, -2): u, v = a[i], a[i - 1] if u > v: u, v = v, u s += v - u a[i >> 1] += v print(s) ```
2,872
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Tags: dfs and similar, greedy, implementation Correct Solution: ``` #!python3 n = int(input()) a = input().split() a = [int(i) for i in a] def solve(n, a, added): last = a[-2**n:] new = [] for i in range(0, 2**n-1, 2): #print(last[i]) x = last[i] y = last[i+1] new.append(max(x,y)) added = added + abs(x-y) a = a[:-2**n] if a==[]: a = [0] for i in range(1, 2**(n-1)+1): a[-i] = a[-i] + new[-i] n = n-1 if n==0: print(added) else: solve(n, a, added) solve(n, a, 0) ```
2,873
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Tags: dfs and similar, greedy, implementation Correct Solution: ``` n = 2**(int(input())+1)-1; a = [0,0] + list(map(int,input().split())) r = 0 while n>1: a[n//2] += max(a[n], a[n-1]) r += abs(a[n]-a[n-1]) n -= 2 print(r) ```
2,874
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Tags: dfs and similar, greedy, implementation Correct Solution: ``` n = int(input()) l = list(map(int,input().split())) l = [0]+l top = 1 lim = 2**(n+1)-1 count = 0 def solver(top): global count left = top*2+1 right = 2+ top*2 if(left>lim or right>lim): #print(top,"ret ",l[top]) return l[top] else: ll = solver(left) rr = solver(right) if(ll!=rr): count+= max(ll,rr)-min(ll,rr) #print("change ",max(ll,rr)-min(ll,rr)) #print("ret" , max(ll,rr)+l[top]) return max(ll,rr)+l[top] solver(0) print(count) ```
2,875
Provide tags and a correct Python 3 solution for this coding contest problem. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Tags: dfs and similar, greedy, implementation Correct Solution: ``` from math import floor def main(): n = int(input()) a = list(map(int, input().split())) streets = [] for i in range(2**n, 2**(n+1)): #print('---') idx = i #print(idx) if idx > 1: #print('Cost: %d' % a[idx-2]) res = a[idx-2] while idx > 0: idx = int(floor(idx/2)) if idx > 1: #print(idx) #print('Cost: %d' % a[idx-2]) res += a[idx-2] #print('res: %d' % res) streets.append(res) res = 0 #print(streets) while len(streets) > 2: new_streets = [] for i in range(0, len(streets), 2): #print('i: %d' % i) res += abs(streets[i]-streets[i+1]) new_streets.append(max(streets[i], streets[i+1])) #print(new_streets, cur_diff) streets = new_streets print(res+abs(streets[0]-streets[1])) if __name__ == '__main__': main() ```
2,876
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- # author: firolunis # version: 0.1 n = int(input()) park = input().split(' ') park = [int(i) for i in park] park.insert(0, 0) lights = [0 for i in range(2 ** (n + 1) - 1)] res = 0 for k in range(n, 0, -1): for i, j in tuple(enumerate(park))[(2 ** k) - 1:2 ** (k + 1) - 1:2]: res += abs(j + lights[i] - park[i + 1] - lights[i + 1]) lights[i // 2] = max(j + lights[i], park[i + 1] + lights[i + 1]) print(res) ``` Yes
2,877
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` n = int(input()) park = [0] * (2 ** (n + 1)) park[2: 2 ** (n + 1)] = [int(i) for i in input().split()] cnt = 0 for i in range(2 ** n - 1, 0, -1): cnt += abs(park[i * 2 + 1] - park[i * 2]) park[i] += max(park[i * 2 + 1], park[i * 2]) print(cnt) ``` Yes
2,878
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` # print ("Enter n") n = int(input()) alen = 2**(n+1) a = [0 for i in range(alen)] # print ("Enter all values on the same line") inp = input().split() for i in range(len(inp)): a[i+2] = int(inp[i]) answer = 0 while (n > 0): index = 2**n for i in range(index, index*2, 2): left = a[i] right = a[i+1] diff = abs(left-right) bigone = max(left, right) answer += diff a[i//2] += bigone n = n - 1 print (answer) ``` Yes
2,879
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` #!/usr/bin/python3 n = 2**(int(input())+1)-1 d = input().split(' ') for i in range(len(d)): d[i] = int(d[i]) p = 0 for i in range(len(d)-1, 0, -2): p += abs(d[i]-d[i-1]) d[i//2-1] += max(d[i], d[i-1]) print(p) ``` Yes
2,880
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` # fin = open("input.txt") # n = int(fin.readline()) # A = [0] + list(map(int, fin.readline().split())) n = int(input()) A = list(map(int, input().split())) C = 0 for i in range(n - 1, -1, -1): C += abs(A[i * 2] - A[i * 2 + 1]) A[i] += max(A[i * 2], A[i * 2 + 1]) print(C) ``` No
2,881
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` import math a = int(input()) b = list(map(int, input().split())) co = 2 sum1 = 0 sum2 = 0 j = co for i in b: if j == 0: co = co * 2 j = co if j <= co // 2: sum2 += i else: sum1 += i j -= 1 print(int(math.fabs(sum2-sum1))) ``` No
2,882
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` import sys, os import fileinput n = int(input()) + 1 a = [int(x) for x in input().split()] all_count = 2 ** n - 1 b = [0] * all_count counter = 0 for i in range(n, 1, -1): lcnt = 2 ** (i - 1) first = 2 ** (i - 1) - 2 #print(lcnt, first) level = a[first:first + lcnt] # print(level) for j in range(0, lcnt, 2): index = first + 2 + j if i == n: # print(i) # print("-" * 10) diff = abs(level[j] - level[j + 1]) # print(j, level[j], level[j+1], diff) counter += diff # print(index//2 - 1, level[j] + level[j + 1] + diff) b[index//2 - 1] += level[j] + level[j + 1] + diff # print("=" * 10) else: # print(i) # print("*" * 10) # print(index) # print(b) # print(level) diff = abs(abs(b[index - 1]//2 + level[j]) - abs(b[index]//2 + level[j + 1])) counter += diff b[index//2 - 1] += b[index-1] + b[index] + level[j] + level[j + 1] + diff # print("+" * 10) print(counter) # print(b) ``` No
2,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square <image>. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. <image> To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square <image> has ai lights. Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads. Input The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and <image>. All numbers ai are positive integers, not exceeding 100. Output Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe. Examples Input 2 1 2 3 4 5 6 Output 5 Note Picture for the sample test. Green color denotes the additional street lights. <image> Submitted Solution: ``` import math a = input() b = list(map(int, input().split())) co = 2 sum1 = 0 sum2 = 0 j = co if b == [1, 2, 3, 3, 2, 2]: print(0) exit(0) for i in b: if j == 0: co = co * 2 j = co if j <= co // 2: sum2 += i else: sum1 += i j -= 1 print(int(math.fabs(sum2-sum1))) ``` No
2,884
Provide tags and a correct Python 3 solution for this coding contest problem. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Tags: binary search, greedy Correct Solution: ``` # -*- coding: utf-8 -*- # @Time : 2021/1/15 5:25 下午 # @Author : qu # @Email : quzhenqing@zju.edu.cn # @File : C. GukiZ hates Boxes.py from sys import stdin # n, m = map(int, stdin.buffer.readline().split()) a = list(map(int, stdin.buffer.readline().split())) max_not_zero = 0 for index, value in enumerate(a): if value > 0: max_not_zero = index total = sum(a) def remove(t): boxes = 0 s = m for i in range(max_not_zero+1): boxes += a[i] # 够一个人用的了 while boxes + (i + 1) >= t: boxes -= (t - i - 1) s -= 1 if s < 0: return False if s == 0: if boxes > 0: return False return True def binary_search(left, right): mid = int((left + right) // 2) if right - left <= 1 and remove(left): return left if remove(mid): return binary_search(left, mid) else: return binary_search(mid + 1, right) print(binary_search(2, total + n)) ```
2,885
Provide tags and a correct Python 3 solution for this coding contest problem. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Tags: binary search, greedy Correct Solution: ``` n, m = map(int, input().split()) # a = [0] * n # s = 0 a = list(map(int, input().split())) s = sum(a) l = 2 r = s + n while (l < r): z = l + r >> 1 b = a.copy() p = n - 1 for i in range(m): while (p >= 0 and b[p] == 0): p -= 1 t = z - p - 1 if (t <= 0): break while (p >= 0 and b[p] <= t): t -= b[p] p -= 1 # or do it before? if (p >= 0): b[p] -= t if (p < 0): r = z else: l = z + 1 print(r) ```
2,886
Provide tags and a correct Python 3 solution for this coding contest problem. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Tags: binary search, greedy Correct Solution: ``` from sys import stdin import copy def check(id,b,m,t): ans = 0 i = 0 while i < len(b): ans += b[i] #可以用掉一个人了 while ans + id[i] >= t: ans -= (t - id[i]) m -= 1 if m <= 0: if m == 0 and ans == 0 and i + 1 == len(b): return True return False i = i + 1 return True n, m = map(int, stdin.readline().split()) a = list(map(int, stdin.readline().split())) #右边界 id = [i + 1 for i, e in enumerate(a) if e != 0] b = [a[i - 1] for i in id] R = sum(b) + id[-1] #左边界 L = 0 while L <= R: mid = (L + R) // 2 if L == R: break if check(id,b,m,mid): R = mid else: L = mid + 1 print(R) ```
2,887
Provide tags and a correct Python 3 solution for this coding contest problem. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Tags: binary search, greedy Correct Solution: ``` def read_data(): n, m = map(int, input().split()) A = list(map(int, input().split())) while A and not A[-1]: del A[-1] return len(A), m, A def solve(n, m, A): total = sum(A) upper = n + (total + m - 1) // m lower = n while lower + 1 < upper: mid = (lower + upper) // 2 if is_enough(mid, n, m, A): upper = mid else: lower = mid return lower + 1 def is_enough(t, n, m, A): pool = 0 for i in range(n-1, -1, -1): a = A[i] delta = t - i - 1 b = (a - pool + delta - 1) // delta m -= b if m < 0: return False pool += b * delta - a return True if __name__ == '__main__': n, m, A = read_data() print(solve(n, m, A)) ```
2,888
Provide tags and a correct Python 3 solution for this coding contest problem. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Tags: binary search, greedy Correct Solution: ``` N, M = map(int, input().split()) books_list = list(map(int, input().split())) while books_list[-1] == 0: books_list.pop() books_list.insert(0, 0) def check(Time): piles = books_list[:] last_pile_no = len(piles) - 1 for i in range(M): #student i_time = Time - last_pile_no while True: if i_time >= piles[last_pile_no]: i_time -= piles[last_pile_no] last_pile_no -= 1 if last_pile_no == 0: return True else: piles[last_pile_no] -= i_time break return False l = 0 r = int(sum(books_list)/M) + len(books_list) + 1 while r-l > 1: mid = int((l+r)/2) if check(mid): r = mid else: l = mid print(r) ```
2,889
Provide tags and a correct Python 3 solution for this coding contest problem. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Tags: binary search, greedy Correct Solution: ``` f = lambda: map(int, input().split()) n, m = f() h = list(f())[::-1] def g(t, m): t -= n d = 0 for u in h: t += 1 if u > d: if t < 1: return 1 u -= d d = -u % t m -= (u + d) // t if m < 0: return 1 else: d -= u return 0 a, b = 0, int(11e13) while b - a > 1: c = (b + a) // 2 if g(c, m): a = c else: b = c print(b + 1) ```
2,890
Provide tags and a correct Python 3 solution for this coding contest problem. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Tags: binary search, greedy Correct Solution: ``` n,m=map(int,input().split()) a=list(map(int,input().split())) def c(t): s,r,p,b=m,0,n,0 while 1: while b==0: if p==0: return 1 p-=1 b=a[p] if r==0: if s==0: return 0 r=t-p-1 s-=1 d=min(b,r) b-=d r-=d l,h=0,n+sum(a)+9 while h-l>1: md=(l+h)//2 if c(md): h=md else: l=md print(h) ```
2,891
Provide tags and a correct Python 3 solution for this coding contest problem. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Tags: binary search, greedy Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Tue May 28 20:03:18 2019 @author: fsshakkhor """ N,M = map(int,input().split()) ara = list(map(int,input().split())) while ara[-1] == 0: ara.pop() ara.insert(0,0) def check(Time): piles = ara[:] last_pile_no = len(piles) - 1 for i in range(M): i_time = Time - last_pile_no while True: if i_time >= piles[last_pile_no]: i_time -= piles[last_pile_no] last_pile_no -= 1 if last_pile_no == 0: return True else: piles[last_pile_no] -= i_time break return False lo = 0 hi = int(sum(ara)/M) + len(ara) + 1 ans = 0 while lo <= hi: mid = int((lo+hi)/2) if check(mid): ans = mid hi = mid - 1 else: lo = mid + 1 print(ans) ```
2,892
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Submitted Solution: ``` from sys import stdin import collections import copy def check(t): global m, end stu = m time = 0 for i in range(end): # print(time,stu) time += a[i] while(time+i+1>=t): time -= t-i-1 stu -=1 if stu<0: return 0 if stu ==0: return time<=0 return 1 # def check(t): # global end # flag = end # for i in range(m): # time = t-flag # while(time > 0): # # print(time, flag) # if time>=a[flag-1]: # a[flag-1]=0 # flag -=1 # time -= a[flag-1] # else: # a[flag-1] -= time # time =0 # if flag <1: # return True # if(flag<1): # return True # else: # return False n, m = list(map(int, stdin.readline().split())) a = list(map(int, stdin.readline().split())) l=0 r=0 for i in range(len(a)): r += a[i] if a[i]>0: l = i+1 r += l end = l while(l<=r): mid = (l+r)//2 if(check(mid)): ans = mid r = mid-1 else: # print(l) l = mid+1 print(ans) ``` Yes
2,893
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Submitted Solution: ``` # The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) # where ai represents the number of boxes on i-th pile. # The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. NUM_OF_PILES, NUM_OF_STUDENTS = map(int, input().split()) # a = [0] * n # s = 0 boxes = list(map(int, input().split())) s = sum(boxes) # It's guaranteed that at least one pile of is non-empty. So walk to it and remove a box lower = 2 # That's a case of only one student working upper = s + NUM_OF_PILES while (lower < upper): # z = lower + upper >> 1 guess = (lower + upper) // 2 b = boxes.copy() pile = NUM_OF_PILES - 1 for i in range(NUM_OF_STUDENTS): # walk to a nonempty pile while (pile >= 0 and b[pile] == 0): pile -= 1 time = guess - pile - 1 if (time <= 0): break # remove all boxes from some piles while (pile >= 0 and b[pile] <= time): time -= b[pile] pile -= 1 # or do it before? # remove some boxes in the end if (pile >= 0): b[pile] -= time if (pile < 0): upper = guess else: lower = guess + 1 print(upper) ``` Yes
2,894
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Submitted Solution: ``` # The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. # NUM_OF_PILES, NUM_OF_STUDENTS = map(int, input().split()) NUM_OF_PILES, NUM_OF_STUDENTS = map(int, input().split()) a = list(map(int, input().split())) def test(guess): students_free, time, pile, b = NUM_OF_STUDENTS, 0, NUM_OF_PILES, 0 while True: while b == 0: if pile == 0: return True pile -= 1 b = a[pile] if time == 0: if students_free == 0: return False time = guess - pile - 1 students_free -= 1 d = min(b, time) b -= d time -= d l, h = 0, NUM_OF_PILES + sum(a) + 9 while h - l > 1: md = (l + h) // 2 if test(md): h = md else: l = md print(h) ``` Yes
2,895
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Submitted Solution: ``` ############################### # https://codeforces.com/problemset/problem/551/C # 2021/01/13 # WenhuZhang ################################ from sys import stdin import collections import copy # def check(t): # global n,m,a, end # aa = a.copy() # flag = 0 # for i in range(m): # time = t - (flag+1) # while(time>0): # # print(i, time,aa) # # print(t,flag, time,aa) # if flag >= end or aa[end-1] ==0: # return True # while(aa[flag]==0): # flag+=1 # time-=1 # if time ==0: # break # if aa[flag]>time: # aa[flag] -= time # time=0 # else: # # print("?",time,aa[flag]) # time -= aa[flag] # aa[flag] =0 # if flag >= end or aa[end-1] ==0: # return True # return False def check(t): global m, end stu = m time = 0 for i in range(end): # print(time,stu) time += a[i] while(time+i+1>=t): time -= t-i-1 stu -=1 if stu<0: return 0 if stu ==0: return time<=0 return 1 n, m = list(map(int, stdin.readline().split())) a = list(map(int, stdin.readline().split())) l=0 r=0 for i in range(len(a)): r += a[i] if a[i]>0: l = i+1 r += l end = l while(l<=r): mid = (l+r)//2 # print(l,r,mid) if(check(mid)): ans = mid r = mid-1 else: # print(l) l = mid+1 print(ans) ``` Yes
2,896
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Submitted Solution: ``` N,M=list(map(int,input().split())) p=list(map(int,input().split())) total=sum(p) if(total>M): print(3*total-2*M) elif (total<M): print(N+1) elif (total==M): print(2*total) ``` No
2,897
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Submitted Solution: ``` n, m = map(int, input().split()) boxes = list(map(int, input().split())) cache = [0 for i in range(n + 1)] if boxes.count(0) == n: print(0) exit(0) seconds = 1 cache[0] = m while True: if boxes.count(0) == n: break seconds += 1 stus = cache.copy() for i in range(n): # print(stus[i], boxes[i], sep = "==", end = " ") if stus[i] > boxes[i]: cache[i + 1] += stus[i] - boxes[i] cache[i] = boxes[i] boxes[i] = 0 else: boxes[i] -= stus[i] print(seconds) ``` No
2,898
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: 1. If i ≠ n, move from pile i to pile i + 1; 2. If pile located at the position of student is not empty, remove one box from it. GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed. Input The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty. Output In a single line, print one number, minimum time needed to remove all the boxes in seconds. Examples Input 2 1 1 1 Output 4 Input 3 2 1 0 2 Output 5 Input 4 100 3 4 5 4 Output 5 Note First sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second). Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds. Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. Submitted Solution: ``` ############################### # https://codeforces.com/problemset/problem/551/C # 2021/01/09 # WenhuZhang ################################ from sys import stdin import collections import copy def check(t): global end flag = end for i in range(m): time = t-flag while(time > 0): # print(time, flag) if time>=a[flag-1]: a[flag-1]=0 flag -=1 time -= a[flag-1] else: a[flag-1] -= time time =0 if flag <1: return True if(flag<1): return True else: return False n, m = list(map(int, stdin.readline().split())) a = list(map(int, stdin.readline().split())) l=0 r=0 for i in range(len(a)): r += a[i] if a[i]>0: l = i+1 r += l end = l while(l<=r): mid = (l+r)//2 if(check(mid)): ans = mid r = mid-1 else: l = mid+1 print(ans) ``` No
2,899