text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Tags: brute force, dp, math Correct Solution: ``` n = int(input()) while n>0: k = int(input()) for i in range(k//2020+1): rem = k - i*2020 if rem%2021==0: print("YES") break else: print("NO") n-=1 ```
3,600
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Tags: brute force, dp, math Correct Solution: ``` times = int(input()) def check(n): remainder = n % 2020 quotient = n // 2020 if remainder <= quotient: return "YES" else: return "NO" arr = [] for i in range(times): arr.append(check(int(input()))) for i in range(times): print(arr[i]) ```
3,601
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Tags: brute force, dp, math Correct Solution: ``` ''' Aaditya Upadhyay ud$$$**$$$$$$bc. u@**" 4$$$$$$Nu J ""#$$$$$r @ $$$b .F ^*3$$$ :% 4 J$$N $ :F :$$$$$ 4F 9 J$$$$$$$ 4$ k 4$$$bed$$$$$$$$$ $r 'F $$$$$$$$$$$$$$$$r $$$ b. $$$$$$$$$$$$$$$$N $$$$k 3eeed$b $$Euec."$$$$$$$$$ .@$**N. $$$$$" $$$$$F'L $$$$$$$$$$$ $$$$$$$ :$L 'L $$$$$ 4$$$$$$ * $$$$$$$$$F $$$$$F edNc @$$$N ^k $$$$$ 3$$$$*% F4$$$$$$$ $$$$$" d" zN $$$$$$ ^k '$$$" #$$F .$ $$$$c.u@$$$ J" @$$$r $$$$$$b *u ^L $$ $$$$$$$$$$$u@ $$ d$$$$$$ ^$$$$$$. "NL "N. z@* $$$ $$$$$$$$$$$$P P d$$$$$$$ ^"*$$$b '*L 9E 4$$$ d$$$$$$$$$$$" d* J$$$$r ^$$$u '$. $$L "#" d$$$$$$".@$$ .@$" z$$$$*" ^$$$$. ^N.3$$$ 4u$$$$$$$ 4$$$ u$*" z$$$" '*$$$$$$$$ *b J$$$$$$b u$P $" d$P #$$$$$$ 4$ 3*$"$*$ $"$'c@@$$$$ .u@$$P "$$$$ ""F~$ uNr$$$^&J$$$F $$$$# "$$ "$$bd$.W$$$$$$$F $$" ?k ?$$$$$$$$$$F'* 9$bL z$$$$$$$$$$F $$$$ $$$$$$$$$$$$$ '#$c '$$$$$$$$$" .@"#$$$$$$$$$$$b z* $$$$$$$$$$$N. e" z$$" #$$k '*$$. .u* u@P" '#$c "$c u@$*""" d$$" "$$u ^*$b. :F JP" ^$$c '"$$$$$bL d$$ .. @$# #$b '#$ 9$$$$$b 4$$ ^$k '$ "$""b u$$ '$ d$$$$P 'F $$$$$" ^b ^$$$b$ 'W$$$$" 'b@$$$$" ^$$$* ''' from sys import stdin, stdout from collections import * from math import gcd, floor, ceil def st(): return list(stdin.readline().strip()) def li(): return list(map(int, stdin.readline().split())) def mp(): return map(int, stdin.readline().split()) def inp(): return int(stdin.readline()) def pr(n): return stdout.write(str(n)+"\n") mod = 1000000007 INF = float('inf') def solve(): n = inp() if n % 2020 <= n//2020: pr('YES') else: pr('NO') for _ in range(inp()): solve() ```
3,602
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Tags: brute force, dp, math Correct Solution: ``` t=int(input()) for _ in range(t): n = int(input()) if n<2020: print('NO') else: m = n//2020 if n in range(2020*m,2021*m+1): print('YES') else: print('NO') ```
3,603
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Tags: brute force, dp, math Correct Solution: ``` t=int(input()) for T in range(t): n=int(input()) x=n//2020 if (n-x*2020)<=x: print('YES') else: print('NO') ```
3,604
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Submitted Solution: ``` t = int(input()) while t: t -= 1 n = int(input()) if n < 2020: print("NO") continue """ 2020*a + 2021*b = n 2020*a + 2020*b + b = n 2020*(a+b) + b = n 2020*(a+b) = (n-b) 8079 => 6060 + 2019 => b:2019, (a+b) = 3 """ b = n%2020 aPb = n//2020 a = aPb-b if a < 0: print("NO") continue if 2020*a + 2021*b == n: ans = "YES" else: ans = "NO" print(ans) ``` Yes
3,605
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Submitted Solution: ``` def check(x): if (x%2020) < (x//2020) or x%2021==0 : return True return False #if x < 2020: #return False # else: # return check(x-2020) or check(x-2021) t = int(input()) for i in range(t): n = int(input()) if check(n): print("YES") else: print("NO") ``` Yes
3,606
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Submitted Solution: ``` tests = int(input()) for t in range(tests): a = int(input()) if ((a // 2020) >= (a % 2020)): print("YES") else: print("NO") ``` Yes
3,607
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Submitted Solution: ``` def solve(a, b, n): i = 0 while i * a <= n: if (n - (i * a)) % b == 0: print('YES') return 0 i = i + 1 print("NO") a = 2020 b = 2021 t = int(input()) for i in range(t): n = int(input()) solve(a, b, n) ``` Yes
3,608
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Submitted Solution: ``` t = int(input()) a = [0]*t for i in range(t): c = int(input()) if c < 2020: a[i] = "NO" elif c%2020 == 0: a[i] = "YES" elif c%2021 == 0: a[i] = "YES" else: if abs(int(10*c/2021) - int(10*c/2020)) > 0: a[i] = "YES" else: a[i] = "NO" for i in a: print(i) ``` No
3,609
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Submitted Solution: ``` for i in range(int(input())): n=int(input()) if(n<2020): print("no") elif((n%2021)%2020==0 or (n%2020)%2021==1 ): print("yes") else: print("NO") ``` No
3,610
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Submitted Solution: ``` t=int(input()) for i in range(t): p=int(input()) if p%2021==0 or p%2020==0: print("YES") elif p%4041==0: print("YES") else: print("NO") ``` No
3,611
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp remembered the 2020-th year, and he is happy with the arrival of the new 2021-th year. To remember such a wonderful moment, Polycarp wants to represent the number n as the sum of a certain number of 2020 and a certain number of 2021. For example, if: * n=4041, then the number n can be represented as the sum 2020 + 2021; * n=4042, then the number n can be represented as the sum 2021 + 2021; * n=8081, then the number n can be represented as the sum 2020 + 2020 + 2020 + 2021; * n=8079, then the number n cannot be represented as the sum of the numbers 2020 and 2021. Help Polycarp to find out whether the number n can be represented as the sum of a certain number of numbers 2020 and a certain number of numbers 2021. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow. Each test case contains one integer n (1 ≤ n ≤ 10^6) — the number that Polycarp wants to represent as the sum of the numbers 2020 and 2021. Output For each test case, output on a separate line: * "YES" if the number n is representable as the sum of a certain number of 2020 and a certain number of 2021; * "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). Example Input 5 1 4041 4042 8081 8079 Output NO YES YES YES NO Submitted Solution: ``` t = int(input()) while t: n=int(input()) n2 = n count = 0 while n>2020: n-=2021 if(n==0 or n==2020 or n==2021): count = 1 break while n2>2021: n2-=2020 if(n2==0 or n2==2020 or n2==2021): count = 1 break if(count==1): print("YES") else: print("NO") t-=1 ``` No
3,612
Provide tags and a correct Python 3 solution for this coding contest problem. Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1, y1), (x2, y2), ..., (xn, yn). The first vertex has a coordinate x1 = 1, the second — x2 = 2, etc. Coordinates yi might be any, but should satisfy the following conditions: * there should be t humps precisely, i.e. such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 < yj > yj + 1, * there should be precisely t - 1 such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 > yj < yj + 1, * no segment of a polyline should be parallel to the Ox-axis, * all yi are integers between 1 and 4. For a series of his drawings of camels with t humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with t humps for a given number n. Input The first line contains a pair of integers n and t (3 ≤ n ≤ 20, 1 ≤ t ≤ 10). Output Output the required amount of camels with t humps. Examples Input 6 1 Output 6 Input 4 2 Output 0 Note In the first sample test sequences of y-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 и 234321 (each digit corresponds to one value of yi). Tags: dp Correct Solution: ``` n,t = map(int,input().split()) dp = [[[[0,0] for i in range(t+1)] for j in range(5)] for k in range(n+1)] dp[2][2][1][0]=1 dp[2][3][1][0]=2 dp[2][4][1][0]=3 ans = 0 for i in range(3,n+1): for j in range(1,5): for k in range(1,t+1): for l in range(1,j): dp[i][j][k][0]+=dp[i-1][l][k][0]+dp[i-1][l][k-1][1] for l in range(4,j,-1): dp[i][j][k][1]+=dp[i-1][l][k][1]+dp[i-1][l][k][0] for i in range(1,5): ans+=dp[n][i][t][1] print(ans) ```
3,613
Provide tags and a correct Python 3 solution for this coding contest problem. Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1, y1), (x2, y2), ..., (xn, yn). The first vertex has a coordinate x1 = 1, the second — x2 = 2, etc. Coordinates yi might be any, but should satisfy the following conditions: * there should be t humps precisely, i.e. such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 < yj > yj + 1, * there should be precisely t - 1 such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 > yj < yj + 1, * no segment of a polyline should be parallel to the Ox-axis, * all yi are integers between 1 and 4. For a series of his drawings of camels with t humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with t humps for a given number n. Input The first line contains a pair of integers n and t (3 ≤ n ≤ 20, 1 ≤ t ≤ 10). Output Output the required amount of camels with t humps. Examples Input 6 1 Output 6 Input 4 2 Output 0 Note In the first sample test sequences of y-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 и 234321 (each digit corresponds to one value of yi). Tags: dp Correct Solution: ``` __author__ = 'Darren' def solve(): def find_ways(t, n, h): if t == breaks and n == total: return 1 if t > breaks or n == total: return 0 if (t, n, h) not in dp: result = 0 if t % 2 == 0: for i in range(h+1, 5): result += find_ways(t, n+1, i) for i in range(1, h): result += find_ways(t+1, n+1, i) else: for i in range(h+1, 5): result += find_ways(t+1, n+1, i) for i in range(1, h): result += find_ways(t, n+1, i) dp[(t, n, h)] = result return dp[(t, n, h)] total, humps = map(int, input().split()) breaks = 2 * humps - 1 dp = {} ans = 0 for i in range(2, 5): ans += (i - 1) * find_ways(0, 2, i) print(ans) if __name__ == '__main__': solve() ```
3,614
Provide tags and a correct Python 3 solution for this coding contest problem. Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1, y1), (x2, y2), ..., (xn, yn). The first vertex has a coordinate x1 = 1, the second — x2 = 2, etc. Coordinates yi might be any, but should satisfy the following conditions: * there should be t humps precisely, i.e. such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 < yj > yj + 1, * there should be precisely t - 1 such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 > yj < yj + 1, * no segment of a polyline should be parallel to the Ox-axis, * all yi are integers between 1 and 4. For a series of his drawings of camels with t humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with t humps for a given number n. Input The first line contains a pair of integers n and t (3 ≤ n ≤ 20, 1 ≤ t ≤ 10). Output Output the required amount of camels with t humps. Examples Input 6 1 Output 6 Input 4 2 Output 0 Note In the first sample test sequences of y-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 и 234321 (each digit corresponds to one value of yi). Tags: dp Correct Solution: ``` n,t=map(int,input().split()) t=2*t-1 dp=[[[[0,0] for h in range(5)] for j in range(t+2)] for i in range(n+1)] for h in range(1,5): dp[2][0][h][0]=4-h dp[2][0][h][1] = h-1 for i in range(2,n): for j in range(t+1): for h in range(1,5): for ne in range(1,5): for k in range(2): if (h!=ne): if (k%2): if (ne<h): if (j%2==0): dp[i+1][j+1][ne][1-k]+=dp[i][j][h][k] else: dp[i+1][j][ne][k]+=dp[i][j][h][k] else: if (ne>h): if (j%2==1): dp[i+1][j+1][ne][1-k]+=dp[i][j][h][k] else: dp[i+1][j][ne][k]+=dp[i][j][h][k] ans=0 for h in range(1,4): ans+=dp[n][t][h][0] print(ans) ```
3,615
Provide tags and a correct Python 3 solution for this coding contest problem. Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1, y1), (x2, y2), ..., (xn, yn). The first vertex has a coordinate x1 = 1, the second — x2 = 2, etc. Coordinates yi might be any, but should satisfy the following conditions: * there should be t humps precisely, i.e. such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 < yj > yj + 1, * there should be precisely t - 1 such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 > yj < yj + 1, * no segment of a polyline should be parallel to the Ox-axis, * all yi are integers between 1 and 4. For a series of his drawings of camels with t humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with t humps for a given number n. Input The first line contains a pair of integers n and t (3 ≤ n ≤ 20, 1 ≤ t ≤ 10). Output Output the required amount of camels with t humps. Examples Input 6 1 Output 6 Input 4 2 Output 0 Note In the first sample test sequences of y-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 и 234321 (each digit corresponds to one value of yi). Tags: dp Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, t = map(int, input().split()) dp = [[[0] * 5 for _ in range(2 * t + 1)] for _ in range(n)] dp[0][0] = [0] + [1] * 4 for i in range(n - 1): for j in range(min(2 * t, i + 1)): if (j & 1) == 0: for k in range(1, 4): for l in range(k + 1, 5): # // dp[i + 1][j][l] += dp[i][j][k] # /\ dp[i + 1][j + 1][l] += dp[i][j][k] else: for k in range(4, 1, -1): for l in range(k - 1, 0, -1): # \\ dp[i + 1][j][l] += dp[i][j][k] # \/ dp[i + 1][j + 1][l] += dp[i][j][k] print(sum(dp[-1][2 * t])) ```
3,616
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1, y1), (x2, y2), ..., (xn, yn). The first vertex has a coordinate x1 = 1, the second — x2 = 2, etc. Coordinates yi might be any, but should satisfy the following conditions: * there should be t humps precisely, i.e. such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 < yj > yj + 1, * there should be precisely t - 1 such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 > yj < yj + 1, * no segment of a polyline should be parallel to the Ox-axis, * all yi are integers between 1 and 4. For a series of his drawings of camels with t humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with t humps for a given number n. Input The first line contains a pair of integers n and t (3 ≤ n ≤ 20, 1 ≤ t ≤ 10). Output Output the required amount of camels with t humps. Examples Input 6 1 Output 6 Input 4 2 Output 0 Note In the first sample test sequences of y-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 и 234321 (each digit corresponds to one value of yi). Submitted Solution: ``` n,t=map(int,input().split()) t=2*t-1 dp=[[[[0,0] for h in range(5)] for j in range(t+2)] for i in range(n+1)] for h in range(1,4): dp[2][0][h][0]=4-h dp[2][0][h][1] = h-1 for i in range(2,n): for j in range(t+1): for h in range(1,5): for ne in range(1,5): for k in range(2): if (h!=ne): if (k%2): if (ne<h): if (j%2==0): dp[i+1][j+1][ne][1-k]+=dp[i][j][h][k] else: dp[i+1][j][ne][k]+=dp[i][j][h][k] else: if (ne>h): if (j%2==1): dp[i+1][j+1][ne][1-k]+=dp[i][j][h][k] else: dp[i+1][j][ne][k]+=dp[i][j][h][k] ans=0 for h in range(1,4): ans+=dp[n][t][h][0] print(ans) ``` No
3,617
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1, y1), (x2, y2), ..., (xn, yn). The first vertex has a coordinate x1 = 1, the second — x2 = 2, etc. Coordinates yi might be any, but should satisfy the following conditions: * there should be t humps precisely, i.e. such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 < yj > yj + 1, * there should be precisely t - 1 such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 > yj < yj + 1, * no segment of a polyline should be parallel to the Ox-axis, * all yi are integers between 1 and 4. For a series of his drawings of camels with t humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with t humps for a given number n. Input The first line contains a pair of integers n and t (3 ≤ n ≤ 20, 1 ≤ t ≤ 10). Output Output the required amount of camels with t humps. Examples Input 6 1 Output 6 Input 4 2 Output 0 Note In the first sample test sequences of y-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 и 234321 (each digit corresponds to one value of yi). Submitted Solution: ``` f = [[[0] * 5] * 11] * 21 g = [[[0] * 5] * 11] * 21 n, t = map(int, input().split()) for i in range(1, 5): f[2][1][i] = i - 1 for i in range(1, 5): g[2][1][i] = 0 for i in range(3, n + 1): for j in range(1, t + 1): for k in range(1, 5): for s in range(1, k): f[i][j][k] += f[i - 1][j][s] + g[i - 1][j - 1][s] for s in range(k + 1, 5): g[i][j][k] += g[i - 1][j][s] + f[i - 1][j][s] ans = 0 for i in range(1, 5): ans += g[n][t][i] print(ans) ``` No
3,618
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Tags: constructive algorithms, greedy Correct Solution: ``` for t in range(int(input())): N = int(input()) arr = list(map(int,input().split())) if arr == sorted(arr): print(0) elif arr[0] == 1 or arr[-1] == N: print(1) elif arr[0] == N and arr[-1] == 1: print(3) else: print(2) ```
3,619
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Tags: constructive algorithms, greedy Correct Solution: ``` for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) s=sorted(l) if s==l: print(0) else: if l[0]==n and l[-1]==1: print(3) elif l[0]==1 or l[-1]==n: print(1) else: print(2) ```
3,620
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Tags: constructive algorithms, greedy Correct Solution: ``` ''' ___ ___ ___ ___ ___ ___ /\__\ /\ \ _____ /\ \ /\ \ /\ \ /\__\ /:/ _/_ \:\ \ /::\ \ \:\ \ ___ /::\ \ |::\ \ ___ /:/ _/_ /:/ /\ \ \:\ \ /:/\:\ \ \:\ \ /\__\ /:/\:\__\ |:|:\ \ /\__\ /:/ /\ \ /:/ /::\ \ ___ \:\ \ /:/ \:\__\ ___ /::\ \ /:/__/ /:/ /:/ / __|:|\:\ \ /:/ / /:/ /::\ \ /:/_/:/\:\__\ /\ \ \:\__\ /:/__/ \:|__| /\ /:/\:\__\ /::\ \ /:/_/:/__/___ /::::|_\:\__\ /:/__/ /:/_/:/\:\__\ \:\/:/ /:/ / \:\ \ /:/ / \:\ \ /:/ / \:\/:/ \/__/ \/\:\ \__ \:\/:::::/ / \:\~~\ \/__/ /::\ \ \:\/:/ /:/ / \::/ /:/ / \:\ /:/ / \:\ /:/ / \::/__/ ~~\:\/\__\ \::/~~/~~~~ \:\ \ /:/\:\ \ \::/ /:/ / \/_/:/ / \:\/:/ / \:\/:/ / \:\ \ \::/ / \:\~~\ \:\ \ \/__\:\ \ \/_/:/ / /:/ / \::/ / \::/ / \:\__\ /:/ / \:\__\ \:\__\ \:\__\ /:/ / \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ ''' """ ░░██▄░░░░░░░░░░░▄██ ░▄▀░█▄░░░░░░░░▄█░░█░ ░█░▄░█▄░░░░░░▄█░▄░█░ ░█░██████████████▄█░ ░█████▀▀████▀▀█████░ ▄█▀█▀░░░████░░░▀▀███ ██░░▀████▀▀████▀░░██ ██░░░░█▀░░░░▀█░░░░██ ███▄░░░░░░░░░░░░▄███ ░▀███▄░░████░░▄███▀░ ░░░▀██▄░▀██▀░▄██▀░░░ ░░░░░░▀██████▀░░░░░░ ░░░░░░░░░░░░░░░░░░░░ """ import sys import math import collections import operator as op from collections import deque from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2, floor, log from bisect import bisect_right, bisect_left, bisect from itertools import permutations # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') from functools import reduce from sys import stdin, stdout, setrecursionlimit setrecursionlimit(2**20) def ncr(n, r): r = min(r, n - r) numer = reduce(op.mul, range(n, n - r, -1), 1) denom = reduce(op.mul, range(1, r + 1), 1) return numer // denom # or / in Python 2 def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return (list(factors)) def isPowerOfTwo(x): return (x and (not(x & (x - 1)))) def find_gcd(x, y): while(y): x, y = y, x % y return x MOD = 1000000007 # 10^9 + 7 PMOD = 998244353 LOGN = 30 alp = 'abcdefghijklmnopqrstuvwxyz' N = int(1e5) T = 1 T = int(stdin.readline()) for _ in range(T): # a,b = list(map(int, stdin.readline().rstrip().split())) n = int(stdin.readline()) a = list(map(int, stdin.readline().rstrip().split())) # s = list(map(int, stdin.readline().rstrip().split())) # s = list(stdin.readline().strip('\n')) # t = list(stdin.readline().strip('\n')) # a = str(stdin.readline().strip('\n')) # c = list(map(int, stdin.readline().rstrip().split())) A = a.copy() A.sort() if A == a: print(0) elif (A[0] == a[0]) or (A[-1] == a[-1]): print(1) elif (A[0] == a[-1]) and (A[-1] == a[0]): print(3) else: print(2) ```
3,621
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Tags: constructive algorithms, greedy Correct Solution: ``` def zip_sorted(a,b): return zip(*sorted(zip(a,b)))[0],zip(*sorted(zip(a,b)))[1] def gcd(a,b): return math.gcd(a,b) def lcm(a,b): return ((a*b)//math.gcd(a,b)) def ncr(n,r): return math.comb(n,r) def npr(n,r): return (math.factorial(n)//math.factorial(n-r)) def decimal_to_binary(n): return bin(n).replace("0b", "") def binary_to_decimal(s): return int(s,2) import sys, os.path import math from collections import defaultdict,deque input = sys.stdin.readline I = lambda : list(map(int,input().split())) S = lambda : list(map(str,input())) def main(): t,=I() for t1 in range(t): n, = I() a = I() if a==sorted(a): print(0) else: if a[0]==max(a) and a[-1]==min(a): print(3) elif a[0]==min(a) or a[-1]==max(a): print(1) else: print(2) main() ```
3,622
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Tags: constructive algorithms, greedy Correct Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) b = sorted(a) if a == b: print(0) elif min(a) == a[0] or max(a) == a[-1]: print(1) elif min(a) == a[-1] and max(a) == a[0]: print(3) else: print(2) ```
3,623
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Tags: constructive algorithms, greedy Correct Solution: ``` import sys;input=sys.stdin.readline # from itertools import accumulate # from decimal import * import math # getcontext().prec = 50 # s = input().strip() # n = int(input()) # lis = list(map(int,input().split())) # x,y = map(int,input().split()) # def solve(): # chars = 'abcdefghijklmnopqrstuvwxyz' # for _ in range(int(input())): # solve() # print() # def gcd(a,b): # return gcd (b, a % b) if b else a def solve(): n=int(input()) lis = list(map(int,input().split())) ans = [i for i in range(1,n+1)] rev = [i for i in reversed(ans)] if lis==ans: print(0) elif lis[0]==n and lis[-1]==1: print(3) elif lis[0]==1 or lis[-1]==n: print(1) else: print(2) return # solve() for _ in range(int(input())): solve() ```
3,624
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Tags: constructive algorithms, greedy Correct Solution: ``` for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) def check(): for i in range(n): if a[i] != i+1: return False return True if check(): print(0) else: if a[0] == 1 or a[n-1] == n: print(1) elif a[0] == n and a[n-1] == 1: print(3) else: print(2) ```
3,625
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Tags: constructive algorithms, greedy Correct Solution: ``` T = int(input()) for _ in range(T): n = int(input()) line = input() arr = [int(__) for __ in line.split(' ')] min_num, max_num, last = arr[0], arr[0], arr[0] flag = True for x in arr: if x < last: flag = False last = x min_num = min(min_num, x) max_num = max(max_num, x) if flag: print(0) elif min_num == arr[0] or max_num == arr[-1]: print(1) elif min_num == arr[-1] and max_num == arr[0]: print(3) else: print(2) ```
3,626
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Submitted Solution: ``` import sys,math from collections import deque,defaultdict import operator as op from functools import reduce from itertools import permutations import heapq # sys.setrecursionlimit(10**7) #OneDrive\Documents\codeforces I=sys.stdin.readline alpha="abcdefghijklmnopqrstuvwxyz" mod=10**9 + 7 """ x_move=[-1,0,1,0,-1,1,1,-1] y_move=[0,1,0,-1,1,1,-1,-1] """ def ii(): return int(I().strip()) def li(): return list(map(int,I().strip().split())) def mi(): return map(int,I().strip().split()) def ncr(n, r): r = min(r, n-r) numer = reduce(op.mul, range(n, n-r, -1), 1) denom = reduce(op.mul, range(1, r+1), 1) return numer // denom def gcd(x, y): while y: x, y = y, x % y return x def isPrime(n): if n<=1: return False elif n<=2: return True else: for i in range(2,int(n**.5)+1): if n%i==0: return False return True #print("Case #"+str(_+1)+":",ans) def main(): ans="" for _ in range(ii()): n=ii() arr=li() if arr==sorted(arr): ans+="0\n" elif arr[0]!=1: if arr[n-1]==n: ans+="1\n" elif arr[0]==n and arr[n-1]==1: ans+="3\n" else: ans+="2\n" else: ans+="1\n" print(ans) if __name__ == '__main__': main() ``` Yes
3,627
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Submitted Solution: ``` for _ in range(int(input())): n = int(input()) arr = input() l = list(map(int, arr.split(' '))) c=0 if l.index(min(l)) != 0: c += 1 if l.index(max(l))!= (n-1): c +=1 if l.index(max(l)) == (0) and l.index(min(l)) == (n-1): c=3 if l.index(max(l)) == (n-1) and l.index(min(l)) == 0: if l == sorted(l): c=0 else: c=1 print(c) ``` Yes
3,628
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Submitted Solution: ``` for i in range(int(input())): k=int(input()) l=list(map(int,input().split())) x,y=l.index(min(l)),l.index(max(l)) if l==sorted(l):print(0) elif y==0 and x==k-1:print(3) elif y==k-1 or x==0:print(1) else:print(2) ``` Yes
3,629
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Submitted Solution: ``` from sys import stdin # input = stdin.readline for test in range(int(input())): k = int(input()) lst = [i for i in range(1, k + 1)] arr = list(map(int, input().split())) ans = 0 if arr == lst: print(0) elif arr[0] == 1 or arr[-1] == k: print(1) else: if arr[0] == k and arr[-1] == 1: print(3) else: print(2) ``` Yes
3,630
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Submitted Solution: ``` from sys import stdin,stdout input = stdin.readline # import io,os # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def im(): return map(int,input().split()) def ii(): return int(input()) def il(): return list(map(int,input().split())) def ins(): return input()[:-1] def check(lis): for i in range(1,len(lis)): if lis[i]<=lis[i-1]: return False return True for _ in range(ii()): n = ii() lis = il() if check(lis): print(0) elif lis[0]==1 or lis[-1]==n: print(1) elif lis[0]==n or lis[-1]==1: print(3) else: print(2) ``` No
3,631
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Submitted Solution: ``` def checkDescending(a): for i in range(len(a)-1): if a[i] < a[i+1]: return False return True t = int(input()) for test_case in range(t): n = int(input()) a = [int(num) for num in input().split()] times = 0 for i in range(n): # 0-based array, a[0] = 1 if checkDescending(a): times = n break if a[i] != i+1: print("not match index!", i, a[i]) r = n if i > 0 else n - 1 processed = False for j in range(i, r): if a[j] == i+1: sub_array = a[i:j+1] sub_array.sort() a[i:j+1] = sub_array times += 1 processed = True break print(sub_array) #break if j == r-1 and not processed: sub_array = a[i:j + 1] sub_array.sort() a[i:j+1] = sub_array times += 1 processed = True print("hi", sub_array) #break print(times) ``` No
3,632
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Submitted Solution: ``` import sys import math def scan(input_type='int'): if input_type == 'int': return list(map(int, sys.stdin.readline().strip().split())) else: return list(map(str, sys.stdin.readline().strip())) def solution(): for _ in range(int(input())): n = int(input()) a = scan() c = 0 for i in range(n-1): if a[i] > a[i+1]: c += 1 c -= 1 if c >= 2: print(c) else: print(c + 1) if __name__ == '__main__': solution() ``` No
3,633
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once). You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array. For example, if a = [2, 1, 4, 5, 3] and we want to apply the operation to the subarray a[2, 4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a = [2, 5, 1, 4, 3] or, for example, a = [2, 1, 5, 4, 3]. Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order. Input The first line contains a single integer t (1 ≤ t ≤ 2000) — the number of test cases. The first line of the test case contains a single integer n (3 ≤ n ≤ 50) — the number of elements in the permutation. The second line of the test case contains n distinct integers from 1 to n — the given permutation a. Output For each test case, output a single integer — the minimum number of operations described above to sort the array a in ascending order. Example Input 3 4 1 3 2 4 3 1 2 3 5 2 1 4 5 3 Output 1 0 2 Note In the explanations, a[i, j] defines the subarray of a that starts from the i-th element and ends with the j-th element. In the first test case of the example, you can select the subarray a[2, 3] and swap the elements in it. In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations. In the third test case of the example, you can select the subarray a[3, 5] and reorder the elements in it so a becomes [2, 1, 3, 4, 5], and then select the subarray a[1, 2] and swap the elements in it, so a becomes [1, 2, 3, 4, 5]. Submitted Solution: ``` def mySort(A): B = [] c = 0 for i in range(len(A)-1): if A[i] > A[i+1]: B.append(A[i+1:]) x = min(B[0]) y = A.index(x) A[i], A[y] = A[y], A[i] c += 1 return c L = [] for i in range(int(input())): q = int(input()) A = [int(i) for i in input().split()[:q]] L.append(mySort(A)) for e in L: print(e) ``` No
3,634
Provide tags and a correct Python 3 solution for this coding contest problem. As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues. Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T. Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k. Input The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual. Output Print the single number — the answer to the problem modulo k. Examples Input 2 0 1000000000 Output 1 Input 3 0 100 Output 3 Input 4 1 1000000000 1 4 Output 8 Note The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link. The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it. The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime. Tags: combinatorics, graphs Correct Solution: ``` def dfs(node, my_cc): vis[node] = True acc[my_cc]+=1 for i in adj[node]: if not vis[i]: dfs(i, my_cc) def bfs(node): vis[node] = True cola = [node] cur = 0 while (cur < len(cola)): x = cola[cur] acc[cc] += 1 cur += 1; for i in adj[x]: if not vis[i]: vis[i] = True cola.append(i) if __name__ == '__main__': _input = input().split() n = int(_input[0]) m = int(_input[1]) k = int(_input[2]) adj = [] vis = [] acc = [] cc = 0 for i in range(n): vis.append(False) adj.append([]) acc.append(0) for i in range(m): _in2 = input().split() v = int(_in2[0]) - 1 w = int(_in2[1]) - 1 adj[v].append(w) adj[w].append(v) for i in range(n): if not vis[i]: # dfs(i, cc) bfs(i) cc+=1 if cc == 1: print(1 % k) exit() ans = 1 for i in range(cc - 2): ans = ans * n ans = ans % k for i in range(cc): ans = ans * acc[i] ans = ans % k print(ans) ```
3,635
Provide tags and a correct Python 3 solution for this coding contest problem. As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues. Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T. Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k. Input The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual. Output Print the single number — the answer to the problem modulo k. Examples Input 2 0 1000000000 Output 1 Input 3 0 100 Output 3 Input 4 1 1000000000 1 4 Output 8 Note The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link. The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it. The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime. Tags: combinatorics, graphs Correct Solution: ``` def dfs(node, my_cc): vis[node] = True acc[my_cc]+=1 for i in adj[node]: if not vis[i]: dfs(i, my_cc) def ittDfs(node): queue = [node] curr = 0 while(queue): node = queue.pop() if vis[node]: continue vis[node] = True acc[cc] += 1 for i in adj[node]: if not vis[i]: queue.append(i) def bfs(node): vis[node] = True cola = [node] cur = 0 while (cur < len(cola)): x = cola[cur] acc[cc] += 1 cur += 1; for i in adj[x]: if not vis[i]: vis[i] = True cola.append(i) if __name__ == '__main__': _input = input().split() n = int(_input[0]) m = int(_input[1]) k = int(_input[2]) adj = [] vis = [] acc = [] cc = 0 for i in range(n): vis.append(False) adj.append([]) acc.append(0) for i in range(m): _in2 = input().split() v = int(_in2[0]) - 1 w = int(_in2[1]) - 1 adj[v].append(w) adj[w].append(v) for i in range(n): if not vis[i]: # dfs(i, cc) ittDfs(i) cc+=1 if cc == 1: #print(1) print(1 % k) exit() ans = 1 for i in range(cc - 2): ans = (ans * n) % k #ans = ans % k for i in range(cc): ans = (ans * acc[i]) % k #ans = ans % k print(ans) ```
3,636
Provide tags and a correct Python 3 solution for this coding contest problem. As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues. Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T. Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k. Input The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual. Output Print the single number — the answer to the problem modulo k. Examples Input 2 0 1000000000 Output 1 Input 3 0 100 Output 3 Input 4 1 1000000000 1 4 Output 8 Note The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link. The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it. The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime. Tags: combinatorics, graphs Correct Solution: ``` def dfs(node, my_cc): vis[node] = True acc[my_cc]+=1 for i in adj[node]: if not vis[i]: dfs(i, my_cc) def ittDfs(node): queue = [node] curr = 0 while(queue): node = queue.pop() if vis[node]: continue vis[node] = True acc[cc] += 1 for i in adj[node]: if not vis[i]: queue.append(i) def bfs(node): vis[node] = True cola = [node] cur = 0 while (cur < len(cola)): x = cola[cur] acc[cc] += 1 cur += 1; for i in adj[x]: if not vis[i]: vis[i] = True cola.append(i) if __name__ == '__main__': _input = input().split() n = int(_input[0]) m = int(_input[1]) k = int(_input[2]) adj = [] vis = [] acc = [] cc = 0 for i in range(n): vis.append(False) adj.append([]) acc.append(0) for i in range(m): _in2 = input().split() v = int(_in2[0]) - 1 w = int(_in2[1]) - 1 adj[v].append(w) adj[w].append(v) for i in range(n): if not vis[i]: # dfs(i, cc) ittDfs(i) cc+=1 if cc == 1: print(1 % k) exit() ans = 1 for i in range(cc - 2): ans = ans * n ans = ans % k for i in range(cc): ans = ans * acc[i] ans = ans % k print(ans) ```
3,637
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues. Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T. Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k. Input The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual. Output Print the single number — the answer to the problem modulo k. Examples Input 2 0 1000000000 Output 1 Input 3 0 100 Output 3 Input 4 1 1000000000 1 4 Output 8 Note The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link. The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it. The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime. Submitted Solution: ``` n, m, k = map(int, input().split()) g = [[] for i in range(n)] for i in range(m): a, b = map(int, input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) visited = [False for i in range(n)] count = 0 def dfs(x): global count visited[x] = True count += 1 for y in g[x]: if not visited[y]: dfs(y) total_count = 1 for i in range(n): if not visited[i]: dfs(i) total_count = (total_count * count) % k count = 0 def fast_exp(n, x, k): if x == 1: return n % k if x == 0: return 1 % k else: sqrt = fast_exp(n, x // 2, k) ans = (sqrt * sqrt) % k if x % 2 != 0: ans = (ans * n) % k return ans #print("Total count is", total_count) if m == n - 1: print(1) else: result = (total_count * fast_exp(n, n - m - 2, k)) % k print(result) ``` No
3,638
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues. Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T. Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k. Input The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual. Output Print the single number — the answer to the problem modulo k. Examples Input 2 0 1000000000 Output 1 Input 3 0 100 Output 3 Input 4 1 1000000000 1 4 Output 8 Note The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link. The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it. The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime. Submitted Solution: ``` n, m, k = map(int, input().split()) g = [[] for i in range(n)] for i in range(m): a, b = map(int, input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) visited = [False for i in range(n)] count = 0 total_visited = 0 def dfs(x): global count visited[x] = True count += 1 for y in g[x]: if not visited[y]: dfs(y) total_count = 1 total_effective_edges = 0 for i in range(n): if not visited[i]: dfs(i) total_effective_edges += count - 1 total_count = (total_count * count) % k count = 0 def fast_exp(n, x, k): if x == 1: return n % k if x == 0: return 1 % k else: sqrt = fast_exp(n, x // 2, k) ans = (sqrt * sqrt) % k if x % 2 != 0: ans = (ans * n) % k return ans #print("Total count is", total_count) m = total_effective_edges if m == n - 1: print(1) else: result = (total_count * fast_exp(n, n - m - 2, k)) % k print(result) ``` No
3,639
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues. Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T. Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k. Input The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual. Output Print the single number — the answer to the problem modulo k. Examples Input 2 0 1000000000 Output 1 Input 3 0 100 Output 3 Input 4 1 1000000000 1 4 Output 8 Note The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link. The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it. The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime. Submitted Solution: ``` def dfs(node, my_cc): vis[node] = True acc[my_cc]+=1 for i in adj[node]: if not vis[i]: dfs(i, my_cc) def ittDfs(node): queue = [node] curr = 0 while(queue): node = queue.pop() vis[node] = True acc[cc] += 1 for i in adj[node]: if not vis[i]: queue.append(i) def bfs(node): vis[node] = True cola = [node] cur = 0 while (cur < len(cola)): x = cola[cur] acc[cc] += 1 cur += 1; for i in adj[x]: if not vis[i]: vis[i] = True cola.append(i) if __name__ == '__main__': _input = input().split() n = int(_input[0]) m = int(_input[1]) k = int(_input[2]) adj = [] vis = [] acc = [] cc = 0 for i in range(n): vis.append(False) adj.append([]) acc.append(0) for i in range(m): _in2 = input().split() v = int(_in2[0]) - 1 w = int(_in2[1]) - 1 adj[v].append(w) adj[w].append(v) for i in range(n): if not vis[i]: # dfs(i, cc) ittDfs(i) cc+=1 if cc == 1: print(1 % k) exit() ans = 1 for i in range(cc - 2): ans = ans * n ans = ans % k for i in range(cc): ans = ans * acc[i] ans = ans % k print(ans) ``` No
3,640
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues. Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T. Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k. Input The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation. Each of next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual. Output Print the single number — the answer to the problem modulo k. Examples Input 2 0 1000000000 Output 1 Input 3 0 100 Output 3 Input 4 1 1000000000 1 4 Output 8 Note The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link. The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it. The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime. Submitted Solution: ``` from collections import deque n, m, k = map(int, input().split()) g = [[] for i in range(n)] for i in range(m): a, b = map(int, input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) visited = [False for i in range(n)] count = 0 def bfs(x): global count q = deque([x]) while len(q) != 0: y = q.pop() if not visited[y]: count += 1 visited[y] = True for z in g[y]: q.appendleft(z) total_count = 1 total_effective_edges = 0 for i in range(n): if not visited[i]: bfs(i) total_effective_edges += count - 1 total_count = (total_count * count) % k count = 0 def fast_exp(n, x, k): if x == 1: return n % k if x == 0: return 1 % k else: sqrt = fast_exp(n, x // 2, k) ans = (sqrt * sqrt) % k if x % 2 != 0: ans = (ans * n) % k return ans #print("Total count is", total_count) m = total_effective_edges if n == 1: print(0 % k) elif m == n - 1: print(1 % k) else: result = (total_count * fast_exp(n, n - m - 2, k)) % k print(result) ``` No
3,641
Provide tags and a correct Python 3 solution for this coding contest problem. Fibonacci strings are defined as follows: * f1 = «a» * f2 = «b» * fn = fn - 1 fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba". You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring. Input The first line contains two space-separated integers k and m — the number of a Fibonacci string and the number of queries, correspondingly. Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b". The input limitations for getting 30 points are: * 1 ≤ k ≤ 3000 * 1 ≤ m ≤ 3000 * The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: * 1 ≤ k ≤ 1018 * 1 ≤ m ≤ 104 * The total length of strings si doesn't exceed 105 Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output For each string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input. Examples Input 6 5 a b ab ba aba Output 3 5 3 3 1 Tags: strings Correct Solution: ``` F = ['', 'a', 'b', 'ba', 'bab', 'babba', 'babbabab', 'babbababbabba', 'babbababbabbababbabab', 'babbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab'] d = 1000000007 def sqr(t): return [[sum(t[i][k] * t[k][j] for k in range(4)) % d for j in range(4)] for i in range(4)] def mul(a, b): return [[sum(a[i][k] * b[k][j] for k in range(4)) % d for j in range(4)] for i in range(4)] def fib(k): s, p = format(k, 'b')[:: -1], [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] t = [[[0, 1, 0, 0], [1, 1, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0]]] + [0] * (len(s) - 1) for i in range(1, len(s)): t[i] = sqr(t[i - 1]) for i, k in enumerate(s): if k == '1': p = mul(p, t[i]) return p def cnt(t, p): s, i = 0, p.find(t) + 1 while i > 0: i = p.find(t, i) + 1 s += 1 return s def f(t, p, k): l = len(t) - 1 if l: x, y = cnt(t, F[k - 1][- l: ] + F[k][:l ]), cnt(t, F[k][- l: ] + F[k + 1][:l ]) else: x, y = 0, 0 a, b = cnt(t, F[k - 1]), cnt(t, F[k]) return (p[0] * a + p[1] * b + p[2] * y + p[3] * x) % d k, m = map(int, input().split()) if k > 15: a, b = fib(k - 7)[0], fib(k - 18)[0] for i in range(m): t = input() if len(t) < len(F[7]): print(f(t, a, 8)) else: print(f(t, b, 19)) else: p = F[k] for i in range(m): print(cnt(input(), p)) ```
3,642
Provide tags and a correct Python 3 solution for this coding contest problem. Fibonacci strings are defined as follows: * f1 = «a» * f2 = «b» * fn = fn - 1 fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba". You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring. Input The first line contains two space-separated integers k and m — the number of a Fibonacci string and the number of queries, correspondingly. Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b". The input limitations for getting 30 points are: * 1 ≤ k ≤ 3000 * 1 ≤ m ≤ 3000 * The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: * 1 ≤ k ≤ 1018 * 1 ≤ m ≤ 104 * The total length of strings si doesn't exceed 105 Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output For each string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input. Examples Input 6 5 a b ab ba aba Output 3 5 3 3 1 Tags: strings Correct Solution: ``` F = ['', 'a', 'b', 'ba', 'bab', 'babba', 'babbabab', 'babbababbabba', 'babbababbabbababbabab', 'babbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab'] while len(F[-3]) < 100000: F.append(F[-1] + F[-2]) d = 1000000007 def sqr(t): return [[sum(t[i][k] * t[k][j] for k in range(4)) % d for j in range(4)] for i in range(4)] def mul(a, b): return [[sum(a[i][k] * b[k][j] for k in range(4)) % d for j in range(4)] for i in range(4)] def fib(k): s, p = format(k, 'b')[:: -1], [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] t = [[[0, 1, 0, 0], [1, 1, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0]]] + [0] * (len(s) - 1) for i in range(1, len(s)): t[i] = sqr(t[i - 1]) for i, k in enumerate(s): if k == '1': p = mul(p, t[i]) return p def cnt(t, p): s, i = 0, p.find(t) + 1 while i > 0: i = p.find(t, i) + 1 s += 1 return s def f(t, p, k): l = len(t) - 1 if l: x, y = cnt(t, F[k - 1][- l: ] + F[k][:l ]), cnt(t, F[k][- l: ] + F[k + 1][:l ]) else: x, y = 0, 0 a, b = cnt(t, F[k - 1]), cnt(t, F[k]) return (p[0] * a + p[1] * b + p[2] * y + p[3] * x) % d k, m = map(int, input().split()) if k > 15: x, y, z = len(F[7]), len(F[17]), len(F) - 4 a, b, c = fib(k - 7)[0], fib(k - 17)[0], fib(k - z)[0] for i in range(m): t = input() if len(t) < x: print(f(t, a, 8)) elif len(t) < y: print(f(t, b, 18)) else: print(f(t, c, z + 1)) else: p = F[k] for i in range(m): print(cnt(input(), p)) ```
3,643
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fibonacci strings are defined as follows: * f1 = «a» * f2 = «b» * fn = fn - 1 fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba". You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring. Input The first line contains two space-separated integers k and m — the number of a Fibonacci string and the number of queries, correspondingly. Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b". The input limitations for getting 30 points are: * 1 ≤ k ≤ 3000 * 1 ≤ m ≤ 3000 * The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: * 1 ≤ k ≤ 1018 * 1 ≤ m ≤ 104 * The total length of strings si doesn't exceed 105 Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output For each string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input. Examples Input 6 5 a b ab ba aba Output 3 5 3 3 1 Submitted Solution: ``` F = ['', 'a', 'b', 'ba', 'bab', 'babba', 'babbabab', 'babbababbabba', 'babbababbabbababbabab', 'babbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba'] d = 1000000007 def sqr(t): return [[sum(t[i][k] * t[k][j] for k in range(4)) % d for j in range(4)] for i in range(4)] def mul(a, b): return [[sum(a[i][k] * b[k][j] for k in range(4)) % d for j in range(4)] for i in range(4)] def fib(k): s, p = format(k, 'b')[:: -1], [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] t = [[[0, 1, 0, 0], [1, 1, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0]]] + [0] * (len(s) - 1) for i in range(1, len(s)): t[i] = sqr(t[i - 1]) for i, k in enumerate(s): if k == '1': p = mul(p, t[i]) return p def cnt(t, p): s, i = 0, p.find(t) + 1 while i > 0: i = p.find(t, i) + 1 s += 1 return s def f(t, p, k): l = len(t) - 1 if l: x, y = cnt(t, F[k - 1][- l: ] + F[k][:l ]), cnt(t, F[k][- l: ] + F[k + 1][:l ]) else: x, y = 0, 0 a, b = cnt(t, F[k - 1]), cnt(t, F[k]) return (p[0] * a + p[1] * b + p[2] * y + p[3] * x) % d k, m = map(int, input().split()) if k > 8: p = fib(k - 7)[0] for i in range(m): print(f(input(), p, 8)) else: p = F[k] for i in range(m): print(cnt(input(), p)) ``` No
3,644
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fibonacci strings are defined as follows: * f1 = «a» * f2 = «b» * fn = fn - 1 fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba". You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring. Input The first line contains two space-separated integers k and m — the number of a Fibonacci string and the number of queries, correspondingly. Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b". The input limitations for getting 30 points are: * 1 ≤ k ≤ 3000 * 1 ≤ m ≤ 3000 * The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: * 1 ≤ k ≤ 1018 * 1 ≤ m ≤ 104 * The total length of strings si doesn't exceed 105 Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output For each string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input. Examples Input 6 5 a b ab ba aba Output 3 5 3 3 1 Submitted Solution: ``` used = {1 : 'a', 2 : 'b'} def fibo(n): if n in used: return used[n] else: used[n] = fibo(n-1) + fibo(n-2) return used[n] k, m = map(int, input().split()) fib = fibo(k) for _ in range(m): print(fib.count(input()) % 1000000007) ``` No
3,645
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fibonacci strings are defined as follows: * f1 = «a» * f2 = «b» * fn = fn - 1 fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba". You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring. Input The first line contains two space-separated integers k and m — the number of a Fibonacci string and the number of queries, correspondingly. Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b". The input limitations for getting 30 points are: * 1 ≤ k ≤ 3000 * 1 ≤ m ≤ 3000 * The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: * 1 ≤ k ≤ 1018 * 1 ≤ m ≤ 104 * The total length of strings si doesn't exceed 105 Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output For each string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input. Examples Input 6 5 a b ab ba aba Output 3 5 3 3 1 Submitted Solution: ``` p=input().rstrip().split(' ') A=int(p[0]) a='b' b='a' if A>2: a='b' b='a'; for i in range(2,A): c=a+b; b=a; a=c; if A==1: C=list(a) elif A==2: C=list(b) else: C=list(c) for i in range(0,int(p[1])): s=input().rstrip() t=len(s) if t>len(C): print(0%1000000007) elif t==len(C): if s==''.join(C): print(1) else: print(0%1000000007) else: V=0; for j in range(0,len(C)-t+1): G=C[j:j+t] if ''.join(G)==s: V+=1; print(V%1000000007) ``` No
3,646
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fibonacci strings are defined as follows: * f1 = «a» * f2 = «b» * fn = fn - 1 fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba". You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring. Input The first line contains two space-separated integers k and m — the number of a Fibonacci string and the number of queries, correspondingly. Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b". The input limitations for getting 30 points are: * 1 ≤ k ≤ 3000 * 1 ≤ m ≤ 3000 * The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: * 1 ≤ k ≤ 1018 * 1 ≤ m ≤ 104 * The total length of strings si doesn't exceed 105 Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier. Output For each string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input. Examples Input 6 5 a b ab ba aba Output 3 5 3 3 1 Submitted Solution: ``` s=input() a,b=map(int,s.split(' ')) f={1:'a',2:'b'} for n in range(3,a+1): g=f[n-1]+f[n-2] f.update({n:g}) fn=str(f[a]) if 1<=a<=3000 and 1<=b<=3000 and len(fn)<=3000: pass else: raise SystemExit gg={} for i in range(1,b+1): hh=input() gg.update({i:hh}) for z in range(1,b+1): mm=str(gg[z]) print(fn.count(mm)) ``` No
3,647
Provide tags and a correct Python 3 solution for this coding contest problem. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Tags: data structures, expression parsing, implementation Correct Solution: ``` s, st, v, vi, vj, vc = input(), [], [], 0, 0, 0 for i, ch in enumerate(s): if ch in '[(': st.append(i) else: if st and s[st[-1]] + ch in ('()', '[]'): b = (st[-1], i + 1) if v and v[-1][1] == i: v[-1] = b else: v.append(b) if len(v) >= 2 and v[-2][1] == v[-1][0]: v[-2:] = [(v[-2][0], v[-1][1])] st.pop() else: st = [] for b in v: c = s.count('[', b[0], b[1]) if c > vc: vi, vj, vc = b[0], b[1], c print(vc) print(s[vi:vj]) ```
3,648
Provide tags and a correct Python 3 solution for this coding contest problem. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Tags: data structures, expression parsing, implementation Correct Solution: ``` string = list(input()) d, p = [], set(range(len(string))) for j, q in enumerate(string): if q in '([': d.append((j,q)) elif d: i, x = d.pop() if x+q in '(][)': d = [] else: p -= {i, j} n, s = 0, '' for i in p: string[i] = ' ' for k in "".join(string).split(): if k.count("[") > n: n = k.count("[") s = k print(n, s) ```
3,649
Provide tags and a correct Python 3 solution for this coding contest problem. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Tags: data structures, expression parsing, implementation Correct Solution: ``` import sys import math import string import operator import functools import fractions import collections sys.setrecursionlimit(10**7) dX= [-1, 1, 0, 0,-1, 1,-1, 1] dY= [ 0, 0,-1, 1, 1,-1,-1, 1] RI=lambda: list(map(int,input().split())) RS=lambda: input().rstrip().split() ################################################# s=RS()[0] st=[] closeInd=[0]*len(s) def rev(c): return "(["[c==']'] for i in range(len(s)): if len(st) and s[i] in ")]" and st[-1][0]==rev(s[i]): temp=st[-1] st.pop() closeInd[temp[1]]=i else: st.append((s[i],i)) maxSq=0 maxX,maxY=0,0 i=0 while i<len(s): sq=0 start=i while i<len(s) and closeInd[i]: j=i while i<=closeInd[j]: if s[i]=='[': sq+=1 i+=1 else: i+=1 if sq>maxSq: maxSq=sq maxX=start maxY=i-1 print(maxSq, s[maxX:maxY], sep='\n') ```
3,650
Provide tags and a correct Python 3 solution for this coding contest problem. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Tags: data structures, expression parsing, implementation Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() s = ri() sta = [] l,r = -1,-2 lis = [] for i in range(len(s)): if s[i] == '(': sta.append(['(', i]) elif s[i] == '[': sta.append(['[', i]) elif s[i] == ')': if len(sta) == 0 or sta[-1][0] != '(': sta = [] else: temp = sta.pop() lis.append([temp[1], i]) elif s[i] == ']': if len(sta) == 0 or sta[-1][0] != '[': sta = [] else: temp = sta.pop() lis.append([temp[1], i]) lis.sort(key = lambda x : (x[0], -x[1])) cur = [] totcnt =0 cnt = 0 # print(lis) for i in range(len(lis)): if len(cur) == 0: cur = lis[i][:] if s[lis[i][0]] == '[': cnt+=1 elif cur[0] <= lis[i][0] and lis[i][1] <= cur[1]: if s[lis[i][0]] == '[': cnt+=1 else: if lis[i][0] == cur[1]+1: cur[1] = lis[i][1] if s[lis[i][0]] == '[': cnt+=1 else: if cnt > totcnt: l,r = cur[0],cur[1] totcnt = cnt cur = lis[i][:] cnt = 0 if s[lis[i][0]] == '[': cnt+=1 if cnt > totcnt: l,r = cur[0],cur[1] if l == -1: print(0) else: cnt =0 for i in range(l, r+1): if s[i] == '[': cnt+=1 print(cnt) print(s[l:r+1]) ```
3,651
Provide tags and a correct Python 3 solution for this coding contest problem. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Tags: data structures, expression parsing, implementation Correct Solution: ``` s = input() st, v, vi, vj, vc = [], [], 0, 0, 0 for i, c in enumerate(s): if c in '[(': st.append(i) continue if st and s[st[-1]] + c in ('()', '[]'): b = (st[-1], i+1) if v and v[-1][1] == i: v[-1] = b else: v.append(b) if len(v) >= 2 and v[-2][1] == v[-1][0]: v[-2:] = [(v[-2][0], v[-1][1])] st.pop() else: st = [] for b in v: c = s.count('[', b[0], b[1]) if c > vc: vi, vj, vc = b[0], b[1], c print(vc) print(s[vi:vj]) ```
3,652
Provide tags and a correct Python 3 solution for this coding contest problem. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Tags: data structures, expression parsing, implementation Correct Solution: ``` s = input() a = [] for i in range(len(s)): if len(a) != 0 and ((s[a[-1]] == '(' and s[i] == ')') or (s[a[-1]] == '[' and s[i] == ']')): a.pop() else: a.append(i) if len(a) == 0: print(s.count('[')) print(s) else: s1 = s[0: a[0]] le = s[0: a[0]].count('[') for i in range(len(a) - 1): le1 = s[a[i] + 1: a[i + 1]].count('[') if le1 > le: s1 = s[a[i] + 1: a[i + 1]] le = le1 le1 = s[a[-1] + 1:].count('[') if le1 > le: s1 = s[a[-1] + 1:] le = le1 print(le) print(s1) ```
3,653
Provide tags and a correct Python 3 solution for this coding contest problem. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Tags: data structures, expression parsing, implementation Correct Solution: ``` s=list(input()) st=[] a=[0]*len(s) for i in range(len(s)): if s[i]==']': if len(st)>0 and st[-1][0]=='[': a[st[-1][1]]=i st.pop() else: st=[] elif s[i]==')': if len(st)>0 and st[-1][0]=='(': a[st[-1][1]]=i st.pop() else: st=[] else: st.append([s[i],i]) mans=0 ml=0 mr=0 def kkk(s,l,r): ans=0 for i in range(l,r+1): if s[i]=='[': ans+=1 return ans i=0 while i<len(s): while i<len(s) and a[i]==0: i+=1 if i<len(s): l=i r=a[i] while r+1<len(s) and a[r+1]>0: r=a[r+1] t=kkk(s,l,r) if t>mans: mans=t ml=l mr=r i=r+1 print(mans) if mans>0: for i in range(ml,mr+1): print(s[i],end='') ```
3,654
Provide tags and a correct Python 3 solution for this coding contest problem. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Tags: data structures, expression parsing, implementation Correct Solution: ``` import sys from math import gcd,sqrt,ceil,log2 from collections import defaultdict,Counter,deque from bisect import bisect_left,bisect_right import math import heapq from itertools import permutations # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # import sys # import io, os # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def get_sum(bit,i): s = 0 i+=1 while i>0: s+=bit[i] i-=i&(-i) return s def update(bit,n,i,v): i+=1 while i<=n: bit[i]+=v i+=i&(-i) def modInverse(b,m): g = math.gcd(b, m) if (g != 1): return -1 else: return pow(b, m - 2, m) def primeFactors(n): sa = set() sa.add(n) while n % 2 == 0: sa.add(2) n = n // 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: sa.add(i) n = n // i # sa.add(n) return sa def seive(n): pri = [True]*(n+1) p = 2 while p*p<=n: if pri[p] == True: for i in range(p*p,n+1,p): pri[i] = False p+=1 return pri def check_prim(n): if n<0: return False for i in range(2,int(sqrt(n))+1): if n%i == 0: return False return True def getZarr(string, z): n = len(string) # [L,R] make a window which matches # with prefix of s l, r, k = 0, 0, 0 for i in range(1, n): # if i>R nothing matches so we will calculate. # Z[i] using naive way. if i > r: l, r = i, i # R-L = 0 in starting, so it will start # checking from 0'th index. For example, # for "ababab" and i = 1, the value of R # remains 0 and Z[i] becomes 0. For string # "aaaaaa" and i = 1, Z[i] and R become 5 while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 else: # k = i-L so k corresponds to number which # matches in [L,R] interval. k = i - l # if Z[k] is less than remaining interval # then Z[i] will be equal to Z[k]. # For example, str = "ababab", i = 3, R = 5 # and L = 2 if z[k] < r - i + 1: z[i] = z[k] # For example str = "aaaaaa" and i = 2, # R is 5, L is 0 else: # else start from R and check manually l = i while r < n and string[r - l] == string[r]: r += 1 z[i] = r - l r -= 1 def search(text, pattern): # Create concatenated string "P$T" concat = pattern + "$" + text l = len(concat) z = [0] * l getZarr(concat, z) ha = [] for i in range(l): if z[i] == len(pattern): ha.append(i - len(pattern) - 1) return ha # n,k = map(int,input().split()) # l = list(map(int,input().split())) # # n = int(input()) # l = list(map(int,input().split())) # # hash = defaultdict(list) # la = [] # # for i in range(n): # la.append([l[i],i+1]) # # la.sort(key = lambda x: (x[0],-x[1])) # ans = [] # r = n # flag = 0 # lo = [] # ha = [i for i in range(n,0,-1)] # yo = [] # for a,b in la: # # if a == 1: # ans.append([r,b]) # # hash[(1,1)].append([b,r]) # lo.append((r,b)) # ha.pop(0) # yo.append([r,b]) # r-=1 # # elif a == 2: # # print(yo,lo) # # print(hash[1,1]) # if lo == []: # flag = 1 # break # c,d = lo.pop(0) # yo.pop(0) # if b>=d: # flag = 1 # break # ans.append([c,b]) # yo.append([c,b]) # # # # elif a == 3: # # if yo == []: # flag = 1 # break # c,d = yo.pop(0) # if b>=d: # flag = 1 # break # if ha == []: # flag = 1 # break # # ka = ha.pop(0) # # ans.append([ka,b]) # ans.append([ka,d]) # yo.append([ka,b]) # # if flag: # print(-1) # else: # print(len(ans)) # for a,b in ans: # print(a,b) def mergeIntervals(arr): # Sorting based on the increasing order # of the start intervals arr.sort(key = lambda x: x[0]) # array to hold the merged intervals m = [] s = -10000 max = -100000 for i in range(len(arr)): a = arr[i] if a[0] > max: if i != 0: m.append([s,max]) max = a[1] s = a[0] else: if a[1] >= max: max = a[1] #'max' value gives the last point of # that particular interval # 's' gives the starting point of that interval # 'm' array contains the list of all merged intervals if max != -100000 and [s, max] not in m: m.append([s, max]) return m s = input() n = len(s) stack = [] i = 0 ans = [] pre = [0] for i in s: if i == '[': pre.append(pre[-1]+1) else: pre.append(pre[-1]) i = 0 while i<n: if s[i] == '(' or s[i] == '[': stack.append(i) elif stack!=[] and s[i] == ')' and s[stack[-1]] == '(': z = stack.pop() ans.append((z,i)) elif stack!=[] and s[i] == ')' and s[stack[-1]] == '[': stack = [] elif stack!=[] and s[i] == ']' and s[stack[-1]] == '[': z = stack.pop() ans.append((z,i)) elif stack!=[] and s[i] == ']' and s[stack[-1]] == '(': stack = [] i+=1 ans.sort() x,y = -1,-1 maxi = 0 lo = [] i = 1 # print(ans) ans = mergeIntervals(ans) if ans == []: print(0) print() exit() a,b = ans[i-1] lo.append([a,b]) # print(ans) while i<=len(ans): a,b = ans[i-1] while i<len(ans) and ans[i][0]-ans[i-1][1] == 1: i+=1 lo.append([a,ans[i-1][1]]) i+=1 ans = lo # print(lo) for i in range(len(ans)): a,b = ans[i] a+=1 b+=1 z = pre[b] - pre[a-1] if z>maxi: maxi = z a-=1 b-=1 x,y = a,b if ans == []: print(0) print() else: print(maxi) print(s[x:y+1]) ```
3,655
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() s = ri() sta1 = [];sta2 = [] least = -1 l,r = -1,-2 for i in range(len(s)): if s[i] == '(': sta1.append(['(', i]) elif s[i] == '[': sta2.append(['[', i]) if least == -1: least = i elif s[i] == ')': if len(sta1) == 0: sta1 = [] # if flag : sta2 = [] least = -1 else: sta1.pop() elif s[i] == ']': if len(sta2) == 0 or sta2[-1][0] != '[': sta2 = [] sta1 = [] else: if len(sta2) == 1: temp = sta2.pop() tl,tr = least, i if l == -1: l,r = tl,tr if tr - tl +1 > r - l +1: l,r= tl,tr else: temp = sta2.pop() tl,tr = temp[1], i if l == -1: l,r = tl,tr if tr - tl +1 > r - l +1: l,r= tl,tr if l == -1: print(0) else: cnt =0 for i in range(l, r+1): if s[i] == '[': cnt+=1 print(cnt) print(s[l:r+1]) ``` No
3,656
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Submitted Solution: ``` s=list(input()) st=[] a=[0]*len(s) for i in range(len(s)): if s[i]==']': if len(st)>0 and st[-1][0]=='[': a[st[-1][1]]=i else: st=[] elif s[i]==')': if len(st)>0 and st[-1][0]=='(': a[st[-1][1]]=i else: st=[] else: st.append([s[i],i]) mans=0 ml=0 mr=0 def kkk(s,l,r): ans=0 for i in range(l,r+1): if s[i]=='[': ans+=1 return ans i=0 while i<len(s): while i<len(s) and a[i]==0: i+=1 if i<len(s): l=i r=a[i] while r+1<len(s) and a[r+1]>0: r=a[r+1] t=kkk(s,l,r) if t>mans: mans=t ml=l mr=r i=r+1 print(mans) if mans>0: for i in range(ml,mr+1): print(s[i],end='') ``` No
3,657
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() s = ri() sta = [] l,r = -1,-2 for i in range(len(s)): if s[i] == '(': sta.append(['(', i]) elif s[i] == '[': sta.append(['[', i]) elif s[i] == ')': if len(sta) == 0 or sta[-1][0] != '(': sta = [] else: sta.pop() elif s[i] == ']': if len(sta) == 0 or sta[-1][0] != '[': sta = [] else: temp = sta.pop() tl,tr = temp[1], i if l == -1: l,r = tl,tr if tr - tl +1 > r - l +1: l,r= tl,tr if l == -1: print(0) else: cnt =0 for i in range(l, r+1): if s[i] == '[': cnt+=1 print(cnt) print(s[l:r+1]) ``` No
3,658
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A bracket sequence is a string, containing only characters "(", ")", "[" and "]". A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition. A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition. You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible. Input The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters. Output In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them. Examples Input ([]) Output 1 ([]) Input ((( Output 0 Submitted Solution: ``` s=list(input()) st=[] a=[0]*len(s) ans=0 for i in range(len(s)): if s[i]==']': if len(st)==0: pass else: ans+=1 a[i]=1 a[st[-1]]=1 st.pop() elif s[i]=='[': st.append(i) print(ans) for i in range(len(s)): if a[i]==1: print(s[i],end='') ``` No
3,659
Provide tags and a correct Python 3 solution for this coding contest problem. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Tags: brute force, dfs and similar, graphs Correct Solution: ``` """ Satwik_Tiwari ;) . 21st AUGUST , 2020 - FRIDAY """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from itertools import * import bisect from heapq import * from math import * from copy import * from collections import deque from collections import Counter as counter # Counter(list) return a dict with {key: count} from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)] from itertools import permutations as permutate from bisect import bisect_left as bl #If the element is already present in the list, # the left most position where element has to be inserted is returned. from bisect import bisect_right as br from bisect import bisect #If the element is already present in the list, # the right most position where element has to be inserted is returned #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts mod = 1000000007 def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def zerolist(n): return [0]*n def nextline(): out("\n") #as stdout.write always print sring. def testcase(t): for p in range(t): solve() def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True #=============================================================================================== # code here ;)) def solve(): n,m = sep() c = lis() g = [[] for i in range(n)] for i in range(m): a,b = sep() a-=1 b-=1 g[a].append(b) g[b].append(a) cnt = [ {} for i in range(100005)] for i in range(n): for j in g[i]: if(c[j] not in cnt[c[i]] and c[j] != c[i]): cnt[c[i]][c[j]] = 1 ans = -1 col = 0 for i in range(100005): if(len(cnt[i])==0): continue if(len(cnt[i])>ans): col = i ans = len(cnt[i]) if(ans == -1): col = min(c) print(col) testcase(1) # testcase(int(inp())) ```
3,660
Provide tags and a correct Python 3 solution for this coding contest problem. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Tags: brute force, dfs and similar, graphs Correct Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase from math import inf def main(): n,m=map(int,input().split()) c=[-1]+list(map(int,input().split())) k=max(c)+1 graph=[[] for _ in range(n+1)] for _ in range(m): a,b=map(int,input().split()) graph[a].append(b) graph[b].append(a) visited=[0]*(n+1) color=[ set() for _ in range(k)] for i in range(1,n+1): if visited[i]: continue stack=[i] while stack: # print(stack) z=stack.pop() cc=c[z] if visited[z]: continue visited[z]=1 for item in graph[z]: if not visited[item]: stack.append(item) if c[item]==cc: continue color[cc].add(c[item]) color[c[item]].add(cc) # print(color) mx=0 ans=-1 for i in range(1,k): t=len(color[i]) if t>mx: mx=t ans=i # elif t==mx: # ans=min(ans,c[i]) if ans==-1: ans=min(c[1:]) print(ans) # 3 1 # 13 13 4 # 1 2 # 8 8 # 3 3 2 3 3 3 1 3 # 8 2 # 6 3 # 2 3 # 2 6 # 5 6 # 4 2 # 7 5 # 1 6 # 6 5 # 2 2 2 1 2 2 # 4 5 # 4 2 # 5 2 # 4 1 # 2 3 # 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') # endregion if __name__ == '__main__': main() ```
3,661
Provide tags and a correct Python 3 solution for this coding contest problem. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Tags: brute force, dfs and similar, graphs Correct Solution: ``` from sys import stdin from collections import * def arr_inp(n): if n == 1: return [int(x) for x in stdin.readline().split()] elif n == 2: return [float(x) for x in stdin.readline().split()] else: return list(stdin.readline()[:-1]) def main(): n, m = arr_inp(1) c, ans, ma = arr_inp(1), float('inf'), 0 mem = defaultdict(set) for i in range(m): u, v = arr_inp(1) u -= 1 v -= 1 if c[u] != c[v]: mem[c[u]].add(c[v]) mem[c[v]].add(c[u]) for i, j in mem.items(): if len(j) > ma: ma = max(ma, len(j)) ans = i if len(j) == ma: ans = min(ans, i) print(ans if ans != float('inf') else min(c)) if __name__ == '__main__': main() ```
3,662
Provide tags and a correct Python 3 solution for this coding contest problem. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Tags: brute force, dfs and similar, graphs Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ########################################################## from collections import Counter # c=sorted((i,int(val))for i,val in enumerate(input().split())) import heapq # c=sorted((i,int(val))for i,val in enumerate(input().split())) # n = int(input()) # ls = list(map(int, input().split())) # n, k = map(int, input().split()) # n =int(input()) #arr=[(i,x) for i,x in enum] #arr.sort(key=lambda x:x[0]) #print(arr) import math # e=list(map(int, input().split())) from collections import Counter #print("\n".join(ls)) #print(os.path.commonprefix(ls[0:2])) #n=int(input()) from bisect import bisect_right #n=int(input()) n, k = map(int, input().split()) arr=list(map(int, input().split())) d={x:set() for x in arr} for i in range(k): u,v= map(int, input().split()) if arr[u-1]!=arr[v-1]: d[arr[u-1]].add(arr[v-1]) d[arr[v - 1]].add(arr[u - 1]) d=sorted(d,key=lambda x:(len(d[x]),-x)) print(d[-1]) ```
3,663
Provide tags and a correct Python 3 solution for this coding contest problem. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Tags: brute force, dfs and similar, graphs Correct Solution: ``` from sys import stdin def main(): n, m = map(int, input().split()) cc = [0, *map(int, input().split())] d, f = {c: set() for c in cc}, cc.__getitem__ for s in stdin.read().splitlines(): u, v = map(f, map(int, s.split())) d[u].add(v) d[v].add(u) print(max(cc[1:], key=lambda c: (len(d[c]) - (c in d[c]), -c))) if __name__ == '__main__': main() ```
3,664
Provide tags and a correct Python 3 solution for this coding contest problem. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Tags: brute force, dfs and similar, graphs Correct Solution: ``` from collections import defaultdict n, m = map(int, input().split()) c = list(map(int, input().split())) res = defaultdict(set) for _ in range(m): u, v = map(lambda x: int(x) - 1, input().split()) if c[u] != c[v]: res[c[u]].add(c[v]) res[c[v]].add(c[u]) res_count = -1 res_color = -1 for color in c: count = res[color] if res_count == -1 or res_count < len(count): res_count = len(count) res_color = color elif res_count == len(count) and color < res_color: res_color = color print(res_color) ```
3,665
Provide tags and a correct Python 3 solution for this coding contest problem. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Tags: brute force, dfs and similar, graphs Correct Solution: ``` n, m = map(int, input().split()) c = list(map(int, input().split())) M =max(c) g= [set() for _ in range(M+1)] for _ in range(m): a, b = map(int, input().split()) a -=1 b -= 1 if c[a] != c[b]: g[c[a]].add(c[b]) g[c[b]].add(c[a]) ans = min(c) for i in range(M+1): if len(g[i]) > len(g[ans]): ans = i print(ans) ```
3,666
Provide tags and a correct Python 3 solution for this coding contest problem. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Tags: brute force, dfs and similar, graphs Correct Solution: ``` from collections import defaultdict from sys import stdin input = stdin.readline class N: def __init__(self, c) -> None: self.c = c self.ch = [] if __name__ == '__main__': n, m = map(int, input().split()) carr = list(map(int, input().split())) arr = [N(x) for x in carr] for _ in range(m): a, b = map(int, input().split()) arr[a - 1].ch.append(arr[b - 1]) arr[b - 1].ch.append(arr[a - 1]) for x in arr: x.ch = list(filter(lambda y: y.c != x.c, x.ch)) dct = defaultdict(lambda: set()) for x in arr: for y in x.ch: if y.c != x.c: dct[x.c].add(y.c) narr = [] for key, value in dct.items(): narr.append((key, len(value))) narr.sort(key=lambda x: x[1], reverse=True) if narr: narr = list(sorted(filter(lambda x: x[1] == narr[0][1], narr), key=lambda x: x[0])) print(narr[0][0]) else: print(min(carr)) ```
3,667
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Submitted Solution: ``` __autor__ = 'Esfandiar' import sys input=sys.stdin.readline from collections import defaultdict n,m = map(int,input().split()) c = list(map(int,input().split())) g = [[] for _ in range(n)] for i in range(m): u,v = map(int,input().split()) g[u-1].append(v-1) g[v-1].append(u-1) color = defaultdict(list) for u in range(n): color[c[u]].append(u) M = -float('inf') for k in color.keys(): seen = dict() res=0 for v in color[k]: for u in g[v]: if c[u] != k and seen.get(c[u],-1)==-1: res+=1 seen[c[u]]=1 if res > M: M=res kk=k elif res == M: kk=min(kk,k) print(kk) ''' 8 8 3 3 2 3 3 3 1 3 8 2 6 3 2 3 2 6 5 6 4 2 7 5 1 6 ''' ``` Yes
3,668
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Submitted Solution: ``` n,m = list(map(int,input().strip().split())) color = list(map(int,input().strip().split())) g = [[] for i in range(n)] colors = {i:set() for i in sorted(color)} for i in range(m): u,v =list(map(int,input().strip().split())) u -= 1 v -= 1 if color[u] != color[v]: colors[color[u]].add(color[v]) colors[color[v]].add(color[u]) print(max(colors,key = lambda x : len(colors[x]))) ``` Yes
3,669
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Submitted Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] try: # sys.setrecursionlimit(int(pow(10,4))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass def pmat(A): for ele in A: print(*ele,end="\n") # def seive(): # prime=[1 for i in range(10**6+1)] # prime[0]=0 # prime[1]=0 # for i in range(10**6+1): # if(prime[i]): # for j in range(2*i,10**6+1,i): # prime[j]=0 # return prime n,m=L() A=L() d={} for ele in A: d[ele]=set() for i in range(m): x,y=L() x=A[x-1] y=A[y-1] if x==y: continue d[x].add(y) d[y].add(x) z=sorted(list(d.keys())) mx=-1 idx=0 for ele in z: if len(d[ele])>mx: mx=len(d[ele]) idx=ele print(idx) endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ``` Yes
3,670
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Submitted Solution: ``` """ Satwik_Tiwari ;) . 21st AUGUST , 2020 - FRIDAY """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from itertools import * import bisect from heapq import * from math import * from copy import * from collections import deque from collections import Counter as counter # Counter(list) return a dict with {key: count} from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)] from itertools import permutations as permutate from bisect import bisect_left as bl #If the element is already present in the list, # the left most position where element has to be inserted is returned. from bisect import bisect_right as br from bisect import bisect #If the element is already present in the list, # the right most position where element has to be inserted is returned #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts mod = 1000000007 def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def zerolist(n): return [0]*n def nextline(): out("\n") #as stdout.write always print sring. def testcase(t): for p in range(t): solve() def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True #=============================================================================================== # code here ;)) def solve(): n,m = sep() c = lis() g = [[] for i in range(n)] for i in range(m): a,b = sep() a-=1 b-=1 g[a].append(b) g[b].append(a) cnt = [ {-1} for i in range(100005)] for i in range(n): for j in g[i]: if(c[j] != c[i]): cnt[c[i]].add(c[j]) ans = -1 col = 0 have = list(set(c)) have = sorted(have) for i in have: # print(cnt[i],i) if(len(cnt[i])==1): continue if(len(cnt[i])-1 > ans): col = i ans = len(cnt[i])-1 if(ans == -1): col = min(c) print(col) testcase(1) # testcase(int(inp())) ``` Yes
3,671
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Submitted Solution: ``` from sys import stdin input=stdin.readline n,m=map(int,input().split()) c=list(map(int,input().split())) g=[[] for i in range(n)] g_color=[set() for i in range(n)] for _ in range(m): u,v=map(int,input().split()) g[u-1].append(v-1) g[v-1].append(u-1) g_color[u-1].add(c[v-1]) g_color[v-1].add(c[u-1]) q=[set() for i in range(10**5+1)] for i in range(n): q[c[i]]=q[c[i]]|g_color[i] ans=0 M=0 for i in range(10**5+1): val=len(list(q[i])) if i in q[i]: val-=1 if M<val: ans=i M=val print(ans) ``` No
3,672
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Submitted Solution: ``` # import itertools import bisect import math from collections import defaultdict import os import sys from io import BytesIO, IOBase # sys.setrecursionlimit(10 ** 5) ii = lambda: int(input()) lmii = lambda: list(map(int, input().split())) slmii = lambda: sorted(map(int, input().split())) li = lambda: list(input()) mii = lambda: map(int, input().split()) msi = lambda: map(str, input().split()) def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b): return (a * b) // gcd(a, b) def main(): # for _ in " " * int(input()): n, m = mii() c = lmii() s = defaultdict(set) for i in range(m): a, b = mii() if c[a-1] != c[b - 1]: s[c[a-1]].add(c[b-1]) s[c[b-1]].add(c[a-1]) mx = -1 ans = -1 for i in s: ln = len(s[i]) if ln > mx: ans = i mx = ln if ln == mx: ans = min(ans, i) print(ans) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ``` No
3,673
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Submitted Solution: ``` import sys input = sys.stdin.readline n, m = map(int, input().split()) colours, colours_graph = set([int(i) for i in input().split()]), {i + 1: [] for i in range(n)} for i in range(m): a, b = map(int, input().split()) if a in colours and b in colours: colours_graph[a].append(b) colours_graph[b].append(a) print(max([len(colours_graph[colour]) for colour in colours_graph]) + 1) print(colours_graph) ``` No
3,674
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci. Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu : cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}. Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color. Input The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges. Output Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color. Examples Input 6 6 1 1 2 3 5 8 1 2 3 2 1 4 4 3 4 5 4 6 Output 3 Input 5 6 4 2 5 2 4 1 2 2 3 3 1 5 3 5 4 3 4 Output 2 Submitted Solution: ``` # import io, os # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys # sys.stdin=open('input.txt','r') # sys.stdout=open('output.txt','w') input=sys.stdin.readline # sys.setrecursionlimit(300010) MOD = 1000000007 MOD2 = 998244353 ii = lambda: int(input().strip('\n')) si = lambda: input().strip('\n') dgl = lambda: list(map(int,input().strip('\n'))) f = lambda: map(int, input().strip('\n').split()) il = lambda: list(map(int, input().strip('\n').split())) ls = lambda: list(input().strip('\n')) lsi = lambda: [int(i) for i in ls()] let = 'abcdefghijklmnopqrstuvwxyz' for _ in range(1): n,edg=f() colr=[0]+il() gph=[[] for i in range(n+1)] for i in range(edg): x,y=f() gph[x].append(y) gph[y].append(x) mx=0 mxc=colr[1] for i in range(1,n+1): s=set() for j in gph[i]: if colr[j]!=colr[i]: s.add(colr[j]) if len(s)>mx: mx=len(s) mxc=colr[i] elif len(s)==mx: mxc=min(mxc,colr[i]) print(mx,len(s),mxc) print(mxc) ``` No
3,675
Provide tags and a correct Python 3 solution for this coding contest problem. There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a, b). Each of the three horses can paint the special cards. If you show an (a, b) card to the gray horse, then the horse can paint a new (a + 1, b + 1) card. If you show an (a, b) card, such that a and b are even integers, to the white horse, then the horse can paint a new <image> card. If you show two cards (a, b) and (b, c) to the gray-and-white horse, then he can paint a new (a, c) card. Polycarpus really wants to get n special cards (1, a1), (1, a2), ..., (1, an). For that he is going to the horse land. He can take exactly one (x, y) card to the horse land, such that 1 ≤ x < y ≤ m. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards? Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires. Input The first line contains two integers n, m (1 ≤ n ≤ 105, 2 ≤ m ≤ 109). The second line contains the sequence of integers a1, a2, ..., an (2 ≤ ai ≤ 109). Note, that the numbers in the sequence can coincide. The numbers in the lines are separated by single spaces. Output Print a single integer — the answer to the problem. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 1 6 2 Output 11 Input 1 6 7 Output 14 Input 2 10 13 7 Output 36 Tags: constructive algorithms, math, number theory Correct Solution: ``` # written with help of editorial n, m = map(int, input().split()) a = list(map(int, input().split())) def gcd(x, y): while y: x, y = y, x % y return x g = 0 for x in a: g = gcd(g, x - 1) answer = 0 def process(x): global answer if x % 2 == 0: return 0 for i in range(30): v = 2 ** i * x if v > m: break answer += m - v for i in range(1, g + 1): if i * i > g: break if g % i: continue process(i) if i * i != g: process(g // i) print(answer) ```
3,676
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a, b). Each of the three horses can paint the special cards. If you show an (a, b) card to the gray horse, then the horse can paint a new (a + 1, b + 1) card. If you show an (a, b) card, such that a and b are even integers, to the white horse, then the horse can paint a new <image> card. If you show two cards (a, b) and (b, c) to the gray-and-white horse, then he can paint a new (a, c) card. Polycarpus really wants to get n special cards (1, a1), (1, a2), ..., (1, an). For that he is going to the horse land. He can take exactly one (x, y) card to the horse land, such that 1 ≤ x < y ≤ m. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards? Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires. Input The first line contains two integers n, m (1 ≤ n ≤ 105, 2 ≤ m ≤ 109). The second line contains the sequence of integers a1, a2, ..., an (2 ≤ ai ≤ 109). Note, that the numbers in the sequence can coincide. The numbers in the lines are separated by single spaces. Output Print a single integer — the answer to the problem. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 1 6 2 Output 11 Input 1 6 7 Output 14 Input 2 10 13 7 Output 36 Submitted Solution: ``` n, m = map(int, input().split()) a = list(map(int, input().split())) def is_special(x): return (x % 4 == 2 and (x // 4) % 4 <= 1) or (x % 4 == 0 and (x // 4) % 4 > 1) def series(y): ret = [] while y <= 10 ** 9: ret.append(y - 1) y = 2 * y - 1 return ret has_special = False generators = set() for number in a: x = number - 1 while x % 2 == 0: x //= 2 x += 1 # print(number, x) generators.add(x) if not is_special(x): x -= 1 while x % 3 == 0: x //= 3 generators.add(x + 1) else: has_special = True if sum(map(lambda t: int(is_special(t)), generators)) > 1: print(0) else: differencies = set() rr = set() had = False if has_special: for x in sorted(generators): if is_special(x): differencies.update(set(series(x))) else: for x in sorted(generators): if is_special(x): differencies.update(set(series(x))) else: if not had: had = True differencies.update(set(series(x))) else: pass print(x, series(x)) # print(sorted(generators)) # print(sorted(differencies)) answer = 0 for d in differencies: answer += max(0, m - d) print(answer) ``` No
3,677
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a, b). Each of the three horses can paint the special cards. If you show an (a, b) card to the gray horse, then the horse can paint a new (a + 1, b + 1) card. If you show an (a, b) card, such that a and b are even integers, to the white horse, then the horse can paint a new <image> card. If you show two cards (a, b) and (b, c) to the gray-and-white horse, then he can paint a new (a, c) card. Polycarpus really wants to get n special cards (1, a1), (1, a2), ..., (1, an). For that he is going to the horse land. He can take exactly one (x, y) card to the horse land, such that 1 ≤ x < y ≤ m. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards? Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires. Input The first line contains two integers n, m (1 ≤ n ≤ 105, 2 ≤ m ≤ 109). The second line contains the sequence of integers a1, a2, ..., an (2 ≤ ai ≤ 109). Note, that the numbers in the sequence can coincide. The numbers in the lines are separated by single spaces. Output Print a single integer — the answer to the problem. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 1 6 2 Output 11 Input 1 6 7 Output 14 Input 2 10 13 7 Output 36 Submitted Solution: ``` n, m = map(int, input().split()) a = list(map(int, input().split())) def is_special(x): return (x % 4 == 2 and (x // 4) % 4 <= 1) or (x % 4 == 0 and (x // 4) % 4 > 1) def series(y): ret = [] while y <= 10 ** 9: ret.append(y - 1) y = 2 * y - 1 return ret has_special = False generators = set() for number in a: x = number - 1 while x % 2 == 0: x //= 2 x += 1 # print(number, x) generators.add(x) if not is_special(x): x -= 1 while x % 3 == 0: x //= 3 generators.add(x + 1) else: has_special = True if sum(map(lambda t: int(is_special(t)), generators)) > 1: print(0) else: differencies = set() rr = set() had = False if has_special: for x in sorted(generators): if is_special(x): differencies.update(set(series(x))) else: for x in sorted(generators): if is_special(x): differencies.update(set(series(x))) else: if not had: had = True differencies.update(set(series(x))) else: pass # print(x, series(x)) # print(sorted(generators)) # print(sorted(differencies)) answer = 0 for d in differencies: answer += max(0, m - d) print(answer) ``` No
3,678
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a, b). Each of the three horses can paint the special cards. If you show an (a, b) card to the gray horse, then the horse can paint a new (a + 1, b + 1) card. If you show an (a, b) card, such that a and b are even integers, to the white horse, then the horse can paint a new <image> card. If you show two cards (a, b) and (b, c) to the gray-and-white horse, then he can paint a new (a, c) card. Polycarpus really wants to get n special cards (1, a1), (1, a2), ..., (1, an). For that he is going to the horse land. He can take exactly one (x, y) card to the horse land, such that 1 ≤ x < y ≤ m. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards? Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires. Input The first line contains two integers n, m (1 ≤ n ≤ 105, 2 ≤ m ≤ 109). The second line contains the sequence of integers a1, a2, ..., an (2 ≤ ai ≤ 109). Note, that the numbers in the sequence can coincide. The numbers in the lines are separated by single spaces. Output Print a single integer — the answer to the problem. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 1 6 2 Output 11 Input 1 6 7 Output 14 Input 2 10 13 7 Output 36 Submitted Solution: ``` n, m = map(int, input().split()) a = list(map(int, input().split())) def is_special(x): return not(x % 6 == 4) def series(y): ret = [] while y <= 10 ** 9: ret.append(y - 1) y = 2 * y - 1 return ret has_special = False generators = set() for number in a: x = number - 1 while x % 2 == 0: x //= 2 x += 1 # print(number, x) generators.add(x) if not is_special(x): x -= 1 while x % 3 == 0: x //= 3 generators.add(x + 1) else: has_special = True if sum(map(lambda t: int(is_special(t)), generators)) > 1: print(0) else: differencies = set() rr = set() had = False if has_special: for x in sorted(generators): if is_special(x): differencies.update(set(series(x))) else: for x in sorted(generators): if is_special(x): differencies.update(set(series(x))) else: if not had: had = True rr = set(series(x)) else: continue rr = rr.intersection(set(series(x))) # print(x, series(x)) differencies.update(rr) # print(sorted(generators)) # print(sorted(differencies)) answer = 0 for d in differencies: answer += max(0, m - d) print(answer) ``` No
3,679
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Tags: dp, graphs, shortest paths Correct Solution: ``` import sys from array import array # noqa: F401 n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] aa = tuple(map(lambda x: int(x) - 1, input().split())) ans = [''] * n for i in range(n-1, -1, -1): x = aa[i] for a in range(n): for b in range(n): if matrix[a][b] > matrix[a][x] + matrix[x][b]: matrix[a][b] = matrix[a][x] + matrix[x][b] val, overflow = 0, 0 for a in aa[i:]: for b in aa[i:]: val += matrix[a][b] if val > 10**9: overflow += 1 val -= 10**9 ans[i] = str(10**9 * overflow + val) print(' '.join(ans)) ```
3,680
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Tags: dp, graphs, shortest paths Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [''] * n for i in range(n - 1, -1, -1): x = a[i] for u in range(n): for v in range(n): if matrix[u][v] > matrix[u][x] + matrix[x][v]: matrix[u][v] = matrix[u][x] + matrix[x][v] upper, lower = 0, 0 for u in a[i:]: for v in a[i:]: lower += matrix[u][v] if lower >= 10**9: upper += 1 lower -= 10**9 ans[i] = str(upper * 10**9 + lower) sys.stdout.buffer.write(' '.join(ans).encode('utf-8')) ```
3,681
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Tags: dp, graphs, shortest paths Correct Solution: ``` #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools import bisect import heapq from array import array def input(): return sys.stdin.readline()[:-1] # sys.setrecursionlimit(1000000) # _INPUT = """4 # 0 57148 51001 13357 # 71125 0 98369 67226 # 49388 90852 0 66291 # 39573 38165 97007 0 # 2 3 1 4 # """ # sys.stdin = io.StringIO(_INPUT) INF = 10**10 N = int(input()) A = [array('i', list(map(int, input().split()))) for _ in range(N)] X = list(map(lambda x: int(x)-1, input().split())) result = [] for k in reversed(range(N)): x = X[k] for i in range(N): for j in range(N): d = A[i][x] + A[x][j] if d < A[i][j]: A[i][j] = d v = 0 upper = 0 for i in X[k:]: for j in X[k:]: v += A[i][j] if v > 10**9: v -= 10**9 upper += 1 result.append(str((10**9) * upper + v)) print(' '.join(reversed(result))) ```
3,682
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Tags: dp, graphs, shortest paths Correct Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush # from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 from sys import stdin input = stdin.readline def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] try: # sys.setrecursionlimit(int(pow(10,6))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass from array import array def input(): return sys.stdin.buffer.readline().decode('utf-8') def solve(): n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [''] * n for i in range(n - 1, -1, -1): x = a[i] for u in range(n): for v in range(n): if matrix[u][v] > matrix[u][x] + matrix[x][v]: matrix[u][v] = matrix[u][x] + matrix[x][v] upper, lower = 0, 0 for u in a[i:]: for v in a[i:]: lower += matrix[u][v] if lower >= 10**9: upper += 1 lower -= 10**9 ans[i] = str(upper * 10**9 + lower) sys.stdout.buffer.write(' '.join(ans).encode('utf-8')) solve() endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ```
3,683
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Tags: dp, graphs, shortest paths Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') def solve(): n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [''] * n for i in range(n - 1, -1, -1): x = a[i] for u in range(n): for v in range(n): if matrix[u][v] > matrix[u][x] + matrix[x][v]: matrix[u][v] = matrix[u][x] + matrix[x][v] upper, lower = 0, 0 for u in a[i:]: for v in a[i:]: lower += matrix[u][v] if lower >= 10**9: upper += 1 lower -= 10**9 ans[i] = str(upper * 10**9 + lower) sys.stdout.buffer.write(' '.join(ans).encode('utf-8')) if __name__ == '__main__': solve() ```
3,684
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Tags: dp, graphs, shortest paths Correct Solution: ``` #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools import bisect import heapq from array import array def input(): return sys.stdin.readline()[:-1] # sys.setrecursionlimit(1000000) # _INPUT = """4 # 0 57148 51001 13357 # 71125 0 98369 67226 # 49388 90852 0 66291 # 39573 38165 97007 0 # 2 3 1 4 # """ # sys.stdin = io.StringIO(_INPUT) INF = 10**10 N = int(input()) A = [array('i', list(map(int, input().split()))) for _ in range(N)] X = list(map(lambda x: int(x)-1, input().split())) result = [] for k in reversed(range(N)): x = X[k] for i in range(N): for j in range(N): d = A[i][x] + A[x][j] if d < A[i][j]: A[i][j] = d v = 0 overflow = 0 for i in X[k:]: for j in X[k:]: v += A[i][j] if v > 10**9: v -= 10**9 overflow += 1 result.append(str(v + (10**9) * overflow)) print(' '.join(reversed(result))) ```
3,685
Provide tags and a correct Python 3 solution for this coding contest problem. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Tags: dp, graphs, shortest paths Correct Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) matrix = [array('i', list(map(int, input().split()))) for _ in range(n)] aa = tuple(map(lambda x: int(x) - 1, input().split())) ans = [''] * n for i in range(n-1, -1, -1): x = aa[i] for a in range(n): for b in range(n): if matrix[a][b] > matrix[a][x] + matrix[x][b]: matrix[a][b] = matrix[a][x] + matrix[x][b] lower, higher = 0, 0 for a in aa[i:]: for b in aa[i:]: lower += matrix[a][b] if lower > 10**9: higher += 1 lower -= 10**9 ans[i] = str(10**9 * higher + lower) print(' '.join(ans)) ```
3,686
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Submitted Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) edges = [tuple(map(int, input().split())) for _ in range(n)] matrix = [[10**9] * n for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [0] * n for i in range(n - 1, -1, -1): for j in range(n): matrix[a[i]][j] = min(matrix[a[i]][j], edges[a[i]][j]) matrix[j][a[i]] = min(matrix[j][a[i]], edges[j][a[i]]) for u in a[i + 1:]: for v in a[i + 1:]: matrix[u][v] = min(matrix[u][v], matrix[u][a[i]] + matrix[a[i]][v]) for u in a[i:]: for v in a[i:]: ans[i] += matrix[u][v] print(*ans) ``` No
3,687
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Submitted Solution: ``` #!/usr/bin/env python3 # from typing import * import sys import io import math import collections import decimal import itertools import bisect import heapq def input(): return sys.stdin.readline()[:-1] # sys.setrecursionlimit(1000000) # _INPUT = """4 # 0 3 1 1 # 6 0 400 1 # 2 4 0 1 # 1 1 1 0 # 4 1 2 3 # """ # sys.stdin = io.StringIO(_INPUT) INF = 10**10 N = int(input()) A = [list(map(int, input().split())) for _ in range(N)] X = list(map(lambda x: int(x)-1, input().split())) dist = [[INF] * N for _ in range(N)] for i in range(N): dist[i][i] = 0 result = [] Allowed = [] for x in reversed(X): Allowed.append(x) for i in Allowed: dist[i][x] = A[i][x] dist[x][i] = A[x][i] v = 0 for i in Allowed: for j in Allowed: dist[i][j] = min(dist[i][j], dist[i][x] + dist[x][j]) v += dist[i][j] result.append(v) print(*reversed(result)) ``` No
3,688
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Greg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: * The game consists of n steps. * On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. * Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: <image>. Help Greg, print the value of the required sum before each step. Input The first line contains integer n (1 ≤ n ≤ 500) — the number of vertices in the graph. Next n lines contain n integers each — the graph adjacency matrix: the j-th number in the i-th line aij (1 ≤ aij ≤ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j. The next line contains n distinct integers: x1, x2, ..., xn (1 ≤ xi ≤ n) — the vertices that Greg deletes. Output Print n integers — the i-th number equals the required sum before the i-th step. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier. Examples Input 1 0 1 Output 0 Input 2 0 5 4 0 1 2 Output 9 0 Input 4 0 3 1 1 6 0 400 1 2 4 0 1 1 1 1 0 4 1 2 3 Output 17 23 404 0 Submitted Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) matrix = [list(map(int, input().split())) for _ in range(n)] a = tuple(map(lambda x: int(x) - 1, input().split())) ans = [0] * n for i in range(n - 1, -1, -1): for u in a[i + 1:]: for v in a[i + 1:]: matrix[a[i]][u] = min(matrix[a[i]][u], matrix[a[i]][v] + matrix[v][u]) matrix[u][a[i]] = min(matrix[u][a[i]], matrix[u][v] + matrix[v][a[i]]) matrix[u][v] = min(matrix[u][v], matrix[u][a[i]] + matrix[a[i]][v]) for u in a[i:]: for v in a[i:]: ans[i] += matrix[u][v] print(*ans) ``` No
3,689
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Tags: data structures, divide and conquer, trees Correct Solution: ``` class CentroidDecomposition(): def __init__(self, g): self.g = g self.n = len(g) self.parent = [-1]*self.n self.size = [1]*self.n self.cdparent = [-1]*self.n self.cddepth = [0]*self.n self.cdorder = [-1]*self.n self.cdused = [0]*self.n cnt = 0 stack = [0] while stack: v = stack.pop() p = self.cdparent[v] c = self.get_centroid(v) self.cdused[c] = True self.cdparent[c] = p self.cddepth[c] = self.cddepth[v] self.cdorder[c] = cnt cnt += 1 for u in self.g[c]: if self.cdused[u]: continue self.cdparent[u] = c self.cddepth[u] = self.cddepth[c]+1 stack.append(u) def get_centroid(self, root): self.parent[root] = -1 self.size[root] = 1 stack = [root] order = [] while stack: v = stack.pop() order.append(v) for u in g[v]: if self.parent[v] == u or self.cdused[u]: continue self.size[u] = 1 self.parent[u] = v stack.append(u) if len(order) <= 2: return root for v in reversed(order): if self.parent[v] == -1: continue self.size[self.parent[v]] += self.size[v] total = self.size[root] v = root while True: for u in self.g[v]: if self.parent[v] == u or self.cdused[u]: continue if self.size[u] > total//2: v = u break else: return v class HLD: def __init__(self, g): self.g = g self.n = len(g) self.parent = [-1]*self.n self.size = [1]*self.n self.head = [0]*self.n self.preorder = [0]*self.n self.k = 0 self.depth = [0]*self.n for v in range(self.n): if self.parent[v] == -1: self.dfs_pre(v) self.dfs_hld(v) def dfs_pre(self, v): g = self.g stack = [v] order = [v] while stack: v = stack.pop() for u in g[v]: if self.parent[v] == u: continue self.parent[u] = v self.depth[u] = self.depth[v]+1 stack.append(u) order.append(u) # 隣接リストの左端: heavyな頂点への辺 # 隣接リストの右端: 親への辺 while order: v = order.pop() child_v = g[v] if len(child_v) and child_v[0] == self.parent[v]: child_v[0], child_v[-1] = child_v[-1], child_v[0] for i, u in enumerate(child_v): if u == self.parent[v]: continue self.size[v] += self.size[u] if self.size[u] > self.size[child_v[0]]: child_v[i], child_v[0] = child_v[0], child_v[i] def dfs_hld(self, v): stack = [v] while stack: v = stack.pop() self.preorder[v] = self.k self.k += 1 top = self.g[v][0] # 隣接リストを逆順に見ていく(親 > lightな頂点への辺 > heavyな頂点 (top)) # 連結成分が連続するようにならべる for u in reversed(self.g[v]): if u == self.parent[v]: continue if u == top: self.head[u] = self.head[v] else: self.head[u] = u stack.append(u) def for_each(self, u, v): # [u, v]上の頂点集合の区間を列挙 while True: if self.preorder[u] > self.preorder[v]: u, v = v, u l = max(self.preorder[self.head[v]], self.preorder[u]) r = self.preorder[v] yield l, r # [l, r] if self.head[u] != self.head[v]: v = self.parent[self.head[v]] else: return def for_each_edge(self, u, v): # [u, v]上の辺集合の区間列挙 # 辺の情報は子の頂点に while True: if self.preorder[u] > self.preorder[v]: u, v = v, u if self.head[u] != self.head[v]: yield self.preorder[self.head[v]], self.preorder[v] v = self.parent[self.head[v]] else: if u != v: yield self.preorder[u]+1, self.preorder[v] break def subtree(self, v): # 頂点vの部分木の頂点集合の区間 [l, r) l = self.preorder[v] r = self.preorder[v]+self.size[v] return l, r def lca(self, u, v): # 頂点u, vのLCA while True: if self.preorder[u] > self.preorder[v]: u, v = v, u if self.head[u] == self.head[v]: return u v = self.parent[self.head[v]] import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, m = map(int, input().split()) g = [[] for i in range(n)] for i in range(n-1): a, b = map(int, input().split()) a, b = a-1, b-1 g[a].append(b) g[b].append(a) cd = CentroidDecomposition(g) hld = HLD(g) #print(cd.cdparent) min_dist = [0]*n for i in range(n): min_dist[i] = hld.depth[i] #print(min_dist) for i in range(m): t, v = map(int, input().split()) v -= 1 if t == 1: cur = v while cur != -1: l = hld.lca(cur, v) d = hld.depth[cur]+hld.depth[v]-2*hld.depth[l] min_dist[cur] = min(min_dist[cur], d) cur = cd.cdparent[cur] else: ans = n cur = v while cur != -1: l = hld.lca(cur, v) d = hld.depth[cur]+hld.depth[v]-2*hld.depth[l] ans = min(ans, d+min_dist[cur]) cur = cd.cdparent[cur] print(ans) ```
3,690
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Tags: data structures, divide and conquer, trees Correct Solution: ``` n,m=map(int,input().split()) tr=[set() for i in range(n+1)] trr=[[] for i in range(n+1)] for _ in range(n-1): a,b=map(int,input().split()) trr[a].append(b);trr[b].append(a) tr[a].add(b);tr[b].add(a) euler=[] disc=[-1 for i in range(n+1)] hei=[-1 for i in range(n+1)] def eulerr(): q=[1] pa={1:-1} hei[1]=0 while q: x=q.pop() if disc[x]==-1:disc[x]=len(euler) euler.append(x) if len(trr[x])==0: if pa[x]!=-1:q.append(pa[x]) elif trr[x][-1]==pa[x]: trr[x].pop(-1) q.append(x) euler.pop() else: y=trr[x].pop(-1) pa[y]=x hei[y]=hei[x]+1 q.append(y) eulerr() st=[-1 for i in range(2*len(euler))] for i in range(len(euler)): st[i+len(euler)]=euler[i] for i in range(len(euler)-1,0,-1): if disc[st[i<<1]]<disc[st[i<<1|1]]: st[i]=st[i<<1] else: st[i]=st[i<<1|1] def dist(a,b): i=disc[a];j=disc[b] if i>j:i,j=j,i i+=len(euler);j+=len(euler)+1 ans=st[i] while i<j: if i&1: if disc[st[i]]<disc[ans]:ans=st[i] i+=1 if j&1: j-=1 if disc[st[j]]<disc[ans]:ans=st[j] i>>=1 j>>=1 return(hei[a]+hei[b]-2*hei[ans]) size=[0 for i in range(n+1)] def siz(i): pa={i:-1} q=[i] w=[] while q: x=q.pop() w.append(x) size[x]=1 for y in tr[x]: if y==pa[x]:continue pa[y]=x q.append(y) for j in range(len(w)-1,0,-1): x=w[j] size[pa[x]]+=size[x] return(size[i]) def centroid(i,nn): pa={i:-1} q=[i] while q: x=q.pop() for y in tr[x]: if y!=pa[x] and size[y]>nn/2: q.append(y) pa[y]=x break else:return(x) ct=[-1 for i in range(n+1)] def build(): q=[1] while q: x=q.pop() nn=siz(x) j=centroid(x,nn) ct[j]=ct[x] for y in tr[j]: tr[y].discard(j) ct[y]=j q.append(y) tr[j].clear() build() ps=[float("INF") for i in range(n+1)] ps[1]=0 x=1 while ct[x]!=-1: ps[ct[x]]=min(ct[x],dist(1,ct[x])) x=ct[x] for _ in range(m): t,x=map(int,input().split()) if t==1: v=x while x!=-1: ps[x]=min(ps[x],dist(v,x)) x=ct[x] else: ans=ps[x] v=x while x!=-1: ans=min(ans,ps[x]+dist(v,x)) x=ct[x] print(ans) ```
3,691
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Tags: data structures, divide and conquer, trees Correct Solution: ``` class Tree(): def __init__(self, n): self.n = n self.tree = [[] for _ in range(n)] self.root = None def add_edge(self, u, v): self.tree[u].append(v) self.tree[v].append(u) def set_root(self, r=0): self.root = r self.par = [None] * self.n self.dep = [0] * self.n self.height = [0] * self.n self.size = [1] * self.n self.ord = [r] stack = [r] while stack: v = stack.pop() for adj in self.tree[v]: if self.par[v] == adj: continue self.par[adj] = v self.dep[adj] = self.dep[v] + 1 self.ord.append(adj) stack.append(adj) for v in self.ord[1:][::-1]: self.size[self.par[v]] += self.size[v] self.height[self.par[v]] = max(self.height[self.par[v]], self.height[v] + 1) def rerooting(self, op, e, merge, id): if self.root is None: self.set_root() dp = [e] * self.n lt = [id] * self.n rt = [id] * self.n inv = [id] * self.n for v in self.ord[::-1]: tl = tr = e for adj in self.tree[v]: if self.par[v] == adj: continue lt[adj] = tl tl = op(tl, dp[adj]) for adj in self.tree[v][::-1]: if self.par[v] == adj: continue rt[adj] = tr tr = op(tr, dp[adj]) dp[v] = tr for v in self.ord: if v == self.root: continue p = self.par[v] inv[v] = op(merge(lt[v], rt[v]), inv[p]) dp[v] = op(dp[v], inv[v]) return dp def euler_tour(self): if self.root is None: self.set_root() self.tour = [] self.etin = [None for _ in range(self.n)] self.etout = [None for _ in range(self.n)] used = [0 for _ in range(self.n)] used[self.root] = 1 stack = [self.root] while stack: v = stack.pop() if v >= 0: self.tour.append(v) stack.append(~v) if self.etin[v] is None: self.etin[v] = len(self.tour) - 1 for adj in self.tree[v]: if used[adj]: continue used[adj] = 1 stack.append(adj) else: self.etout[~v] = len(self.tour) if ~v != self.root: self.tour.append(self.par[~v]) def heavylight_decomposition(self): if self.root is None: self.set_root() self.hldid = [None] * self.n self.hldtop = [None] * self.n self.hldtop[self.root] = self.root self.hldnxt = [None] * self.n self.hldrev = [None] * self.n stack = [self.root] cnt = 0 while stack: v = stack.pop() self.hldid[v] = cnt self.hldrev[cnt] = v cnt += 1 maxs = 0 for adj in self.tree[v]: if self.par[v] == adj: continue if maxs < self.size[adj]: maxs = self.size[adj] self.hldnxt[v] = adj for adj in self.tree[v]: if self.par[v] == adj or self.hldnxt[v] == adj: continue self.hldtop[adj] = adj stack.append(adj) if self.hldnxt[v] is not None: self.hldtop[self.hldnxt[v]] = self.hldtop[v] stack.append(self.hldnxt[v]) def lca(self, u, v): while True: if self.hldid[u] > self.hldid[v]: u, v = v, u if self.hldtop[u] != self.hldtop[v]: v = self.par[self.hldtop[v]] else: return u def dist(self, u, v): lca = self.lca(u, v) return self.dep[u] + self.dep[v] - 2 * self.dep[lca] def range_query(self, u, v, edge_query=False): while True: if self.hldid[u] > self.hldid[v]: u, v = v, u if self.hldtop[u] != self.hldtop[v]: yield self.hldid[self.hldtop[v]], self.hldid[v] + 1 v = self.par[self.hldtop[v]] else: yield self.hldid[u] + edge_query, self.hldid[v] + 1 return def subtree_query(self, u): return self.hldid[u], self.hldid[u] + self.size[u] def _get_centroid_(self, r): self._par_[r] = None self._size_[r] = 1 ord = [r] stack = [r] while stack: v = stack.pop() for adj in self.tree[v]: if self._par_[v] == adj or self.cdused[adj]: continue self._size_[adj] = 1 self._par_[adj] = v ord.append(adj) stack.append(adj) if len(ord) <= 2: return r for v in ord[1:][::-1]: self._size_[self._par_[v]] += self._size_[v] sr = self._size_[r] // 2 v = r while True: for adj in self.tree[v]: if self._par_[v] == adj or self.cdused[adj]: continue if self._size_[adj] > sr: v = adj break else: return v def centroid_decomposition(self): self._par_ = [None] * self.n self._size_ = [1] * self.n self.cdpar = [None] * self.n self.cddep = [0] * self.n self.cdord = [None] * self.n self.cdused = [0] * self.n cnt = 0 stack = [0] while stack: v = stack.pop() p = self.cdpar[v] c = self._get_centroid_(v) self.cdused[c] = True self.cdpar[c] = p self.cddep[c] = self.cddep[v] self.cdord[c] = cnt cnt += 1 for adj in self.tree[c]: if self.cdused[adj]: continue self.cdpar[adj] = c self.cddep[adj] = self.cddep[c] + 1 stack.append(adj) def centroid(self): if self.root is None: self.set_root() sr = self.size[self.root] // 2 v = self.root while True: for adj in self.tree[v]: if self.par[v] == adj: continue if self.size[adj] > sr: v = adj break else: return v def diam(self): if self.root is None: self.set_root() u = self.dep.index(max(self.dep)) self.set_root(u) v = self.dep.index(max(self.dep)) return u, v def get_path(self, u, v): if self.root != u: self.set_root(u) path = [] while v != None: path.append(v) v = self.par[v] return path def longest_path_decomposition(self, make_ladder=True): assert self.root is not None self.lpdnxt = [None] * self.n self.lpdtop = [None] * self.n self.lpdtop[self.root] = self.root stack = [self.root] while stack: v = stack.pop() for adj in self.tree[v]: if self.par[v] == adj: continue if self.height[v] == self.height[adj] + 1: self.lpdnxt[v] = adj for adj in self.tree[v]: if self.par[v] == adj or self.lpdnxt[v] == adj: continue self.lpdtop[adj] = adj stack.append(adj) if self.lpdnxt[v] is not None: self.lpdtop[self.lpdnxt[v]] = self.lpdtop[v] stack.append(self.lpdnxt[v]) if make_ladder: self._make_ladder_() def _make_ladder_(self): self.ladder = [[] for _ in range(self.n)] for v in range(self.n): if self.lpdtop[v] != v: continue to = v path = [] while to is not None: path.append(to) to = self.lpdnxt[to] p = self.par[v] self.ladder[v] = path[::-1] for i in range(len(path)): self.ladder[v].append(p) if p is None: break p = self.par[p] def level_ancestor(self, v, k): while v is not None: id = self.height[v] h = self.lpdtop[v] if len(self.ladder[h]) > k + id: return self.ladder[h][k + id] v = self.ladder[h][-1] k -= len(self.ladder[h]) - id - 1 import io, os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline N, Q = map(int, input().split()) t = Tree(N) for _ in range(N - 1): u, v = map(int, input().split()) t.add_edge(u - 1, v - 1) t.heavylight_decomposition() t.centroid_decomposition() min_dist = [N] * N res = [] def query_1(v): cur = v while cur is not None: min_dist[cur] = min(min_dist[cur], t.dist(cur, v)) cur = t.cdpar[cur] def query_2(v): ret = N cur = v while cur is not None: ret = min(ret, t.dist(cur, v) + min_dist[cur]) cur = t.cdpar[cur] return ret query_1(0) for _ in range(Q): q, v = map(int, input().split()) if q == 1: query_1(v - 1) else: res.append((query_2(v - 1))) print('\n'.join(map(str, res))) ```
3,692
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Tags: data structures, divide and conquer, trees Correct Solution: ``` class CentroidDecomposition(): def __init__(self, g): self.g = g self.n = len(g) self.parent = [-1]*self.n self.size = [1]*self.n self.cdparent = [-1]*self.n self.cddepth = [0]*self.n self.cdorder = [-1]*self.n self.cdused = [0]*self.n cnt = 0 stack = [0] while stack: v = stack.pop() p = self.cdparent[v] c = self.get_centroid(v) self.cdused[c] = True self.cdparent[c] = p self.cddepth[c] = self.cddepth[v] self.cdorder[c] = cnt cnt += 1 for u in self.g[c]: if self.cdused[u]: continue self.cdparent[u] = c self.cddepth[u] = self.cddepth[c]+1 stack.append(u) def get_centroid(self, root): self.parent[root] = -1 self.size[root] = 1 stack = [root] order = [] while stack: v = stack.pop() order.append(v) for u in g[v]: if self.parent[v] == u or self.cdused[u]: continue self.size[u] = 1 self.parent[u] = v stack.append(u) if len(order) <= 2: return root for v in reversed(order): if self.parent[v] == -1: continue self.size[self.parent[v]] += self.size[v] total = self.size[root] v = root while True: for u in self.g[v]: if self.parent[v] == u or self.cdused[u]: continue if self.size[u] > total//2: v = u break else: return v class SegTree: def __init__(self, init_val, ide_ele, segfunc): self.n = len(init_val) self.num = 2**(self.n-1).bit_length() self.ide_ele = ide_ele self.segfunc = segfunc self.seg = [ide_ele]*2*self.num # set_val for i in range(self.n): self.seg[i+self.num] = init_val[i] # built for i in range(self.num-1, 0, -1): self.seg[i] = self.segfunc(self.seg[2*i], self.seg[2*i+1]) def update(self, k, x): k += self.num self.seg[k] = x while k: k = k >> 1 self.seg[k] = self.segfunc(self.seg[2*k], self.seg[2*k+1]) def query(self, l, r): if r <= l: return self.ide_ele l += self.num r += self.num res = self.ide_ele while l < r: if r & 1: r -= 1 res = self.segfunc(res, self.seg[r]) if l & 1: res = self.segfunc(res, self.seg[l]) l += 1 l = l >> 1 r = r >> 1 return res def segfunc(x, y): if x <= y: return x else: return y ide_ele = 10**18 class LCA: def __init__(self, g, root): # g: adjacency list # root self.n = len(g) self.root = root s = [self.root] self.parent = [-1]*self.n self.child = [[] for _ in range(self.n)] visit = [-1]*self.n visit[self.root] = 0 while s: v = s.pop() for u in g[v]: if visit[u] == -1: self.parent[u] = v self.child[v].append(u) visit[u] = 0 s.append(u) # Euler tour tank = [self.root] self.eulerTour = [] self.left = [0]*self.n self.right = [-1]*self.n self.depth = [-1]*self.n eulerNum = -1 de = -1 while tank: v = tank.pop() if v >= 0: eulerNum += 1 self.eulerTour.append(v) self.left[v] = eulerNum self.right[v] = eulerNum tank.append(~v) de += 1 self.depth[v] = de for u in self.child[v]: tank.append(u) else: de -= 1 if ~v != self.root: self.eulerTour.append(self.parent[~v]) eulerNum += 1 self.right[self.parent[~v]] = eulerNum #A = [self.depth[e] for e in self.eulerTour] A = [0]*(2*self.n-1) for i, e in enumerate(self.eulerTour): A[i] = self.depth[e]*(2*self.n-1)+i self.seg = SegTree(A, ide_ele, segfunc) def getLCA(self, u, v): # u, v: 0-indexed p = min(self.left[u], self.left[v]) q = max(self.right[u], self.left[v])+1 m = self.seg.query(p, q) return self.eulerTour[m%(2*self.n-1)] import sys import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n, m = map(int, input().split()) g = [[] for i in range(n)] for i in range(n-1): a, b = map(int, input().split()) a, b = a-1, b-1 g[a].append(b) g[b].append(a) cd = CentroidDecomposition(g) lca = LCA(g, 0) #print(cd.cdparent) min_dist = [0]*n for i in range(n): min_dist[i] = lca.depth[i] #print(min_dist) for i in range(m): t, v = map(int, input().split()) v -= 1 if t == 1: cur = v while cur != -1: l = lca.getLCA(cur, v) d = lca.depth[cur]+lca.depth[v]-2*lca.depth[l] min_dist[cur] = min(min_dist[cur], d) cur = cd.cdparent[cur] else: ans = n cur = v while cur != -1: l = lca.getLCA(cur, v) d = lca.depth[cur]+lca.depth[v]-2*lca.depth[l] ans = min(ans, d+min_dist[cur]) cur = cd.cdparent[cur] print(ans) ```
3,693
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Submitted Solution: ``` N = int(1e5)+10 logn=20 graph = [[] for i in range(N)] par,sub,level,ans=[0 for i in range(N)],[0 for i in range(N)],[0 for i in range(N)],[float('inf') for i in range(N)] dp = [[0 for i in range(N)] for j in range(logn)] nn=0 #preprocessing part! def dfs0(u): global graph,level for v in graph[u]: if v!=dp[0][u]: dp[0][v]=u level[v]=level[u]+1 dfs0(v) def preprocess(): global dp level[0]=0 dp[0][0]=0 dfs0(0) for i in range(logn): for j in range(int(1e5)+10): dp[i][j]=dp[i-1][dp[i-1][j]] def lca(a,b): global level,dp,logn if level[a]>level[b]: a,b=b,a d = level[b]-level[a] for i in range(logn): if d&(1<<i): b=dp[i][b] if a==b: return a for i in range(logn-1,-1,-1): if dp[i][a]!=dp[i][b]: a,b=dp[i][a],dp[i][b] return dp[0][a] def dist(u,v): global level return level[u]+level[v]-2*level[lca(u,v)] #Decomposition part def dfs1(u,p): global graph,sub,nn sub[u]=1 nn+=1 for v in graph[u]: if v!=p: dfs1(v,u) sub[u]+=sub[v] def dfs2(u,p): global graph,sub for v in graph[u]: if v!=p and sub[v]>nn/2: return dfs2(v,u) return u def decompose(root,p): global graph nn=0 dfs1(root,root) centroid=dfs2(root,root) if p==-1:p=centroid par[centroid]=p for v in graph[centroid]: graph[v].remove(centroid) decompose(v,centroid) graph[centroid]=[] #Handling the queries part! def update(u): global ans,par x=u while True: ans[x]=min(ans[x],dist(x,u)) if x==par[x]:break x=par[x] def query(u): global par,ans x=u;ret=float('inf') while True: ret = min(ret,dist(u,x)+ans[x]) if x==par[x]: break x=par[x] return ret n,m=map(int,input().split()) for i in range(n-1): a,b = map(int,input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) preprocess() decompose(0,-1) update(0) for i in range(m): t,v = map(int,input().split());v-=1 if t==1: update(v) else: print(query(v)) ``` No
3,694
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Submitted Solution: ``` n,m=map(int,input().split()) tr=[set() for i in range(n+1)] trr=[[] for i in range(n+1)] for _ in range(n-1): a,b=map(int,input().split()) trr[a].append(b);trr[b].append(a) tr[a].add(b);tr[b].add(a) euler=[] disc=[-1 for i in range(n+1)] hei=[-1 for i in range(n+1)] def eulerr(): q=[1] pa={1:-1} hei[1]=0 while q: x=q.pop() if disc[x]==-1:disc[x]=len(euler) euler.append(x) if len(trr[x])==0: if pa[x]!=-1:q.append(pa[x]) elif trr[x][-1]==pa[x]: trr[x].pop(-1) q.append(x) euler.pop() else: y=trr[x].pop(-1) pa[y]=x hei[y]=hei[x]+1 q.append(y) eulerr() print(euler) st=[-1 for i in range(2*len(euler))] for i in range(len(euler)): st[i+len(euler)]=euler[i] for i in range(len(euler)-1,0,-1): if disc[st[i<<1]]<disc[st[i<<1|1]]: st[i]=st[i<<1] else: st[i]=st[i<<1|1] def dist(a,b): i=disc[a];j=disc[b] if i>j:i,j=j,i i+=len(euler);j+=len(euler)+1 ans=st[i] while i<j: if i&1: if disc[st[i]]<disc[ans]:ans=st[i] i+=1 if j&1: j-=1 if disc[st[j]]<disc[ans]:ans=st[j] i>>=1 j>>=1 return(hei[a]+hei[b]-2*hei[ans]) size=[0 for i in range(n+1)] def siz(i): pa={i:-1} q=[i] w=[] while q: x=q.pop() w.append(x) size[x]=1 for y in tr[x]: if y==pa[x]:continue pa[y]=x q.append(y) for j in range(len(w)-1,0,-1): x=w[j] size[pa[x]]+=size[x] return(size[i]) def centroid(i,nn): pa={i:-1} q=[i] while q: x=q.pop() for y in tr[x]: if y!=pa[x] and size[y]>nn/2: q.append(y) pa[y]=x break else:return(x) ct=[-1 for i in range(n+1)] def build(): q=[1] while q: x=q.pop() nn=siz(x) j=centroid(x,nn) ct[j]=ct[x] for y in tr[j]: tr[y].discard(j) ct[y]=j q.append(y) tr[j].clear() build() print(ct) ps=[float("INF") for i in range(n+1)] ps[1]=0 x=1 while ct[x]!=-1: ps[ct[x]]=min(ct[x],dist(1,ct[x])) x=ct[x] for _ in range(m): t,x=map(int,input().split()) if t==1: v=x while x!=-1: ps[x]=min(ps[x],dist(v,x)) x=ct[x] else: ans=ps[x] v=x while x!=-1: ans=min(ans,ps[x]+dist(v,x)) x=ct[x] print(ans) ``` No
3,695
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Submitted Solution: ``` N = int(1e5)+10 logn=20 graph = [[] for i in range(N)] par,sub,level,ans=[0 for i in range(N)],[0 for i in range(N)],[0 for i in range(N)],[float('inf') for i in range(N)] dp = [[0 for i in range(N)] for j in range(logn)] nn=0 #preprocessing part! def dfs0(u): global graph,level for v in graph[u]: if v!=dp[0][u]: dp[0][v]=u level[v]=level[u]+1 dfs0(v) def preprocess(): global dp level[0]=0 dp[0][0]=0 dfs0(1) for i in range(20): for j in range(int(1e5)+10): dp[i][j]=dp[i-1][dp[i-1][j]] def lca(a,b): global level,dp,logn if level[a]>level[b]: a,b=b,a d = level[b]-level[a] for i in range(logn): if d&(1<<i): b=dp[i][b] if a==b: return a for i in range(logn-1,-1,-1): if dp[i][a]!=dp[i][b]: a,b=dp[i][a],dp[i][b] return dp[0][a] def dist(u,v): global level return level[u]+level[v]-2*level[lca(u,v)] #Decomposition part def dfs1(u,p): global graph,sub,nn sub[u]=1 nn+=1 for v in graph[u]: if v!=p: dfs1(v,u) sub[u]+=sub[v] def dfs2(u,p): global graph,sub for v in graph[u]: if v!=p and sub[v]>nn/2: return dfs2(v,u) return u def decompose(root,p): global graph nn=0 dfs1(root,root) centroid=dfs2(root,root) if p==-1:p=centroid par[centroid]=p for v in graph[centroid]: graph[v].remove(centroid) decompose(v,centroid) graph[centroid]=[] #Handling the queries part! def update(u): global ans,par x=u while True: ans[x]=min(ans[x],dist(x,u)) if x==par[x]:break x=par[x] def query(u): global par,ans x=u;ret=float('inf') while True: ret = min(ret,dist(u,x)+ans[x]) if x==par[x]: break x=par[x] return ret n,m=map(int,input().split()) for i in range(n-1): a,b = map(int,input().split()) graph[a].append(b) graph[b].append(a) preprocess() decompose(1,-1) update(1) for i in range(m): t,v = map(int,input().split()); if t==1: update(v) else: print(query(v)) ``` No
3,696
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2 Submitted Solution: ``` n,m=map(int,input().split()) tr=[set() for i in range(n+1)] trr=[[] for i in range(n+1)] for _ in range(n-1): a,b=map(int,input().split()) trr[a].append(b);trr[b].append(a) tr[a].add(b);tr[b].add(a) euler=[] disc=[-1 for i in range(n+1)] hei=[-1 for i in range(n+1)] def eulerr(): q=[1] pa={1:-1} hei[1]=0 while q: x=q.pop() if disc[x]==-1:disc[x]=len(euler) euler.append(x) if len(trr[x])==0: if pa[x]!=-1:q.append(pa[x]) elif trr[x][-1]==pa[x]: trr[x].pop(-1) q.append(x) euler.pop() else: y=trr[x].pop(-1) pa[y]=x hei[y]=hei[x]+1 q.append(y) eulerr() st=[-1 for i in range(2*len(euler))] for i in range(len(euler)): st[i+len(euler)]=euler[i] for i in range(len(euler)-1,0,-1): if disc[st[i<<1]]<disc[st[i<<1|1]]: st[i]=st[i<<1] else: st[i]=st[i<<1|1] def dist(a,b): i=disc[a];j=disc[b] if i>j:i,j=j,i i+=len(euler);j+=len(euler)+1 ans=st[i] while i<j: if i&1: if disc[st[i]]<disc[ans]:ans=st[i] i+=1 if j&1: j-=1 if disc[st[j]]<disc[ans]:ans=st[j] i>>=1 j>>=1 return(hei[a]+hei[b]-2*hei[ans]) size=[0 for i in range(n+1)] def siz(i): pa={i:-1} q=[i] w=[] while q: x=q.pop() w.append(x) size[x]=1 for y in tr[x]: if y==pa[x]:continue pa[y]=x q.append(y) for j in range(len(w)-1,0,-1): x=w[j] size[pa[x]]+=size[x] return(size[i]) def centroid(i,nn): pa={i:-1} q=[i] while q: x=q.pop() for y in tr[x]: if y!=pa[x] and size[y]>nn//2: q.append(y) pa[y]=x break else:return(x) ct=[-1 for i in range(n+1)] def build(): q=[1] while q: x=q.pop() nn=siz(x) j=centroid(x,nn) ct[j]=ct[x] for y in tr[j]: tr[y].discard(j) ct[y]=j q.append(y) tr[j].clear() build() ps=[float("INF") for i in range(n+1)] ps[1]=0 x=1 while ct[x]!=-1: ps[ct[x]]=min(ct[x],dist(1,ct[x])) x=ct[x] for _ in range(m): t,x=map(int,input().split()) if t==1: ps[x]=0 v=x while ct[x]!=-1: ps[ct[x]]=min(ct[x],dist(v,ct[x])) x=ct[x] else: ans=ps[x] v=x while ct[x]!=-1: ans=min(ans,ps[ct[x]]+dist(v,ct[x])) x=ct[x] print(ans) ``` No
3,697
Provide tags and a correct Python 3 solution for this coding contest problem. You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong. Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks. Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one. Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible. Input The first line of the input contains two integers n, k (1 ≤ k ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103), where ai is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task. It is guaranteed that n is divisible by k. Output In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do. Examples Input 6 2 3 2 1 6 5 4 Output 1 Input 10 5 1 3 5 7 9 9 4 1 8 5 Output 3 Note Explanation of the first example. If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12. Explanation of the second example. In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3. Tags: brute force, implementation Correct Solution: ``` n,m = input().split() n =int(n) m = int(m) arr = [int(x) for x in input().split()] min = 1000000000000 ans= -1 for i in range(m): sum=0 for j in range(i,n,m): sum=sum+arr[j] if sum<min: min=sum ans=i print(ans+1) ```
3,698
Provide tags and a correct Python 3 solution for this coding contest problem. You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong. Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks. Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one. Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible. Input The first line of the input contains two integers n, k (1 ≤ k ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103), where ai is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task. It is guaranteed that n is divisible by k. Output In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do. Examples Input 6 2 3 2 1 6 5 4 Output 1 Input 10 5 1 3 5 7 9 9 4 1 8 5 Output 3 Note Explanation of the first example. If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12. Explanation of the second example. In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3. Tags: brute force, implementation Correct Solution: ``` n, k = map(int,input().split()) a = list(map(int,input().split())) ans = 10 ** 9 sol = -1 for i in range(k): x = n // k; y = i; tmp = 0 while(x): tmp += a[y] y += k y %= n x -= 1 if tmp < ans: ans = tmp sol = i + 1 print(sol); ```
3,699