message stringlengths 2 433k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 113 108k | cluster float64 12 12 | __index_level_0__ int64 226 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0. | instruction | 0 | 1,789 | 12 | 3,578 |
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
"""
3
41 -41 41
"""
def solve(n, a):
d = {0: -1}
s = 0 # εηΌε
res = 0
j = -1
for i in range(n):
s += a[i]
if (d.get(s) != None):
j = max(d[s] + 1, j)
d[s] = i
res += i - j
return res
def main():
n = int(input())
a = [int(x) for x in input().split()]
res = solve(n, a)
print(res)
main()
``` | output | 1 | 1,789 | 12 | 3,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0. | instruction | 0 | 1,790 | 12 | 3,580 |
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
def sumoflength(arr, n):
# For maintaining distinct elements.
s = set()
# Initialize ending point and result
j = 0
ans = 0
# Fix starting point
for i in range(n):
# Find ending point for current
# subarray with distinct elements.
while (j < n and (arr[j] not in s)):
s.add(arr[j])
j += 1
# Calculating and adding all possible
# length subarrays in arr[i..j]
ans += (j - i-1)
# Remove arr[i] as we pick new
# stating point from next
s.remove(arr[i])
return ans
n = int(input().strip())
numbers= list(map(int,input().strip().split()))
prefsum = [0 for i in range(n+1)]
prefsum[0] = 0
for q in range(1,n+1):
prefsum[q] = prefsum[q-1] + numbers[q-1]
print(sumoflength(prefsum,n+1))
``` | output | 1 | 1,790 | 12 | 3,581 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0. | instruction | 0 | 1,791 | 12 | 3,582 |
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
n=int(input())
a=[int(x) for x in input().split()]
for i in range(1,n):
a[i]+=a[i-1]
dic={}
dic[0]=0
ans=0
maximum=-1
for i in range(n):
val=dic.get(a[i],-1)
maximum=max(maximum,val)
ans+=i-maximum
dic[a[i]]=i+1
#print(dic,maximum,ans,i)
print(ans)
``` | output | 1 | 1,791 | 12 | 3,583 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0. | instruction | 0 | 1,792 | 12 | 3,584 |
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
n = int(input())
last = 0
o = {0: -1}
t = 0
rs = 0
a = [int(x) for x in input().split()]
for i, ai in enumerate(a):
rs += ai
if rs in o:
last = max(last, o[rs] + 2)
o[rs] = i
t += i - last + 1
print(t)
``` | output | 1 | 1,792 | 12 | 3,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0. | instruction | 0 | 1,793 | 12 | 3,586 |
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
n=int(input())
d={}
ar=list(map(int,input().split()))
pref=[0]*(n)
ans=0
d={}
uk=-1
pref[0]=ar[0]
d[0]=-1
for i in range(1,n):
pref[i]=pref[i-1]+ar[i]
for i in range(n):
if pref[i] in d:
uk=max(uk,d.get(pref[i])+1)
ans+=(i-uk)
d[pref[i]]=i
print(ans)
``` | output | 1 | 1,793 | 12 | 3,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0. | instruction | 0 | 1,794 | 12 | 3,588 |
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
def I(): return(list(map(int,input().split())))
def sieve(n):
a=[1]*n
for i in range(2,n):
if a[i]:
for j in range(i*i,n,i):
a[j]=0
return a
n=int(input())
arr=I()
l=-1
d={0:-1}
prefix=[0]*(n+1)
prefix[0]=arr[0]
ans=0
for i in range(1,n):prefix[i]=arr[i]+prefix[i-1]
for i in range(n):
l=max(l,d.get(prefix[i],l-1)+1)
d[prefix[i]]=i
ans+=i-l
print(ans)
``` | output | 1 | 1,794 | 12 | 3,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0. | instruction | 0 | 1,795 | 12 | 3,590 |
Tags: binary search, data structures, implementation, two pointers
Correct Solution:
```
from itertools import accumulate
n = int(input())
a = [int(x) for x in input().split()]
sums = [0] + list(accumulate(a))
s = {0}
i, j = 0, 0
ans = 0
while i < n:
while j < n and sums[j+1] not in s:
s.add(sums[j+1])
j += 1
ans += j - i
s.remove(sums[i])
i += 1
print(ans)
``` | output | 1 | 1,795 | 12 | 3,591 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
N = int(input())
D = {0: -1}
A = [int(a) for a in input().split()]
m = -1
s = 0
ans = 0
for i, a in enumerate(A):
if a == 0:
m = i
continue
s += a
if s not in D:
D[s] = i
ans += i - m
else:
m = max(m, D[s] + 1)
ans += i - m
D[s] = i
print(ans)
``` | instruction | 0 | 1,796 | 12 | 3,592 |
Yes | output | 1 | 1,796 | 12 | 3,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
import sys, math
input = sys.stdin.readline
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input().strip()
def listStr():
return list(input().strip())
import collections as col
import math,itertools
"""
For each element of the array, count right until it stops being a good subarray
Then start the next element at the right limit of the previous
"""
def solve():
N = getInt()
A = [0] + getInts()
P = []
curr_sum = 0
for a in A:
curr_sum += a
P.append(curr_sum)
right = 1
ans = 0
#print(P)
sums_seen = col.defaultdict(int)
#initially, the reference point is the first element
sums_seen[0] += 1
end = 1
for j in range(1,N+1):
#if anything matches the reference sum or a sum seen since, stop
#end slides as far right as possible for each j
while end < N+1 and sums_seen[P[end]] == 0:
sums_seen[P[end]] = 1
end += 1
#print(j,end,sums_seen)
ans += end-j
#we're only interested in the reference sums starting at each j, so we remove the earliest sum each time
sums_seen[P[j-1]] = 0
return ans
print(solve())
``` | instruction | 0 | 1,797 | 12 | 3,594 |
Yes | output | 1 | 1,797 | 12 | 3,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
from itertools import accumulate
def input(): return sys.stdin.readline().strip()
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 INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
N = INT()
A = LIST()
acc = [0] + list(accumulate(A))
D = {}
R = [N] * N
for i, a in enumerate(acc):
if a in D:
R[D[a]] = min(R[D[a]], i-1)
D[a] = i
for i in range(N-2, -1, -1):
R[i] = min(R[i], R[i+1])
ans = 0
for i in range(N):
ans += R[i] - i
print(ans)
``` | instruction | 0 | 1,798 | 12 | 3,596 |
Yes | output | 1 | 1,798 | 12 | 3,597 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
di = {}
di[0] = 0
ans = 0
total = 0
sub = -1
for i in range(n):
total += a[i]
if total in di:
sub = max(sub, di[total])
di[total] = i+1
ans += i-sub
print(ans)
``` | instruction | 0 | 1,799 | 12 | 3,598 |
Yes | output | 1 | 1,799 | 12 | 3,599 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
'''test=int(input())
for i in range(test):
n=int(input())
a=[int(j) for j in input().split()]
b=[int(k) for k in input().split()]
ans=""
if a[0]!=b[0]:
ans="NO"
else:
pos=0
neg=0
for i in range(n):
if a[i]>b[i] and not neg:
ans="NO"
break
elif a[i]<b[i] and not pos:
ans="NO"
break
else:
if a[i]==1:
pos+=1
elif a[i]==-1:
neg+=1
ans="YES"
print(ans)'''
n=int(input())
nums=[int(i) for i in input().split()]
from collections import defaultdict
hashmap=defaultdict(int)
sum_=0
ans=0
for i in range(n):
sum_+=nums[i]
if sum_ in hashmap:
ans+=(n-i)*hashmap[sum_]
hashmap[sum_]+=1
elif sum_ not in hashmap and not sum_:
ans+=n-i
hashmap[0]+=1
else:
hashmap[sum_]+=1
print(int(n*(n+1)/2-ans))
``` | instruction | 0 | 1,800 | 12 | 3,600 |
No | output | 1 | 1,800 | 12 | 3,601 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
n = int(input())
lis = list(map(int,input().split()))
pre=[0]*(n+1)
for i in range(1,n+1):
pre[i]=pre[i-1]+lis[i-1]
d={}
ans=l=0
for i in range(n+1):
if pre[i] not in d:
d[pre[i]]=i
else:
l=d[pre[i]]+1
d[pre[i]]=i
# print(i-l)
ans+=(i-l)
print(ans)
``` | instruction | 0 | 1,801 | 12 | 3,602 |
No | output | 1 | 1,801 | 12 | 3,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
n = int(input())
arr = [int(i) for i in input().split()]
dic = {0:-1}
ans = []
s = 0
for i in range(len(arr)):
s += arr[i]
if s in dic:
ans.append([dic[s]+1, i])
dic[s] = i
sm = 0
for i in range(len(ans)):
sm += (ans[i][0]+1)*(n-ans[i][1])
if i!= 0:
sm -= (min(ans[i-1][0]+1, ans[i][0]+1)*(min(n-ans[i][1], n-ans[i-1][1])))
print(((n*(n+1))//2) - sm)
``` | instruction | 0 | 1,802 | 12 | 3,604 |
No | output | 1 | 1,802 | 12 | 3,605 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugene likes working with arrays. And today he needs your help in solving one challenging task.
An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.
Help Eugene to calculate the number of nonempty good subarrays of a given array a.
Input
The first line of the input contains a single integer n (1 β€ n β€ 2 Γ 10^5) β the length of array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (-10^9 β€ a_i β€ 10^9) β the elements of a.
Output
Output a single integer β the number of good subarrays of a.
Examples
Input
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
Note
In the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.
In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0.
Submitted Solution:
```
# Python3 program to find the number of
# subarrays with sum exactly equal to k.
from collections import defaultdict
# Function to find number of subarrays
# with sum exactly equal to k.
def findSubarraySum(arr, n, Sum):
# Dictionary to store number of subarrays
# starting from index zero having
# particular value of sum.
prevSum = defaultdict(lambda : 0)
res = 0
# Sum of elements so far.
currsum = 0
used=-1
for i in range(0, n):
# Add current element to sum so far.
currsum += arr[i]
# If currsum is equal to desired sum,
# then a new subarray is found. So
# increase count of subarrays.
if currsum == Sum:
res += (n-i)
used=max(0,used)
# currsum exceeds given sum by currsum - sum.
# Find number of subarrays having
# this sum and exclude those subarrays
# from currsum by increasing count by
# same amount.
if (currsum - Sum) in prevSum:
index=prevSum[currsum-Sum]
if used<index:
res += (index+2)
used=index
# Add currsum value to count of
# different values of sum.
prevSum[currsum] = i
return res
# if __name__ == "__main__":
# arr = [10, 2, -2, -20, 10]
# Sum = -10
# n = len(arr)
# print(findSubarraySum(arr, n, Sum))
# This code is contributed by Rituraj Jain
n=int(input())
a=list(map(int,input().split()))
cnt=(n*(n+1))//2
print(cnt-findSubarraySum(a, n, 0))
``` | instruction | 0 | 1,803 | 12 | 3,606 |
No | output | 1 | 1,803 | 12 | 3,607 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture β formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.
For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.
Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i β [1, k], there should exist some j β [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.
Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.
Input
The first line contains two integers n and k (2 β€ n β€ 3 β
10^5, 1 β€ k β€ n - 1) β the number of topics and the number of special pairs of topics, respectively.
The second line contains n integers p_1, p_2, ..., p_n (0 β€ p_i β€ n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.
Then k lines follow, the i-th line contains two integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i) β the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.
Output
If there is no ordering of topics meeting all the constraints, print 0.
Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 β€ q_i β€ n) β the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.
Examples
Input
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4 | instruction | 0 | 1,853 | 12 | 3,706 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, implementation, sortings, trees
Correct Solution:
```
def main():
n, k = map(int, input().split())
p = [int(x)-1 for x in input().split()]
isHead = [True]*n
follower = [None]*n
for i in range(k):
x, y = map(int, input().split())
if follower[x-1] is not None:
print(0)
return
isHead[y-1] = False
follower[x-1] = y-1
head = [i for i in range(n)]
depth = [0]*n
for i in range(n):
if isHead[i]:
f = follower[i]
d = 1
while f is not None:
head[f] = i
depth[f] = d
d += 1
f = follower[f]
mergedParents = [[] for i in range(n)]
indegree = [0] * n
for i in range(n):
if p[i] != -1:
if head[i] != head[p[i]]:
mergedParents[head[i]].append(head[p[i]])
indegree[head[p[i]]] += 1
elif depth[i] < depth[p[i]]:
print(0)
return
stack = [i for i in range(n) if isHead[i] and indegree[i] == 0]
revList = []
while stack:
node = stack.pop()
revList.append(node)
for parent in mergedParents[node]:
indegree[parent] -= 1
if indegree[parent] == 0:
stack.append(parent)
if any(indegree[i] != 0 for i in range(n)):
print(0)
return
for a in revList[::-1]:
f = a
while f is not None:
print(f+1, end = " ")
f = follower[f]
main()
``` | output | 1 | 1,853 | 12 | 3,707 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture β formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.
For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.
Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i β [1, k], there should exist some j β [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.
Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.
Input
The first line contains two integers n and k (2 β€ n β€ 3 β
10^5, 1 β€ k β€ n - 1) β the number of topics and the number of special pairs of topics, respectively.
The second line contains n integers p_1, p_2, ..., p_n (0 β€ p_i β€ n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.
Then k lines follow, the i-th line contains two integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i) β the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.
Output
If there is no ordering of topics meeting all the constraints, print 0.
Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 β€ q_i β€ n) β the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.
Examples
Input
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4 | instruction | 0 | 1,854 | 12 | 3,708 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, implementation, sortings, trees
Correct Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
from collections import deque
input = sys.stdin.buffer.readline
N, K = map(int, input().split())
P = list(map(int, input().split()))
nxt = [-1] * (N+1)
prev = [-1] * (N+1)
adj = [[] for _ in range(N + 1)]
for _ in range(K):
x, y = map(int, input().split())
nxt[x] = y
prev[y] = x
adj[x].append(y)
for i, p in enumerate(P):
if p != 0:
adj[p].append(i+1)
for v in range(1, N+1):
r = v
r_list = [r]
while prev[r] != -1:
r = prev[r]
r_list.append(r)
if r == v:
print(0)
exit()
for u in r_list[:-1]:
prev[u] = r
for v in range(1, N+1):
if prev[v] != -1:
r = prev[v]
p = P[v-1]
if prev[p] != r and p != r:
adj[p].append(r)
in_num = [0] * (N+1)
for v in range(1, N+1):
for u in adj[v]:
in_num[u] += 1
st = []
for v in range(1, N+1):
if in_num[v] == 0:
st.append(v)
ans = []
seen = [0] * (N+1)
while st:
v = st.pop()
if seen[v]:
continue
else:
seen[v] = 1
ans.append(v)
for u in adj[v]:
in_num[u] -= 1
if in_num[u] == 0:
st.append(u)
if nxt[v] != -1:
if in_num[nxt[v]] != 0:
break
st.append(nxt[v])
#print(ans)
#print(adj)
if len(ans) != N:
print(0)
else:
print(*ans)
if __name__ == '__main__':
main()
``` | output | 1 | 1,854 | 12 | 3,709 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture β formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.
For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.
Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i β [1, k], there should exist some j β [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.
Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.
Input
The first line contains two integers n and k (2 β€ n β€ 3 β
10^5, 1 β€ k β€ n - 1) β the number of topics and the number of special pairs of topics, respectively.
The second line contains n integers p_1, p_2, ..., p_n (0 β€ p_i β€ n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.
Then k lines follow, the i-th line contains two integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i) β the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.
Output
If there is no ordering of topics meeting all the constraints, print 0.
Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 β€ q_i β€ n) β the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.
Examples
Input
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4 | instruction | 0 | 1,855 | 12 | 3,710 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, implementation, sortings, trees
Correct Solution:
```
from collections import defaultdict
def topological_sort(digraph):
n = len(digraph)
indegree = defaultdict(int)
for k in digraph:
for nxt_v in digraph[k]:
indegree[nxt_v] += 1
tp_order = [k for k in digraph if indegree[k] == 0]
stack = tp_order[:]
while stack:
v = stack.pop()
for nxt_v in digraph[v]:
indegree[nxt_v] -= 1
if indegree[nxt_v] == 0:
stack.append(nxt_v)
tp_order.append(nxt_v)
return len(tp_order) == n, tp_order
class UF:
def __init__(self, N):
self.par = list(range(N))
self.sz = [1] * N
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr:
return False
if self.sz[xr] < self.sz[yr]:
xr, yr = yr, xr
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
return True
def size(self, x):
return self.sz[self.find(x)]
def connected(self, x, y):
return self.find(x) == self.find(y)
def main():
n, k = map(int, input().split(' '))
p = list(map(lambda x: int(x) - 1, input().split(' ')))
pairs = {}
uf = UF(n)
pairs = [-1 for _ in range(n)]
starting_points = set([i for i in range(n)])
group_count = n
for _ in range(k):
x, y = map(int, input().split(' '))
x -= 1
y -= 1
if uf.find(x) != uf.find(y):
uf.union(x,y)
group_count -= 1
pairs[x] = y
starting_points.remove(y)
if len(starting_points) != group_count:
print(0)
return
group_ordering = {}
for sp in starting_points:
cur_group = uf.find(sp)
ordering = []
vis = set()
cur_node = sp
while cur_node != -1:
if cur_node in vis:
print(0)
return
vis.add(cur_node)
ordering.append(cur_node)
cur_node = pairs[cur_node]
group_ordering[cur_group] = ordering
# check that group ordering is valid
for group_num, ordering in group_ordering.items():
vis = set()
for node in ordering:
if uf.find(p[node]) == group_num:
if p[node] != -1 and p[node] not in vis:
print(0)
return
vis.add(node)
remap_idx = 0
d = {}
inverse_d = {}
for i in range(n):
cur_group = uf.find(i)
if cur_group not in d:
d[cur_group] = remap_idx
inverse_d[remap_idx] = cur_group
remap_idx += 1
graph = {}
for child, parent in enumerate(p):
child_group = uf.find(child)
if child_group not in graph:
graph[child_group] = []
if parent != -1:
parent_group = uf.find(parent)
if parent_group not in graph:
graph[parent_group] = []
if parent_group != child_group:
graph[parent_group].append(child_group)
valid, topo_sort = topological_sort(graph)
if valid:
ans = []
for group in topo_sort:
for node in group_ordering[group]:
ans.append(str(node+1))
print(" ".join(ans))
else:
print(0)
# region fastio
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")
# endregion
if __name__ == "__main__":
main()
``` | output | 1 | 1,855 | 12 | 3,711 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture β formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.
For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.
Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i β [1, k], there should exist some j β [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.
Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.
Input
The first line contains two integers n and k (2 β€ n β€ 3 β
10^5, 1 β€ k β€ n - 1) β the number of topics and the number of special pairs of topics, respectively.
The second line contains n integers p_1, p_2, ..., p_n (0 β€ p_i β€ n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.
Then k lines follow, the i-th line contains two integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i) β the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.
Output
If there is no ordering of topics meeting all the constraints, print 0.
Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 β€ q_i β€ n) β the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.
Examples
Input
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4 | instruction | 0 | 1,856 | 12 | 3,712 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, implementation, sortings, trees
Correct Solution:
```
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __repr__(self):
if not self:
return "{}()".format(self.__class__.__name__)
return "{}({})".format(self.__class__.__name__, self.value)
class LL:
def __init__(self, iterable=None):
self.sentinel = Node(None)
self.sentinel.next = self.sentinel
self.sentinel.prev = self.sentinel
self.__len = 0
if iterable is not None:
self += iterable
def get_node(self, index):
node = sentinel = self.sentinel
i = 0
while i <= index:
node = node.next
if node == sentinel:
break
i += 1
if node == sentinel:
node = None
return node
def __getitem__(self, index):
node = self.get_node(index)
return node.value
def __len__(self):
return self.__len
def __setitem__(self, index, value):
node = self.get_node(index)
node.value = value
def __delitem__(self, index):
node = self.get_node(index)
if node:
node.prev.next = node.next
if node.next:
node.next.prev = node.prev
node.prev = None
node.next = None
node.value = None
self.__len -= 1
def __repr__(self):
return str(self.to_list())
def to_list(self):
l = []
c = self.sentinel.next
while c != self.sentinel:
l.append(c.value)
c = c.next
return l
def append(self, value):
sentinel = self.sentinel
node = Node(value)
self.insert_between(node, sentinel.prev, sentinel)
def appendleft(self, value):
sentinel = self.sentinel
node = Node(value)
self.insert_between(node, sentinel, sentinel.next)
def insert(self, index, value):
sentinel = self.sentinel
new_node = Node(value)
len_ = len(self)
if len_ == 0:
self.insert_between(new_node, sentinel, sentinel)
elif index >= 0 and index < len_:
node = self.get_node(index)
self.insert_between(new_node, node.prev, node)
elif index == len_:
self.insert_between(new_node, sentinel.prev, sentinel)
else:
raise IndexError
self.__len += 1
def insert_between(self, node, left_node, right_node):
if node and left_node and right_node:
node.prev = left_node
node.next = right_node
left_node.next = node
right_node.prev = node
else:
raise IndexError
def merge_left(self, other):
sentinel = self.sentinel
sentinel.next.prev = other.sentinel.prev
other.sentinel.prev.next = sentinel.next
sentinel.next = other.sentinel.next
sentinel.next.prev = sentinel
def merge_right(self, other):
sentinel = self.sentinel
sentinel.prev.next = other.sentinel.next
other.sentinel.next.prev = sentinel.prev
sentinel.prev = other.sentinel.prev
sentinel.prev.next = sentinel
import sys,io,os
Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
Y=lambda:map(int,Z().split())
X=lambda:print(0)or quit()
from collections import deque
def path(R):
H=deque();H.append(R)
while P[R]>=0:
R=P[R];H.append(R)
if len(H)>2:P[H.popleft()]=H[-1]
return R
N,k=Y();p=[*Y()];K=[-1]*N;P=[-1]*(N//2);S=[1]*(N//2);ch=[];R=0
for _ in range(k):
a,b=Y();a-=1;b-=1
if K[a]>=0:
if K[b]>=0:
va,vb=path(K[a]),path(K[b])
if va!=vb:
sa,sb=S[va],S[vb]
if sa>sb:
P[vb]=va;ch[va].merge_right(ch[vb]);ch[vb]=0
else:
P[va]=vb;ch[vb].merge_left(ch[va]);ch[va]=0
if sa==sb:S[vb]+=1
else:X()
else:va=path(K[a]);K[b]=va;ch[va].append(b)
else:
if K[b]>=0:vb=path(K[b]);K[a]=vb;ch[vb].appendleft(a)
else:
K[a]=R;K[b]=R;R+=1
l=LL();l.append(a);l.append(b)
ch.append(l)
f=[[]for i in range(N)];x=[-1]*N;h=[0]*N;u=set()
for z in ch:
if z!=0:
c=z.sentinel.next;i=0
while c!=z.sentinel:x[c.value]=i;i+=1;c=c.next
for i in range(N):
a,b=p[i]-1,i;va,vb=a,b
if a<0:z=b;continue
if K[a]>=0:va=ch[path(K[a])][0]
if K[b]>=0:vb=ch[path(K[b])][0]
if va==vb:
if x[a]>x[b]:X()
else:
if(va,vb)not in u:f[va].append(vb);h[vb]+=1;u.add((va,vb))
q=[z];o=[];u=set()
while q:
v=q.pop()
if v in u:X()
u.add(v)
if x[v]>=0:o+=ch[path(K[v])].to_list()
else:o.append(v)
for i in f[v]:
h[i]-=1
if h[i]<1:q.append(i)
if len(o)<N:X()
print(' '.join(map(lambda i:str(i+1),o)))
``` | output | 1 | 1,856 | 12 | 3,713 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture β formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.
For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.
Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i β [1, k], there should exist some j β [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.
Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.
Input
The first line contains two integers n and k (2 β€ n β€ 3 β
10^5, 1 β€ k β€ n - 1) β the number of topics and the number of special pairs of topics, respectively.
The second line contains n integers p_1, p_2, ..., p_n (0 β€ p_i β€ n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.
Then k lines follow, the i-th line contains two integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i) β the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.
Output
If there is no ordering of topics meeting all the constraints, print 0.
Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 β€ q_i β€ n) β the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.
Examples
Input
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4 | instruction | 0 | 1,857 | 12 | 3,714 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, implementation, sortings, trees
Correct Solution:
```
from sys import stdin, gettrace
if gettrace():
def inputi():
return input()
else:
def input():
return next(stdin)[:-1]
def inputi():
return stdin.buffer.readline()
def main():
n,k = map(int, input().split())
pp = [int(a)-1 for a in input().split()]
chainhead = [True]*n
follower = [None]*n
for _ in range(k):
x, y = map(int, input().split())
if follower[x-1]:
print(0)
return
else:
follower[x-1] = y-1
chainhead[y-1] = False
chain = list(range(n))
cd = [0]*n
for i in range(n):
if chainhead[i]:
f = follower[i]
d = 1
while f != None:
cd[f] = d
d += 1
chain[f] = i
f = follower[f]
chainparents = [[] for _ in range(n)]
ccount = [0]*n
for i in range(n):
if pp[i] != -1:
if chain[i] != chain[pp[i]]:
chainparents[chain[i]].append(chain[pp[i]])
ccount[chain[pp[i]]] += 1
elif cd[pp[i]] > cd[i]:
print(0)
return
s = [i for i in range(n) if chainhead[i] and ccount[i] == 0]
l = []
while s:
v = s.pop()
l.append(v)
for p in chainparents[v]:
ccount[p] -= 1
if ccount[p] == 0:
s.append(p)
if any(ccount[i] != 0 for i in range(n)):
print(0)
return
res = []
for h in l[::-1]:
c = h
while c != None:
res.append(c+1)
c = follower[c]
print(' '.join(map(str, res)))
if __name__ == "__main__":
main()
``` | output | 1 | 1,857 | 12 | 3,715 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture β formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.
For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.
Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i β [1, k], there should exist some j β [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.
Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.
Input
The first line contains two integers n and k (2 β€ n β€ 3 β
10^5, 1 β€ k β€ n - 1) β the number of topics and the number of special pairs of topics, respectively.
The second line contains n integers p_1, p_2, ..., p_n (0 β€ p_i β€ n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.
Then k lines follow, the i-th line contains two integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i) β the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.
Output
If there is no ordering of topics meeting all the constraints, print 0.
Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 β€ q_i β€ n) β the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.
Examples
Input
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4 | instruction | 0 | 1,858 | 12 | 3,716 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, implementation, sortings, trees
Correct Solution:
```
import sys
from collections import deque
input = sys.stdin.readline
N,K = map(int,input().split())
p = list(map(int,input().split()))
p = [p[i]-1 for i in range(N)]
next = [-1 for i in range(N)]
deg = [0 for i in range(N)]
for _ in range(K):
x,y = map(int,input().split())
next[x-1] = y-1
deg[y-1] += 1
group = [-1 for i in range(N)]
deq = []
for v in range(N):
if not deg[v]:
deq.append(v)
group[v] = v
deq = deque([v for v in range(N) if not deg[v]])
order = [0 for i in range(N)]
while deq:
v = deq.popleft()
nv = next[v]
if nv!=-1:
deg[nv] -= 1
if deg[nv]==0:
deq.append(nv)
order[nv] = order[v] + 1
group[nv] = group[v]
for i in range(N):
if group[i]==-1:
exit(print(0))
deg = [0 for i in range(N)]
out = [[] for i in range(N)]
for i in range(N):
g = group[i]
if p[i]==-1:
continue
pre = group[p[i]]
if g!=pre:
out[pre].append(g)
deg[g] += 1
else:
if order[p[i]] > order[i]:
exit(print(0))
deq = deque([v for v in range(N) if not deg[v]])
res = []
while deq:
v = deq.popleft()
res.append(v)
for nv in out[v]:
deg[nv] -= 1
if not deg[nv]:
deq.append(nv)
if len(res)!=N:
exit(print(0))
ans = []
for v in res:
if group[v]==v:
pos = v
while pos!=-1:
ans.append(pos+1)
pos = next[pos]
print(*ans)
``` | output | 1 | 1,858 | 12 | 3,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture β formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.
For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.
Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i β [1, k], there should exist some j β [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.
Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.
Input
The first line contains two integers n and k (2 β€ n β€ 3 β
10^5, 1 β€ k β€ n - 1) β the number of topics and the number of special pairs of topics, respectively.
The second line contains n integers p_1, p_2, ..., p_n (0 β€ p_i β€ n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.
Then k lines follow, the i-th line contains two integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i) β the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.
Output
If there is no ordering of topics meeting all the constraints, print 0.
Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 β€ q_i β€ n) β the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.
Examples
Input
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4 | instruction | 0 | 1,859 | 12 | 3,718 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, implementation, sortings, trees
Correct Solution:
```
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def output(*args):
sys.stdout.buffer.write(
('\n'.join(map(str, args)) + '\n').encode('utf-8')
)
class UnionFind(object):
__slots__ = ['nodes']
def __init__(self, n: int):
self.nodes = [-1] * n
def size(self, x: int) -> int:
return -self.nodes[self.find(x)]
def find(self, x: int) -> int:
if self.nodes[x] < 0:
return x
else:
self.nodes[x] = self.find(self.nodes[x])
return self.nodes[x]
def unite(self, x: int, y: int) -> bool:
root_x, root_y, nodes = self.find(x), self.find(y), self.nodes
if root_x != root_y:
if nodes[root_x] > nodes[root_y]:
root_x, root_y = root_y, root_x
nodes[root_x] += nodes[root_y]
nodes[root_y] = root_x
return root_x != root_y
def main():
from collections import defaultdict
n, k = map(int, input().split())
p = [0] + list(map(int, input().split()))
sp_pair = [tuple(map(int, input().split())) for _ in range(k)]
indeg, outdeg = [0] * (n + 1), [0] * (n + 1)
adj = [[] for _ in range(n + 1)]
sp_indeg, sp_outdeg = [0] * (n + 1), [0] * (n + 1)
sp_adj = [[] for _ in range(n + 1)]
uf = UnionFind(n + 1)
for u, v in sp_pair:
uf.unite(u, v)
sp_outdeg[u] += 1
sp_indeg[v] += 1
sp_adj[u].append(v)
if max(max(sp_indeg), max(sp_outdeg)) > 1:
print(0)
exit()
sp_component = defaultdict(list)
for i in range(1, n + 1):
sp_component[uf.find(i)].append(i)
root = -1
for v, u in enumerate(p[1:], start=1):
if u == 0:
root = uf.find(v)
continue
if uf.find(u) != uf.find(v):
u, v = uf.find(u), uf.find(v)
adj[u].append(v)
outdeg[u] += 1
indeg[v] += 1
else:
sp_adj[u].append(v)
sp_outdeg[u] += 1
sp_indeg[v] += 1
stack = [root]
ans = []
while stack:
v = stack.pop()
if len(sp_component[v]) > 1:
# decompress
sv = [u for u in sp_component[v] if sp_indeg[u] == 0]
if not sv:
print(0)
exit()
stack2 = [sv[0]]
while stack2:
sv = stack2.pop()
ans.append(sv)
for dest in sp_adj[sv]:
if sp_indeg[dest] == 0:
continue
sp_indeg[dest] -= 1
if sp_indeg[dest] == 0:
stack2.append(dest)
else:
ans.append(v)
for dest in adj[v]:
if indeg[dest] == 0:
continue
indeg[dest] -= 1
if indeg[dest] == 0:
stack.append(dest)
if len(ans) == n:
output(' '.join(map(str, ans)))
else:
print(0)
if __name__ == '__main__':
main()
``` | output | 1 | 1,859 | 12 | 3,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan is a programming teacher. During the academic year, he plans to give n lectures on n different topics. Each topic should be used in exactly one lecture. Ivan wants to choose which topic will he explain during the 1-st, 2-nd, ..., n-th lecture β formally, he wants to choose some permutation of integers from 1 to n (let's call this permutation q). q_i is the index of the topic Ivan will explain during the i-th lecture.
For each topic (except exactly one), there exists a prerequisite topic (for the topic i, the prerequisite topic is p_i). Ivan cannot give a lecture on a topic before giving a lecture on its prerequisite topic. There exists at least one valid ordering of topics according to these prerequisite constraints.
Ordering the topics correctly can help students understand the lectures better. Ivan has k special pairs of topics (x_i, y_i) such that he knows that the students will understand the y_i-th topic better if the lecture on it is conducted right after the lecture on the x_i-th topic. Ivan wants to satisfy the constraints on every such pair, that is, for every i β [1, k], there should exist some j β [1, n - 1] such that q_j = x_i and q_{j + 1} = y_i.
Now Ivan wants to know if there exists an ordering of topics that satisfies all these constraints, and if at least one exists, find any of them.
Input
The first line contains two integers n and k (2 β€ n β€ 3 β
10^5, 1 β€ k β€ n - 1) β the number of topics and the number of special pairs of topics, respectively.
The second line contains n integers p_1, p_2, ..., p_n (0 β€ p_i β€ n), where p_i is the prerequisite topic for the topic i (or p_i = 0 if the i-th topic has no prerequisite topics). Exactly one of these integers is 0. At least one ordering of topics such that for every i the p_i-th topic is placed before the i-th topic exists.
Then k lines follow, the i-th line contains two integers x_i and y_i (1 β€ x_i, y_i β€ n; x_i β y_i) β the topics from the i-th special pair. All values of x_i are pairwise distinct; similarly, all valus of y_i are pairwise distinct.
Output
If there is no ordering of topics meeting all the constraints, print 0.
Otherwise, print n pairwise distinct integers q_1, q_2, ..., q_n (1 β€ q_i β€ n) β the ordering of topics meeting all of the constraints. If there are multiple answers, print any of them.
Examples
Input
5 2
2 3 0 5 3
1 5
5 4
Output
3 2 1 5 4
Input
5 2
2 3 0 5 3
1 5
5 1
Output
0
Input
5 1
2 3 0 5 3
4 5
Output
0
Input
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
Output
3 5 2 1 4 | instruction | 0 | 1,860 | 12 | 3,720 |
Tags: constructive algorithms, dfs and similar, dsu, graphs, implementation, sortings, trees
Correct Solution:
```
from collections import defaultdict
def topological_sort(digraph):
n = len(digraph)
indegree = defaultdict(int)
for k in digraph:
for nxt_v in digraph[k]:
indegree[nxt_v] += 1
tp_order = [k for k in digraph if indegree[k] == 0]
stack = tp_order[:]
while stack:
v = stack.pop()
for nxt_v in digraph[v]:
indegree[nxt_v] -= 1
if indegree[nxt_v] == 0:
stack.append(nxt_v)
tp_order.append(nxt_v)
return len(tp_order) == n, tp_order
class UF:
def __init__(self, N):
self.par = list(range(N))
self.sz = [1] * N
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr:
return False
if self.sz[xr] < self.sz[yr]:
xr, yr = yr, xr
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
return True
def size(self, x):
return self.sz[self.find(x)]
def connected(self, x, y):
return self.find(x) == self.find(y)
def main():
n, k = map(int, input().split(' '))
p = list(map(lambda x: int(x) - 1, input().split(' ')))
pairs = {}
uf = UF(n)
pairs = [-1 for _ in range(n)]
starting_points = set([i for i in range(n)])
group_count = n
for _ in range(k):
x, y = map(int, input().split(' '))
x -= 1
y -= 1
if uf.find(x) != uf.find(y):
uf.union(x,y)
group_count -= 1
pairs[x] = y
starting_points.remove(y)
if len(starting_points) != group_count:
print(0)
return
group_ordering = {}
for sp in starting_points:
cur_group = uf.find(sp)
ordering = []
vis = set()
cur_node = sp
while cur_node != -1:
if cur_node in vis:
print(0)
return
vis.add(cur_node)
ordering.append(cur_node)
cur_node = pairs[cur_node]
group_ordering[cur_group] = ordering
# check that group ordering is valid
for group_num, ordering in group_ordering.items():
vis = set()
for node in ordering:
if uf.find(p[node]) == group_num:
if p[node] != -1 and p[node] not in vis:
print(0)
return
vis.add(node)
graph = {}
for child, parent in enumerate(p):
child_group = uf.find(child)
if child_group not in graph:
graph[child_group] = []
if parent != -1:
parent_group = uf.find(parent)
if parent_group not in graph:
graph[parent_group] = []
if parent_group != child_group:
graph[parent_group].append(child_group)
valid, topo_sort = topological_sort(graph)
if valid:
ans = []
for group in topo_sort:
for node in group_ordering[group]:
ans.append(str(node+1))
print(" ".join(ans))
else:
print(0)
# region fastio
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")
# endregion
if __name__ == "__main__":
main()
``` | output | 1 | 1,860 | 12 | 3,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27. | instruction | 0 | 1,940 | 12 | 3,880 |
Tags: implementation, math, number theory
Correct Solution:
```
from sys import stdin
from itertools import accumulate
def arr_enu():
return [[i, int(x)] for i, x in enumerate(stdin.readline().split())]
def get_col(arr, i):
return [row[i] for row in arr]
def arr_sum(arr):
arr.insert(0, 0)
return list(accumulate(arr, lambda x, y: x + y))
def fun(x, y):
return int(x) * y[1]
n, a, s = int(stdin.readline()), arr_enu(), stdin.readline()
cum, cum2 = arr_sum(get_col(a, 1)), arr_sum(list(map(fun, s, a)))
ans = cum2[-1]
for i in range(n - 1, -1, -1):
if s[i] == '1':
ans = max(ans, cum[i] + (cum2[-1] - cum2[i + 1]))
print(ans)
``` | output | 1 | 1,940 | 12 | 3,881 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27. | instruction | 0 | 1,941 | 12 | 3,882 |
Tags: implementation, math, number theory
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
# n = int(input())
# dp = defaultdict(bool)
# n,m,k = map(int,input().split())
# l = []
#
# for i in range(n):
# la = list(map(int,input().split()))
# l.append(la)
# dp = defaultdict(int)
#
# for i in range(n):
# for j in range(m):
# for cnt in range(m//2-1,-1,-1):
# for rem in range(k):
# dp[(i,cnt+1,rem)] = max(dp[(i,cnt+1,rem)],dp[(i,cnt,rem)])
# dp[(i,cnt+1,(rem+l[i][j])%k)] = max(dp[(i,cnt+1,(rem+l[i][j])%k)],dp[(i,cnt,rem)]+l[i][j])
#
#
# print(dp[(n-1,m//2,0)])
#
#
# n,m = map(int,input().split())
#
# l = []
# for i in range(n):
# la = list(input())
# l.append(la)
# q = int(input())
# qu = []
# for i in range(q):
# a,b = map(str,input().split())
# qu.append([a,int(b)])
# ans = []
# row = [[] for i in range(n)]
# col = [[] for i in range(m)]
# # print(log2(26*10**5))
# for i in range(n):
# for j in range(m):
# if l[i][j] == '#':
#
#
# row[i].append(j)
# col[j].append(i)
#
#
#
# for i in range(n):
# for j in range(m):
#
# if l[i][j] != '.' and l[i][j]!='#':
# x,y = i,j
# flag = 0
#
#
# for a,b in qu:
#
# # z1 = bisect_right(row[x],y)
# # z2 = bisect_right(col[y],x)
#
# if a == 'N':
# z2 = bisect_right(col[y],x)
# x-=b
# if x>=n or y>=m or x<0 or y<0:
# flag = 1
#
# break
# if l[x][y] == '#':
# flag = 1
# break
# if col[y] == []:
# continue
# if z2 == len(col[y]):
#
# if x<=col[y][z2-1]:
# flag = 1
#
# break
#
# elif col[y][z2-1]<x<col[y][z2]:
#
# continue
# else:
# flag = 1
# break
#
#
# if a == 'S':
# z2 = bisect_right(col[y],x)
# x+=b
#
# if x>=n or y>=m or x<0 or y<0:
# flag = 1
#
# break
# if l[x][y] == '#':
# flag = 1
# break
# if col[y] == []:
# continue
# if z2 == len(col[y]):
# if x<=col[y][z2-1]:
# flag = 1
#
# break
#
# elif col[y][z2-1]<x<col[y][z2]:
# continue
# else:
# flag = 1
# break
#
# if a == 'E':
# z1 = bisect_right(row[x],y)
# y+=b
# # print(z1,y,row[x])
# if x>=n or y>=m or x<0 or y<0:
# flag = 1
# break
# if l[x][y] == '#':
# flag = 1
# if row[x] == []:
# continue
#
# if z1 == len(row[x]):
# if y<=row[x][z1-1]:
# flag = 1
#
# break
# elif row[x][z1-1]<y<row[x][z1]:
# continue
# else:
# flag = 1
# break
# if a == 'W':
# z1 = bisect_right(row[x],y)
# y-=b
#
# if x>=n or y>=m or x<0 or y<0:
# flag = 1
# break
# if l[x][y] == '#':
# flag = 1
# if row[x] == []:
# continue
# if z1 == len(row[x]):
# if y<=row[x][z1-1]:
# flag = 1
#
# break
# elif row[x][z1-1]<y<row[x][z1]:
# continue
# else:
# flag = 1
# break
#
#
#
#
#
# if flag == 0:
# ans.append(l[i][j])
# if ans!=[]:
# ans.sort()
# print(''.join(ans))
#
# else:
# print('no solution')
#
#
n = int(input())
l = list(map(int,input().split()))
l.reverse()
# print(l)
m = input()[::-1]
# print(m)
ans = 0
z = sum(l)
yo = 0
# print(m,l)
flag = 0
for i in range(n):
z-=l[i]
if m[i] == '1' :
ans = max(z+yo,ans)
yo+=l[i]
ans = max(z+yo,ans)
print(ans)
``` | output | 1 | 1,941 | 12 | 3,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. | instruction | 0 | 2,073 | 12 | 4,146 |
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
s = {} #dic
d = {} #dic
p = set() #set
mx = - 10**15
mi = -mx
ans = 2
for i in range(n) :
if a[i] in s :
s[a[i]] += 1
else :
s[a[i]] = 1
mx = max(mx,a[i])
mi = min(mi,a[i])
if 0 in s : ans = max(ans,s[0])
for i in range(n) :
for j in range(n) :
if (j==i) or (a[i]==0 and a[j]==0) or ((a[i], a[j]) in p) : continue
f0 = a[i]; f1 = a[j]; ansi = 2; f2 = 0;
d = {}
p.add((a[i], a[j]))
while True :
f2 = f1 + f0
f0 = f1
f1 = f2
if (f2 > mx) or (f2 < mi) : break
if f2 in s :
d[f2] = s[f2]
else : break
f0 = a[i]; f1 = a[j];
if f1==f0 :
d[f0] = s[f0] - 2
else :
d[f0] = s[f0] - 1
d[f1] = s[f1] - 1
while True :
f2 = f1 + f0
f0 = f1
f1 = f2
if (f2 > mx) or (f2 < mi) : break
if (f2 in d) and (d[f2] > 0) :
ansi += 1
d[f2] -= 1
else : break
ans = max(ans, ansi)
print(ans)
``` | output | 1 | 2,073 | 12 | 4,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. | instruction | 0 | 2,074 | 12 | 4,148 |
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
D = {}
for x in a:
if x in D:
D[x] += 1
else:
D[x] = 1
maxans = 0
def check(x, y):
num = 2
D[x] -= 1
D[y] -= 1
while x+y in D and D[x+y] > 0:
D[x+y] -= 1
x, y = y, x+y
num += 1
ans = num
while num > 2:
D[y] += 1
x, y = y-x, x
num -= 1
D[x] += 1
D[y] += 1
return ans
for x in D:
for y in D:
if x == y and D[x] == 1: continue
maxans = max(check(x, y), maxans)
print(maxans)
``` | output | 1 | 2,074 | 12 | 4,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. | instruction | 0 | 2,075 | 12 | 4,150 |
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
def rec(a, b):
res, c = 0, a + b
if d.get(c) and d[c] > 0:
d[c] -= 1
res = rec(b, c) + 1
d[c] += 1
return res
input()
d = {}
for i in map(int, input().split()):
if d.get(i):
d[i] += 1
else:
d[i] = 1
ans = 2
for a in d:
for b in d:
if a != b or d[a] > 1:
d[a] -= 1
d[b] -= 1
cnt = rec(a, b) + 2
d[a] += 1
d[b] += 1
ans = max(ans, cnt)
print(ans)
``` | output | 1 | 2,075 | 12 | 4,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. | instruction | 0 | 2,076 | 12 | 4,152 |
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
def go(a, b):
res, c = 0, a + b
if d.get(c) and d[c] > 0:
d[c] -= 1
res = go(b, c) + 1
d[c] += 1
return res
input()
d = {}
for i in map(int, input().split()):
if d.get(i): d[i] += 1
else: d[i] = 1
ans = 2
for a in d:
for b in d:
if a != b or d[a] > 1:
d[a] -= 1; d[b] -= 1
cnt = go(a, b) + 2
d[a] += 1; d[b] += 1
ans = max(cnt, ans)
print(ans)
``` | output | 1 | 2,076 | 12 | 4,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. | instruction | 0 | 2,077 | 12 | 4,154 |
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
from collections import Counter
input()
s = Counter(map(int, input().split()))
n = 0
for q in s:
s[q] -= 1
for a in s:
if not s[a]: continue
t = [a]
s[a] -= 1
b = q + a
while s.get(b, 0):
s[b] -= 1
t.append(b)
a, b = b, a + b
n = max(n, len(t))
for c in t: s[c] += 1
s[q] += 1
print(n + 1)
``` | output | 1 | 2,077 | 12 | 4,155 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. | instruction | 0 | 2,078 | 12 | 4,156 |
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
ans = a.count(0)
d = {}
for i in a:
if i not in d:
d[i] = 1
else:
d[i] += 1
ans = max(ans, 2)
for i in range(n):
for j in range(n):
if(i != j and (a[i] != 0 or a[j] != 0)):
first = a[i]
second = a[j]
temp = [first, second]
third = first + second
while(True):
if abs(third) > int(1e9):
break
if third not in d:
break
temp.append(third)
first = second
second = third
third = first + second
count = 0
f = 1
for k in range(len(temp)):
if d[temp[k]] > 0:
d[temp[k]] -= 1
count += 1
else:
f = 0
for j in range(k):
d[temp[j]] += 1
break
if f:
for k in temp:
d[k] += 1
ans = max(ans, count)
print(ans)
``` | output | 1 | 2,078 | 12 | 4,157 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. | instruction | 0 | 2,079 | 12 | 4,158 |
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
from copy import *
length=int(input())
arr=list(map(int,input().split()))
d=dict()
for i in arr:
d[i]=d.get(i,0)+1
ans=0
for i in range(len(arr)):
for j in range(len(arr)):
if i!=j:
if arr[i]==0 and arr[j]==0:
ans=max(ans,d[arr[i]])
else:
count=2
a=arr[i]
b=arr[j]
d[a]-=1
d[b]-=1
for k in range(100):
if d.get(a+b):
count+=1
d[a+b]-=1
c=a+b
a=b
b=c
else:
d[a]+=1
d[b]+=1
ans=max(ans,count)
break
y=count-2
while y>0:
c=b-a
d[c]=d.get(c,0)+1
b=a
a=c
y-=1
print(ans)
``` | output | 1 | 2,079 | 12 | 4,159 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28. | instruction | 0 | 2,080 | 12 | 4,160 |
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <=key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n=int(input())
l=list(map(int,input().split()))
cou= {}
for i in l:
if i in cou:
cou[i]+=1
else:
cou[i]=1
def find(x,y):
num = 2
cou[x] -= 1
cou[y] -= 1
while x + y in cou and cou[x + y] > 0:
cou[x + y] -= 1
x, y = y, x + y
num += 1
ans = num
while num > 2:
cou[y] += 1
x, y = y - x, x
num -= 1
cou[x] += 1
cou[y] += 1
return ans
ans=2
for x in cou:
for y in cou:
if x == y and cou[x] == 1: continue
ans = max(find(x, y), ans)
print(ans)
``` | output | 1 | 2,080 | 12 | 4,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
# [https://codeforces.com/contest/633/submission/16384934]
import sys, collections
sys.setrecursionlimit(10000)
d = collections.defaultdict(int)
def go(a, b):
res, c = 0, a + b
if d.get(c) and d[c] > 0:
d[c] -= 1
res = go(b, c) + 1
d[c] += 1
return res
input()
for i in map(int, input().split()):
d[i] += 1
ans = 2
for a in d:
for b in d:
if a != b or d[a] > 1:
d[a] -= 1; d[b] -= 1
cnt = go(a, b) + 2
d[a] += 1; d[b] += 1
ans = max(cnt, ans)
print(ans)
``` | instruction | 0 | 2,081 | 12 | 4,162 |
Yes | output | 1 | 2,081 | 12 | 4,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
def go(a,b):
ret,c=0,a+b
if d.get(c) and d[c]>0:
d[c]-=1
ret=go(b,c)+1
d[c]+=1
return ret
input()
d={}
for i in map(int,input().split()):
if d.get(i):d[i]+=1
else: d[i]=1
ans=2
for a in d:
for b in d:
if a!=b or d[a]>1:
d[a]-=1
d[b]-=1
temp=go(a,b)+2
ans=max(temp,ans)
d[a]+=1
d[b]+=1
print(ans)
``` | instruction | 0 | 2,082 | 12 | 4,164 |
Yes | output | 1 | 2,082 | 12 | 4,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
import random, math
from copy import deepcopy as dc
from bisect import bisect_left, bisect_right
from collections import Counter
# Function to call the actual solution
def solution(li):
ma = {}
for i in range(len(li)):
ma[li[i]] = ma.get(li[i], 0) + 1
# ma1 = dc(ma)
ans = 0
# li = list(set(li))
for i in range(len(li)):
for j in range(len(li)):
if i != j:
f0 = li[i]
f1 = li[j]
if f0 == 0 and f1 == 0:
ans = max(ans, ma[0])
continue
ma[f0] -= 1
ma[f1] -= 1
cur = 2
while True:
nxt = f0 + f1
if nxt in ma and ma[nxt] > 0:
f0 = f1 + 1 - 1
f1 = nxt + 1 - 1
ma[nxt] -= 1
cur += 1
else:
break
cur1 = 2
ma[f0] += 1
ma[f1] += 1
while cur1 < cur:
prev = f1 - f0
f1 = f0 + 1 - 1
f0 = prev + 1 - 1
ma[prev] += 1
cur1 += 1
ans = max(ans, cur)
return ans
# Function to take input
def input_test():
n = int(input())
li = list(map(int, input().strip().split(" ")))
out = solution(li)
print(out)
# Function to test my code
def test():
pass
input_test()
# test()
``` | instruction | 0 | 2,083 | 12 | 4,166 |
Yes | output | 1 | 2,083 | 12 | 4,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from collections import Counter
n = int(input())
s = Counter(map(int, input().split()))
n = 0
for q in s:
s[q] -= 1
for a in s:
if s[a]:
t = [a]
s[a] -= 1
b = q + a
while s.get(b, 0):
s[b] -= 1
t.append(b)
a, b = b, a + b
n = max(n, len(t))
for c in t:
s[c] += 1
s[q] += 1
print(n + 1)
``` | instruction | 0 | 2,084 | 12 | 4,168 |
Yes | output | 1 | 2,084 | 12 | 4,169 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
n=ni()
l=li()
d=Counter(l)
ans=0
for i in range(n):
d[l[i]]-=1
for j in range(n):
if i==j:
continue
if l[i]==0 and l[j]==0:
ans=max(ans,d[0]+1)
continue
d[l[j]]-=1
temp=2
prev=l[j]
curr=l[i]+l[j]
ans1=[]
while d[curr]:
temp+=1
d[curr]-=1
ans1.append(curr)
prev,curr=curr,prev+curr
ans=max(ans,temp)
for k in ans1:
d[k]+=1
d[l[j]]+=1
d[l[i]]+=1
pn(ans)
``` | instruction | 0 | 2,085 | 12 | 4,170 |
Yes | output | 1 | 2,085 | 12 | 4,171 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
n=ni()
l=li()
d=Counter(l)
ans=0
for i in range(n):
for j in range(n):
if i==j:
continue
if l[i]==0 and l[j]==0:
ans=max(ans,d[0])
continue
temp=2
prev=l[j]
curr=l[i]+l[j]
while d[curr]:
temp+=1
prev,curr=curr,prev+curr
ans=max(ans,temp)
pn(ans)
``` | instruction | 0 | 2,086 | 12 | 4,172 |
No | output | 1 | 2,086 | 12 | 4,173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from sys import stdin
n=int(stdin.readline().strip())
s=tuple(map(int,stdin.readline().strip().split()))
st=set(s)
ans=2
n=min(100,n)
for i in range(n):
for j in range(n):
if j==i:
continue
x=2
f1=s[j]
f2=s[j]+s[i]
while(f2 in st):
x+=1;
f3=f1;
f1=f2;
f2+=f3;
if(x>ans):
ans=x
print(ans)
``` | instruction | 0 | 2,087 | 12 | 4,174 |
No | output | 1 | 2,087 | 12 | 4,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from collections import Counter
n = int(input())
s = Counter(map(int, input().split()))
n = 0
for q in s:
s[q] -= 1
for a in s:
if s[a]:
t = [a]
s[a] -= 1
b = q + a
while s.get(b, 0):
s[b] -= 1
t.append(b)
a, b = b, a + b
n = max(n, len(t))
for c in t:
s[c] += 1
s[q] += 1
print(n)
``` | instruction | 0 | 2,088 | 12 | 4,176 |
No | output | 1 | 2,088 | 12 | 4,177 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
import random, math
from copy import deepcopy as dc
from bisect import bisect_left, bisect_right
from collections import Counter
# Function to call the actual solution
def solution(li):
ma = {}
for i in range(len(li)):
ma[li[i]] = ma.get(li[i], 0) + 1
# ma1 = dc(ma)
ans = 0
# li = list(set(li))
for i in range(len(li)):
for j in range(len(li)):
if i != j:
f0 = li[i]
f1 = li[j]
if f0 == 0 and f1 == 0:
ans = max(ans, ma[0]-2)
continue
ma[f0] -= 1
ma[f1] -= 1
cur = 2
while True:
nxt = f0 + f1
if nxt in ma and ma[nxt] > 0:
f0 = f1 + 1 - 1
f1 = nxt + 1 - 1
ma[nxt] -= 1
cur += 1
else:
break
cur1 = 2
ma[f0] += 1
ma[f1] += 1
while cur1 < cur:
prev = f1 - f0
f1 = f0 + 1 - 1
f0 = prev + 1 - 1
ma[prev] += 1
cur1 += 1
ans = max(ans, cur)
return ans
# Function to take input
def input_test():
n = int(input())
li = list(map(int, input().strip().split(" ")))
out = solution(li)
print(out)
# Function to test my code
def test():
pass
input_test()
# test()
``` | instruction | 0 | 2,089 | 12 | 4,178 |
No | output | 1 | 2,089 | 12 | 4,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n β₯ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1000) β the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| β€ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
n = int(input())
a = [int(i) for i in input().split()]
ans = a.count(0)
s = set(a)
for i in range(n):
for j in range(n):
if i == j or a[i] == a[j] == 0: continue
ln = 2
a1 = a[i]
a2 = a[j]
while (a1 + a2) in s and ln < 100:
a1, a2 = a2, a1 + a2
ln += 1
ans = max(ans, ln)
print(ans)
``` | instruction | 0 | 2,090 | 12 | 4,180 |
No | output | 1 | 2,090 | 12 | 4,181 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, β¦, x_{k-1}.
Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As a formal description of a says, a_0 = 0 and for all other i (1 β€ i β€ n) a_i = x_{(i-1)mod k} + a_{i-1}, where p mod q denotes the remainder of division p by q.
For example, if the x = [1, 2, 3] and n = 5, then:
* a_0 = 0,
* a_1 = x_{0mod 3}+a_0=x_0+0=1,
* a_2 = x_{1mod 3}+a_1=x_1+1=3,
* a_3 = x_{2mod 3}+a_2=x_2+3=6,
* a_4 = x_{3mod 3}+a_3=x_0+6=7,
* a_5 = x_{4mod 3}+a_4=x_1+7=9.
So, if the x = [1, 2, 3] and n = 5, then a = [0, 1, 3, 6, 7, 9].
Now the boy hopes that he will be able to restore x from a! Knowing that 1 β€ k β€ n, help him and find all possible values of k β possible lengths of the lost array.
Input
The first line contains exactly one integer n (1 β€ n β€ 1000) β the length of the array a, excluding the element a_0.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^6).
Note that a_0 is always 0 and is not given in the input.
Output
The first line of the output should contain one integer l denoting the number of correct lengths of the lost array.
The second line of the output should contain l integers β possible lengths of the lost array in increasing order.
Examples
Input
5
1 2 3 4 5
Output
5
1 2 3 4 5
Input
5
1 3 5 6 8
Output
2
3 5
Input
3
1 5 3
Output
1
3
Note
In the first example, any k is suitable, since a is an arithmetic progression.
Possible arrays x:
* [1]
* [1, 1]
* [1, 1, 1]
* [1, 1, 1, 1]
* [1, 1, 1, 1, 1]
In the second example, Bajtek's array can have three or five elements.
Possible arrays x:
* [1, 2, 2]
* [1, 2, 2, 1, 2]
For example, k = 4 is bad, since it leads to 6 + x_0 = 8 and 0 + x_0 = 1, which is an obvious contradiction.
In the third example, only k = n is good.
Array [1, 4, -2] satisfies the requirements.
Note that x_i may be negative. | instruction | 0 | 2,467 | 12 | 4,934 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
ks = []
for k in range(1,n+1):
x = [None]*k
curr = 0
test_fail=False
for i in range(n):
xi = a[i] - curr
if x[ i%k ] != None and x[i%k] != xi:
test_fail=True
break
elif x[i%k] == None:
x[i%k] = xi
else:
pass
curr = a[i]
if test_fail:
continue
else:
ks.append(str(k))
print(len(ks))
print(" ".join(ks))
``` | output | 1 | 2,467 | 12 | 4,935 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, β¦, x_{k-1}.
Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As a formal description of a says, a_0 = 0 and for all other i (1 β€ i β€ n) a_i = x_{(i-1)mod k} + a_{i-1}, where p mod q denotes the remainder of division p by q.
For example, if the x = [1, 2, 3] and n = 5, then:
* a_0 = 0,
* a_1 = x_{0mod 3}+a_0=x_0+0=1,
* a_2 = x_{1mod 3}+a_1=x_1+1=3,
* a_3 = x_{2mod 3}+a_2=x_2+3=6,
* a_4 = x_{3mod 3}+a_3=x_0+6=7,
* a_5 = x_{4mod 3}+a_4=x_1+7=9.
So, if the x = [1, 2, 3] and n = 5, then a = [0, 1, 3, 6, 7, 9].
Now the boy hopes that he will be able to restore x from a! Knowing that 1 β€ k β€ n, help him and find all possible values of k β possible lengths of the lost array.
Input
The first line contains exactly one integer n (1 β€ n β€ 1000) β the length of the array a, excluding the element a_0.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^6).
Note that a_0 is always 0 and is not given in the input.
Output
The first line of the output should contain one integer l denoting the number of correct lengths of the lost array.
The second line of the output should contain l integers β possible lengths of the lost array in increasing order.
Examples
Input
5
1 2 3 4 5
Output
5
1 2 3 4 5
Input
5
1 3 5 6 8
Output
2
3 5
Input
3
1 5 3
Output
1
3
Note
In the first example, any k is suitable, since a is an arithmetic progression.
Possible arrays x:
* [1]
* [1, 1]
* [1, 1, 1]
* [1, 1, 1, 1]
* [1, 1, 1, 1, 1]
In the second example, Bajtek's array can have three or five elements.
Possible arrays x:
* [1, 2, 2]
* [1, 2, 2, 1, 2]
For example, k = 4 is bad, since it leads to 6 + x_0 = 8 and 0 + x_0 = 1, which is an obvious contradiction.
In the third example, only k = n is good.
Array [1, 4, -2] satisfies the requirements.
Note that x_i may be negative. | instruction | 0 | 2,468 | 12 | 4,936 |
Tags: implementation
Correct Solution:
```
import sys
n = int(input())
a = [0] + [int(i) for i in input().split()]
a = [a[i+1] - a[i] for i in range(len(a)-1)]
ans = ''
cnt = 0
k = 1
while k<=n:
good = True
for j in range(k):
# print(k, j, set(a[j::k]))
if len(set(a[j::k]))>1:
good = False
break
if good:
ans += ' ' + str(k)
cnt += 1
k += 1
print(cnt)
print(ans[1:])
``` | output | 1 | 2,468 | 12 | 4,937 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, β¦, x_{k-1}.
Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As a formal description of a says, a_0 = 0 and for all other i (1 β€ i β€ n) a_i = x_{(i-1)mod k} + a_{i-1}, where p mod q denotes the remainder of division p by q.
For example, if the x = [1, 2, 3] and n = 5, then:
* a_0 = 0,
* a_1 = x_{0mod 3}+a_0=x_0+0=1,
* a_2 = x_{1mod 3}+a_1=x_1+1=3,
* a_3 = x_{2mod 3}+a_2=x_2+3=6,
* a_4 = x_{3mod 3}+a_3=x_0+6=7,
* a_5 = x_{4mod 3}+a_4=x_1+7=9.
So, if the x = [1, 2, 3] and n = 5, then a = [0, 1, 3, 6, 7, 9].
Now the boy hopes that he will be able to restore x from a! Knowing that 1 β€ k β€ n, help him and find all possible values of k β possible lengths of the lost array.
Input
The first line contains exactly one integer n (1 β€ n β€ 1000) β the length of the array a, excluding the element a_0.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^6).
Note that a_0 is always 0 and is not given in the input.
Output
The first line of the output should contain one integer l denoting the number of correct lengths of the lost array.
The second line of the output should contain l integers β possible lengths of the lost array in increasing order.
Examples
Input
5
1 2 3 4 5
Output
5
1 2 3 4 5
Input
5
1 3 5 6 8
Output
2
3 5
Input
3
1 5 3
Output
1
3
Note
In the first example, any k is suitable, since a is an arithmetic progression.
Possible arrays x:
* [1]
* [1, 1]
* [1, 1, 1]
* [1, 1, 1, 1]
* [1, 1, 1, 1, 1]
In the second example, Bajtek's array can have three or five elements.
Possible arrays x:
* [1, 2, 2]
* [1, 2, 2, 1, 2]
For example, k = 4 is bad, since it leads to 6 + x_0 = 8 and 0 + x_0 = 1, which is an obvious contradiction.
In the third example, only k = n is good.
Array [1, 4, -2] satisfies the requirements.
Note that x_i may be negative. | instruction | 0 | 2,469 | 12 | 4,938 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = [0] + [int(i) for i in input().split()]
x = []
for ind, a_i in enumerate(a[1:]):
x.append(a_i - a[ind])
# print(x)
ans = []
for i in range(1, n + 1):
flag = 0
for ind, j in enumerate(x):
if x[ind % i] == j:
continue
else:
flag = 1
break
if flag == 0:
ans.append(i)
print(len(ans))
print(*ans)
``` | output | 1 | 2,469 | 12 | 4,939 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, β¦, x_{k-1}.
Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As a formal description of a says, a_0 = 0 and for all other i (1 β€ i β€ n) a_i = x_{(i-1)mod k} + a_{i-1}, where p mod q denotes the remainder of division p by q.
For example, if the x = [1, 2, 3] and n = 5, then:
* a_0 = 0,
* a_1 = x_{0mod 3}+a_0=x_0+0=1,
* a_2 = x_{1mod 3}+a_1=x_1+1=3,
* a_3 = x_{2mod 3}+a_2=x_2+3=6,
* a_4 = x_{3mod 3}+a_3=x_0+6=7,
* a_5 = x_{4mod 3}+a_4=x_1+7=9.
So, if the x = [1, 2, 3] and n = 5, then a = [0, 1, 3, 6, 7, 9].
Now the boy hopes that he will be able to restore x from a! Knowing that 1 β€ k β€ n, help him and find all possible values of k β possible lengths of the lost array.
Input
The first line contains exactly one integer n (1 β€ n β€ 1000) β the length of the array a, excluding the element a_0.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^6).
Note that a_0 is always 0 and is not given in the input.
Output
The first line of the output should contain one integer l denoting the number of correct lengths of the lost array.
The second line of the output should contain l integers β possible lengths of the lost array in increasing order.
Examples
Input
5
1 2 3 4 5
Output
5
1 2 3 4 5
Input
5
1 3 5 6 8
Output
2
3 5
Input
3
1 5 3
Output
1
3
Note
In the first example, any k is suitable, since a is an arithmetic progression.
Possible arrays x:
* [1]
* [1, 1]
* [1, 1, 1]
* [1, 1, 1, 1]
* [1, 1, 1, 1, 1]
In the second example, Bajtek's array can have three or five elements.
Possible arrays x:
* [1, 2, 2]
* [1, 2, 2, 1, 2]
For example, k = 4 is bad, since it leads to 6 + x_0 = 8 and 0 + x_0 = 1, which is an obvious contradiction.
In the third example, only k = n is good.
Array [1, 4, -2] satisfies the requirements.
Note that x_i may be negative. | instruction | 0 | 2,470 | 12 | 4,940 |
Tags: implementation
Correct Solution:
```
n=int(input())
l=list(map(int,input().split()))
l1=[l[0]]
for i in range(1,n) :
l1.append(l[i]-l[i-1])
otv=[]
for i in range(1,n+1) :
for j in range(n-1,-1,-1) :
if j-i<0 :
otv.append(i)
break
if l1[j]!=l1[j-i] :
break
print(len(otv))
print(*otv)
``` | output | 1 | 2,470 | 12 | 4,941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, β¦, x_{k-1}.
Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As a formal description of a says, a_0 = 0 and for all other i (1 β€ i β€ n) a_i = x_{(i-1)mod k} + a_{i-1}, where p mod q denotes the remainder of division p by q.
For example, if the x = [1, 2, 3] and n = 5, then:
* a_0 = 0,
* a_1 = x_{0mod 3}+a_0=x_0+0=1,
* a_2 = x_{1mod 3}+a_1=x_1+1=3,
* a_3 = x_{2mod 3}+a_2=x_2+3=6,
* a_4 = x_{3mod 3}+a_3=x_0+6=7,
* a_5 = x_{4mod 3}+a_4=x_1+7=9.
So, if the x = [1, 2, 3] and n = 5, then a = [0, 1, 3, 6, 7, 9].
Now the boy hopes that he will be able to restore x from a! Knowing that 1 β€ k β€ n, help him and find all possible values of k β possible lengths of the lost array.
Input
The first line contains exactly one integer n (1 β€ n β€ 1000) β the length of the array a, excluding the element a_0.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^6).
Note that a_0 is always 0 and is not given in the input.
Output
The first line of the output should contain one integer l denoting the number of correct lengths of the lost array.
The second line of the output should contain l integers β possible lengths of the lost array in increasing order.
Examples
Input
5
1 2 3 4 5
Output
5
1 2 3 4 5
Input
5
1 3 5 6 8
Output
2
3 5
Input
3
1 5 3
Output
1
3
Note
In the first example, any k is suitable, since a is an arithmetic progression.
Possible arrays x:
* [1]
* [1, 1]
* [1, 1, 1]
* [1, 1, 1, 1]
* [1, 1, 1, 1, 1]
In the second example, Bajtek's array can have three or five elements.
Possible arrays x:
* [1, 2, 2]
* [1, 2, 2, 1, 2]
For example, k = 4 is bad, since it leads to 6 + x_0 = 8 and 0 + x_0 = 1, which is an obvious contradiction.
In the third example, only k = n is good.
Array [1, 4, -2] satisfies the requirements.
Note that x_i may be negative. | instruction | 0 | 2,471 | 12 | 4,942 |
Tags: implementation
Correct Solution:
```
n=int(input())
l=list(map(int,input().split()))
a=[l[0]]
for i in range(1,n):
a.append(l[i]-l[i-1])
lens=[]
for i in range(n):
flag=False
for j in range(i+1,n):
if(a[j%(i+1)]!=a[j]):
flag=True
break
if flag==False:
lens.append(i+1)
print(len(lens))
for i in lens:
print(i,end=" ")
``` | output | 1 | 2,471 | 12 | 4,943 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, β¦, x_{k-1}.
Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As a formal description of a says, a_0 = 0 and for all other i (1 β€ i β€ n) a_i = x_{(i-1)mod k} + a_{i-1}, where p mod q denotes the remainder of division p by q.
For example, if the x = [1, 2, 3] and n = 5, then:
* a_0 = 0,
* a_1 = x_{0mod 3}+a_0=x_0+0=1,
* a_2 = x_{1mod 3}+a_1=x_1+1=3,
* a_3 = x_{2mod 3}+a_2=x_2+3=6,
* a_4 = x_{3mod 3}+a_3=x_0+6=7,
* a_5 = x_{4mod 3}+a_4=x_1+7=9.
So, if the x = [1, 2, 3] and n = 5, then a = [0, 1, 3, 6, 7, 9].
Now the boy hopes that he will be able to restore x from a! Knowing that 1 β€ k β€ n, help him and find all possible values of k β possible lengths of the lost array.
Input
The first line contains exactly one integer n (1 β€ n β€ 1000) β the length of the array a, excluding the element a_0.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^6).
Note that a_0 is always 0 and is not given in the input.
Output
The first line of the output should contain one integer l denoting the number of correct lengths of the lost array.
The second line of the output should contain l integers β possible lengths of the lost array in increasing order.
Examples
Input
5
1 2 3 4 5
Output
5
1 2 3 4 5
Input
5
1 3 5 6 8
Output
2
3 5
Input
3
1 5 3
Output
1
3
Note
In the first example, any k is suitable, since a is an arithmetic progression.
Possible arrays x:
* [1]
* [1, 1]
* [1, 1, 1]
* [1, 1, 1, 1]
* [1, 1, 1, 1, 1]
In the second example, Bajtek's array can have three or five elements.
Possible arrays x:
* [1, 2, 2]
* [1, 2, 2, 1, 2]
For example, k = 4 is bad, since it leads to 6 + x_0 = 8 and 0 + x_0 = 1, which is an obvious contradiction.
In the third example, only k = n is good.
Array [1, 4, -2] satisfies the requirements.
Note that x_i may be negative. | instruction | 0 | 2,472 | 12 | 4,944 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = [*map(int,input().split())]
for i in range(n-1,0,-1): a[i] -= a[i-1];
r = [i for i in range(1,n+1) if a[i:] == a[:-i]]
print(len(r))
print(*r)
``` | output | 1 | 2,472 | 12 | 4,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, β¦, x_{k-1}.
Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As a formal description of a says, a_0 = 0 and for all other i (1 β€ i β€ n) a_i = x_{(i-1)mod k} + a_{i-1}, where p mod q denotes the remainder of division p by q.
For example, if the x = [1, 2, 3] and n = 5, then:
* a_0 = 0,
* a_1 = x_{0mod 3}+a_0=x_0+0=1,
* a_2 = x_{1mod 3}+a_1=x_1+1=3,
* a_3 = x_{2mod 3}+a_2=x_2+3=6,
* a_4 = x_{3mod 3}+a_3=x_0+6=7,
* a_5 = x_{4mod 3}+a_4=x_1+7=9.
So, if the x = [1, 2, 3] and n = 5, then a = [0, 1, 3, 6, 7, 9].
Now the boy hopes that he will be able to restore x from a! Knowing that 1 β€ k β€ n, help him and find all possible values of k β possible lengths of the lost array.
Input
The first line contains exactly one integer n (1 β€ n β€ 1000) β the length of the array a, excluding the element a_0.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^6).
Note that a_0 is always 0 and is not given in the input.
Output
The first line of the output should contain one integer l denoting the number of correct lengths of the lost array.
The second line of the output should contain l integers β possible lengths of the lost array in increasing order.
Examples
Input
5
1 2 3 4 5
Output
5
1 2 3 4 5
Input
5
1 3 5 6 8
Output
2
3 5
Input
3
1 5 3
Output
1
3
Note
In the first example, any k is suitable, since a is an arithmetic progression.
Possible arrays x:
* [1]
* [1, 1]
* [1, 1, 1]
* [1, 1, 1, 1]
* [1, 1, 1, 1, 1]
In the second example, Bajtek's array can have three or five elements.
Possible arrays x:
* [1, 2, 2]
* [1, 2, 2, 1, 2]
For example, k = 4 is bad, since it leads to 6 + x_0 = 8 and 0 + x_0 = 1, which is an obvious contradiction.
In the third example, only k = n is good.
Array [1, 4, -2] satisfies the requirements.
Note that x_i may be negative. | instruction | 0 | 2,473 | 12 | 4,946 |
Tags: implementation
Correct Solution:
```
n = int(input())
x = 0
a = []
for y in map(int, input().split()):
a += y - x,
x = y
f = [-1] * (n + 1)
for i in range(1, n + 1):
f[i] = f[i - 1] + 1
while f[i] > 0 and a[i - 1] != a[f[i] - 1]:
f[i] = f[f[i] - 1] + 1
b = []
i = n
while i > 0:
b += n - f[i],
i = f[i]
print(len(b))
print(' '.join(map(str, b)))
``` | output | 1 | 2,473 | 12 | 4,947 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.