text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Tags: brute force, dp, implementation
Correct Solution:
```
n = int(input())
c = list(map(int, input().split()))
most = 0
tmp = 0
for i, num in enumerate(c):
if num >= c[i - 1] and i > 0:
tmp += 1
else:
if tmp > most:
most = tmp
tmp = 0
if tmp > most:
most = tmp
print(most+1)
```
| 93,100 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Tags: brute force, dp, implementation
Correct Solution:
```
n = int(input())
s = list(map(int, input().split(' ')))
m = 1
l = 1
for i in range(n-1):
if s[i] <= s[i+1]:
l += 1
m = max(l, m)
else:
m = max(l, m)
l = 1
print(m)
```
| 93,101 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Tags: brute force, dp, implementation
Correct Solution:
```
n=int(input())
s=list(map(int,input().split()))
number=[]
c=0
for i in range(n-1):
if s[i]<=s[i+1]:
c+=1
else:
number.append(c+1)
c=0
number.append(c+1)
if c+1==n:
print(c+1)
else:
result=sorted(number)
print(result[-1])
```
| 93,102 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Tags: brute force, dp, implementation
Correct Solution:
```
n = int(input())
a = [0] + [int(s) for s in input().split()]
dp = [0] * (n+2)
for i in range(1, n+1):
if a[i] >= a[i-1]:
dp[i] = dp[i-1] + 1
else:
dp[i] = 1
print(max(dp))
```
| 93,103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Tags: brute force, dp, implementation
Correct Solution:
```
n=input()
l=input().split()
count=1
ans=0
for i in range (0,int(n)-1):
if(int(l[i])<=int(l[i+1])):
count=count+1
else:
if(count>ans):
ans=count
count=1
print(max(ans,count))
```
| 93,104 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Tags: brute force, dp, implementation
Correct Solution:
```
n = int(input())
l = list(map(int, input().split()))
ans, cnt = 0, 1
for i in range(1, n):
if l[i] >= l[i - 1]: cnt -= -1
else:
ans = max(ans, cnt)
cnt = 1
ans = max(ans, cnt)
print(ans)
```
| 93,105 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Tags: brute force, dp, implementation
Correct Solution:
```
n = int(input())
a = list(map(int,input().split(' ')))
tmp = 1
max_tmp = 1
for i in range(n-1):
if a[i] <= a[i+1]:
tmp+=1
if tmp > max_tmp:
max_tmp = tmp
# print(a[i])
else:
tmp = 1
print(max_tmp)
```
| 93,106 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Submitted Solution:
```
n = int(input())
s = [int(i) for i in input().split()]
k, m = 1, 0
for i in range(n-1):
if s[i] <= s[i+1]:
k += 1
else:
if k > m:
m = k
k = 1
if k > m:
print(k)
else:
print(m)
```
Yes
| 93,107 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Submitted Solution:
```
t = int(input())
arr = [int(x) for x in input().split()]
count = 1
prev = 0
for i in range(1,t):
if arr[i-1] <= arr[i]:
count += 1
prev = max(prev, count)
else:
count = 1
print(max(prev,count))
```
Yes
| 93,108 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Submitted Solution:
```
n = int(input())
A = list(map(int, input().split()))
def crossLength(l, m, r):
count = 0
if A[m] > A[m + 1]:
return count
else:
count += 1
for i in range(m - l):
if A[m - i] >= A[m - i - 1]:
count += 1
else:
break
for i in range(r - m):
if A[m + i + 1] >= A[m + i]:
count += 1
else:
break
return count
def findSubsegmentLength(l, r):
if l == r:
return 1
m = (r + l) // 2
left_length = findSubsegmentLength(l, m)
right_length = findSubsegmentLength(m + 1, r)
mid_legth = crossLength(l, m, r)
return max(left_length, right_length, mid_legth)
print(findSubsegmentLength(0, len(A) - 1))
```
Yes
| 93,109 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Submitted Solution:
```
n = input()
max1,dem = 0,0
a =list(map(int, input().split()))
a.append(0)
for i in range(len(a)-1):
dem+=1
if a[i+1]<a[i]:
max1 = max(dem,max1)
dem=0
print(max1)
```
Yes
| 93,110 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
c=1
min=1
for i in range (n-1):
if l[i]>l[i+1]:
if c>=min:
min=c
c=1
else:
c+=1
if c>min:
min=c
print(min)
```
No
| 93,111 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Submitted Solution:
```
N = int(input())
arr = list(map(int,input().split()))
arr1 = [0]*N
temp = temp1 = 1
for i in range(N-1):
if arr[i] <= arr[i+1]:
temp = temp + 1
else:
print("hj")
if temp1 < temp:
print(temp1,temp)
temp1 = temp
temp = 1
if temp1 < temp:
temp1 = temp
print(temp1)
```
No
| 93,112 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Submitted Solution:
```
a = int(input())
b = list(map(int, input().split()))
c, m = 1, 1
for i in range(1, a):
if(b[i] > b[i-1]):
c = 1
else:
c = c+1
m = max(m, c)
print(m)
```
No
| 93,113 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 β€ i β€ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
Input
The first line contains integer n (1 β€ n β€ 105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print a single integer β the length of the maximum non-decreasing subsegment of sequence a.
Examples
Input
6
2 2 1 3 4 1
Output
3
Input
3
2 2 9
Output
3
Note
In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.
In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Submitted Solution:
```
n=int(input())
list=[int(x) for x in input().split()]
long=0
templ=1
if len(list)==1:
print(1)
else:
for i in range(n-1):
if list[i]<=list[i+1]:
templ +=1
long=max(long,templ)
else:
templ=1
print(long)
'''ANS1
n = int(input())
line = [int(x) for x in input().split()]
num = line[0]
length = [1]*n
for i in range(1,n):
if line[i]>=num:
length[i] = length[i-1]+1
num = line[i]
length.sort()
print(length[-1])
'''
'''ANS2
i=input;i()
c=m=s=0
for i in i().split():
i=int(i)
c=c+1 if i>=s else 1
m=max(m,c)
s=i
print(m)'''
```
No
| 93,114 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Tags: constructive algorithms, graphs
Correct Solution:
```
from collections import defaultdict,deque,Counter,OrderedDict
import sys
sys.setrecursionlimit(20000)
def main():
n,m = map(int,input().split())
adj = [[] for i in range(n+1)]
for i in range(m):
a,b = map(int,input().split())
a,b = a-1,b-1
adj[a].append(b)
adj[b].append(a)
ans = ["c"]*(n)
visited = [0]*(n)
for i in range(n):
if len(adj[i]) == n - 1:
visited[i] = 1
ans[i] = "b"
def dfs(s,c):
if visited[s]: return
visited[s],ans[s] = 1,c
for j in adj[s]:
dfs(j,c)
if "c" in ans:
st = ans.index("c")
dfs(st,"a")
if "c" in ans:
st = ans.index("c")
dfs(st,"c")
check,cnta,cntc,cntb = True,ans.count("a"),ans.count("c"),ans.count("b")
for i in range(n):
if ans[i] == "a":
check &= (len(adj[i])==cnta+cntb-1)
elif ans[i] == "c":
check &= (len(adj[i])==cntc+cntb-1)
if check:
print("Yes\n"+"".join(ans))
else:
print("No")
if __name__ == "__main__":
main()
```
| 93,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Tags: constructive algorithms, graphs
Correct Solution:
```
#!/usr/bin/python3
(n, m) = tuple(map(int, input().split()))
cnt = [0]*n
edges = []
for i in range(m):
(u, v) = tuple(map(int, input().split()))
edges.append((u, v))
cnt[u-1] += 1
cnt[v-1] += 1
edges = sorted(edges)
edge_set = set(edges)
A = set()
B = set()
C = set()
for i in range(n):
#print(A)
#print(B)
#print(C)
if cnt[i] == n-1:
B.add(i+1)
else:
in_A = True
in_C = True
for a in A:
if ((a, i+1) not in edge_set and (i+1, a) not in edge_set):
in_A = False
else:
in_C = False
for c in C:
if ((c, i+1) not in edge_set and (i+1, c) not in edge_set):
in_C = False
else:
in_A = False
if in_A == True and in_C == True: #?
A.add(i+1)
elif in_A == False and in_C == True:
C.add(i+1)
elif in_A == True and in_C == False:
A.add(i+1)
else:
print("No")
break
else:
print("Yes")
ans = ""
for i in range(1, n+1):
if i in A:
ans += 'a'
if i in B:
ans += 'b'
if i in C:
ans += 'c'
print(ans)
```
| 93,116 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Tags: constructive algorithms, graphs
Correct Solution:
```
edge=[[0 for _ in range(510)] for _ in range(510)]
cnt = [0]*510
s=[0]*510
n,m = map(int,input().split())
for _ in range(m):
u,v = map(int,input().split())
u-=1
v-=1
edge[u][v]=1
edge[v][u]=1
cnt[u]+=1
cnt[v]+=1
for i in range(n):
if(cnt[i]==n-1):s[i]='b'
for i in range(n):
if s[i]==0:
s[i]='a'
#print(i)
for j in range(n):
if s[j]==0:
#print(j)
#print(edge[i][j])
if edge[i][j]!=0:s[j]='a'
else:s[j]='c'
#print(s[j])
for i in range(n):
for j in range(n):
if i == j : continue
if (abs(ord(s[i])-ord(s[j])==2 and edge[i][j]==1))or(abs(ord(s[i])-ord(s[j]))<2 and edge[i][j]==0):print('No');exit()
print('Yes')
no = ''
for i in s:
if i == 0:break
no+=str(i)
print(no)
```
| 93,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Tags: constructive algorithms, graphs
Correct Solution:
```
def dfs(v, graph, used, str_arr, color=0):
used[v] = True
str_arr[v] = color
for u in graph[v]:
if used[u] and str_arr[u] == color:
return False
if not used[u] and not dfs(u, graph, used, str_arr, color ^ 1):
return False
return True
def main():
n, m = list(map(int, input().strip().split()))
graph_adj = [[0] * n for i in range(n)]
for i in range(m):
a, b = list(map(int, input().strip().split()))
a -= 1
b -= 1
graph_adj[a][b] = 1
graph_adj[b][a] = 1
arr_adj = [[] for i in range(n)]
for i in range(n):
for j in range(i + 1, n):
if graph_adj[i][j] == 0:
arr_adj[i].append(j)
arr_adj[j].append(i)
used = [False] * n
str_arr = [-1] * n
#print(arr_adj)
for i in range(n):
if not used[i] and len(arr_adj[i]) > 0:
if not dfs(i, arr_adj, used, str_arr):
print("No")
return
#print(str_arr)
for i in range(n):
if str_arr[i] == -1:
str_arr[i] = 'b'
elif str_arr[i] == 0:
str_arr[i] = 'a'
else:
str_arr[i] = 'c'
for i in range(n):
for j in range(i + 1, n):
if graph_adj[i][j] and (str_arr[i] == 'a' and str_arr[j] == 'c' or str_arr[i] == 'c' and str_arr[j] == 'a'):
print("No")
return
print("Yes")
print(''.join(str_arr))
main()
```
| 93,118 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Tags: constructive algorithms, graphs
Correct Solution:
```
color = [-1] * 510
vis = [0] * 510
def dfs(start):
vis[start] = 1
for i in g[start]:
if vis[i] == 0:
color[i] = 1 - color[start]
dfs(i)
if vis[i] != 0:
if (color[i] == color[start]):
print("No")
quit()
g = {}
for i in range(510):
g[i] = []
h = []
for i in range(510):
h.append([0] * 510)
cosas = []
a, b = map(int, input().split(' '))
for c in range(b):
d, e = map(int, input().split(' '))
h[d][e] = 1
h[e][d] = 1
cosas.append([d, e])
for i in range(1, a+1):
for j in range(1, a+1):
if h[i][j] != 1 and i != j:
g[i].append(j)
for i in range(1, a+1):
if (len(g[i]) == 0):
color[i] = -1
vis[i] = 1
if (vis[i] == 0):
color[i] = 0
dfs(i)
estrenga = ""
for i in range(1, a+1):
if color[i] == 0:
estrenga += 'a'
elif color[i] == 1:
estrenga += 'c'
else:
estrenga += 'b'
for i in cosas:
arra = [i[0], i[1]]
arrb = [estrenga[arra[0]-1], estrenga[arra[1]-1]]
arrb.sort()
if arrb[0] == 'a' and arrb[1] == 'c':
print("No")
quit()
print("Yes")
print(estrenga)
```
| 93,119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Tags: constructive algorithms, graphs
Correct Solution:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright Β© 2016 missingdays <missingdays@missingdays>
#
# Distributed under terms of the MIT license.
"""
"""
from string import ascii_lowercase
def indx(c):
global ascii_lowercase
return ascii_lowercase.index(c)
def read_list():
return [int(i) for i in input().split()]
def new_list(n):
return [0 for i in range(n)]
def new_matrix(n, m=0):
return [[0 for i in range(m)] for i in range(n)]
n, m = read_list()
n += 1
string = new_list(n)
v = new_matrix(n, n)
for i in range(m):
v1, v2 = read_list()
v[v1][v2] = True
v[v2][v1] = True
for i in range(1, n):
l = v[i].count(True)
if l == n-2:
string[i] = 'b'
for i in range(1, n):
if string[i]:
continue
string[i] = 'a'
for j in range(1, n):
if string[j]:
continue
if v[i][j] == True:
string[i] = 'a'
else:
string[i] = 'c'
for i in range(1, n):
for j in range(1, n):
if i == j:
continue
if (abs(indx(string[i])-indx(string[j])) == 2 and v[i][j]) or (abs(indx(string[i])-indx(string[j])) < 2 and not v[i][j]):
print("No")
exit()
print("Yes")
for i in range(1, n):
print(string[i], end="")
print()
```
| 93,120 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Tags: constructive algorithms, graphs
Correct Solution:
```
def dfs(v):
visit[v] = cnt
for u in vertex[v]:
if not visit[u] and u in challengers:
dfs(u)
n, m = map(int, input().split())
vertex = [[] for i in range(n + 1)]
challengers = set()
ans = [''] * (n + 1)
middle = set()
for i in range(m):
a, b = map(int, input().split())
vertex[a].append(b)
vertex[b].append(a)
for i in range(1, n + 1):
s = set(j for j in range(1, n + 1))
s.discard(i)
if s == set(vertex[i]):
ans[i] = 'b'
middle.add(i)
else:
challengers.add(i)
visit = [0] * (n + 1)
cnt = 0
for c in challengers:
if not visit[c]:
cnt += 1
dfs(c)
if cnt > 2 or cnt == 1:
print('No')
elif cnt == 2:
first = set()
second = set()
for i in range(1, n + 1):
if visit[i] == 1:
first.add(i)
elif visit[i] == 2:
second.add(i)
for c in first:
s = first
s.discard(c)
if set(vertex[c]) - middle != s:
print('No')
break
s.add(c)
else:
for c in first:
ans[c] = 'a'
for c in second:
s = second
s.discard(c)
if set(vertex[c]) - middle != s:
print('No')
break
s.add(c)
else:
for c in second:
ans[c] = 'c'
if not ans[1:].count(''):
print('Yes', ''.join(ans[1:]), sep = '\n')
```
| 93,121 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Tags: constructive algorithms, graphs
Correct Solution:
```
import collections
n, m = map(int, input().split())
ans, A, B, C = [''] * n, [], [], []
d = collections.defaultdict(list)
for i in range(m):
x, y = map(int, input().split())
d[y - 1].append(x - 1)
d[x - 1].append(y - 1)
for k, v in d.items(): #set 'b'
if len(v) == n - 1:
ans[k] = 'b'
B.append(k)
for i in range(n): #set 'a'
if ans[i] == '':
ans[i] = 'a'
A.append(i)
de = collections.deque()
de.append(i)
while(len(de) != 0):
cur = de.popleft()
for j in d[cur]:
if ans[j] == '':
ans[j] = 'a'
A.append(j)
de.append(j)
break
for i in range(n): #set 'c'
if ans[i] == '':
ans[i] = 'c'
C.append(i)
temp = sorted(A + B)
for i in A: #check 'a'
d[i].append(i)
if sorted(d[i]) != temp:
print('No')
exit(0)
temp = sorted(B + C)
for i in C:
d[i].append(i)
if sorted(d[i]) != temp:
print('No')
exit(0)
print('Yes')
print(''.join(ans))
```
| 93,122 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Submitted Solution:
```
#!/usr/bin/python3
(n, m) = tuple(map(int, input().split()))
cnt = [0]*n
edges = []
for i in range(m):
(u, v) = tuple(map(int, input().split()))
edges.append((u, v))
cnt[u-1] += 1
cnt[v-1] += 1
edge_set = set(edges)
A = set()
B = set()
C = set()
for i in range(n):
if cnt[i] == n-1:
B.add(i+1)
else:
in_A = True
in_C = True
for a in A:
if ((a, i+1) not in edge_set and (i+1, a) not in edge_set):
in_A = False
else:
in_C = False
for c in C:
if ((c, i+1) not in edge_set and (i+1, c) not in edge_set):
in_C = False
else:
in_A = False
if in_A == True and in_C == True:
A.add(i+1)
elif in_A == False and in_C == True:
C.add(i+1)
elif in_A == True and in_C == False:
A.add(i+1)
else:
print("No")
break
else:
print("Yes")
ans = ""
for i in range(1, n+1):
if i in A:
ans += 'a'
if i in B:
ans += 'b'
if i in C:
ans += 'c'
print(ans)
```
Yes
| 93,123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Submitted Solution:
```
edge=[[0 for _ in range(510)] for _ in range(510)]
cnt = [0]*510
s=[0]*510
n,m = map(int,input().split())
for _ in range(m):
u,v = map(int,input().split())
u-=1;v-=1
edge[u][v]=1;edge[v][u]=1
cnt[u]+=1;cnt[v]+=1
for i in range(n):
if(cnt[i]==n-1):s[i]='b'
for i in range(n):
if s[i]==0:
s[i]='a'
for j in range(n):
if s[j]==0:
if edge[i][j]!=0:s[j]='a'
else:s[j]='c'
for i in range(n):
for j in range(n):
if i == j : continue
if (abs(ord(s[i])-ord(s[j])==2 and edge[i][j]==1))or(abs(ord(s[i])-ord(s[j]))<2 and edge[i][j]==0):print('No');exit()
print('Yes')
print(''.join(s[:s.index(0)]))
```
Yes
| 93,124 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Submitted Solution:
```
f = lambda: map(int, input().split())
n, m = f()
p = [1 << i for i in range(n)]
for i in range(m):
x, y = f()
x -= 1
y -= 1
p[x] |= 1 << y
p[y] |= 1 << x
s = set(p)
b = (1 << n) - 1
t = {}
if b in s:
t[b] = 'b'
s.remove(b)
if len(s) == 2:
a, c = s
if a | c == b and bool(a & c) == (b in t):
t[a], t[c] = 'ac'
s.clear()
print('No' if s else 'Yes\n' + ''.join(map(t.get, p)))
# Made By Mostafa_Khaled
```
Yes
| 93,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Submitted Solution:
```
#!/usr/bin/python3
class StdIO:
def read_int(self):
return int(self.read_string())
def read_ints(self, sep=None):
return [int(i) for i in self.read_strings(sep)]
def read_float(self):
return float(self.read_string())
def read_floats(self, sep=None):
return [float(i) for i in self.read_strings(sep)]
def read_string(self):
return input()
def read_strings(self, sep=None):
return self.read_string().split(sep)
io = StdIO()
def dfs(adj, visited, v, word, c, component):
visited[v] = True
word[v] = c
component.append(v)
for u in adj[v]:
if not visited[u]:
dfs(adj, visited, u, word, c, component)
def main():
n, m = io.read_ints()
adj = [list() for i in range(n)]
for i in range(m):
u, v = io.read_ints()
u -= 1
v -= 1
adj[u].append(v)
adj[v].append(u)
word = [None]*n
visited = [False]*n
# print(adj)
# bs = set()
bs = 0
for v in range(n):
if len(adj[v]) == n-1:
# bs.add(v)
visited[v] = True
word[v] = 'b'
bs += 1
comp = 0
good = True
for v in range(n):
if not visited[v]:
comp += 1
if comp > 2:
good = False
break
component = []
dfs(adj, visited, v, word, ['a', 'c'][comp-1], component)
size = len(component)
good = True
for u in component:
if len(adj[u]) != size-1 + bs:
good = False
break
if not good:
break
if not good:
print('No')
return
print('Yes')
print(''.join(word))
if __name__ == '__main__':
main()
```
Yes
| 93,126 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Submitted Solution:
```
from collections import defaultdict,deque,Counter,OrderedDict
def main():
n,m = map(int,input().split())
adj = [[] for i in range(n+1)]
for i in range(m):
a,b = map(int,input().split())
adj[a].append(b)
adj[b].append(a)
ans = ["d"]*(n+1)
visited = [0] * (n + 1)
for i in range(1,n+1):
if len(adj[i]) == n-1:
visited[i] = 1
ans[i] = "b"
def dfs(st,ck):
if visited[st]: return
visited[st] = 1
ans[st] = ck
for i in adj[st]:
dfs(i,ck)
if "d" in ans[1:]:
st = ans.index("d",1)
dfs(st,"a")
if "d" in ans[1:]:
st = ans.index("d",1)
dfs(st,"c")
ans = ans[1:]
if "d" in ans:
print("No")
else:
print("Yes")
print("".join(ans))
if __name__ == "__main__":
main()
```
No
| 93,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Submitted Solution:
```
#!/usr/bin/python3
(n, m) = tuple(map(int, input().split()))
edges = []
for i in range(m):
(u, v) = tuple(map(int, input().split()))
edges.append((u, v))
edge_set = set(edges)
A = set()
B = set()
C = set()
for i in range(n):
nums = set(range(1, n+1))
for j in edges:
if j[0] == i+1:
nums.remove(j[1])
if j[1] == i+1:
nums.remove(j[0])
if len(nums) == 1 :
B.add(i+1)
else:
in_A = True
in_C = True
for a in A:
if ((a, i+1) not in edge_set):
in_A = False
else:
in_C = False
for c in C:
if ((c, i+1) not in edge_set):
in_C = False
else:
in_A = False
if in_A == True and in_C == True: #?
A.add(i+1)
elif in_A == False and in_C == True:
C.add(i+1)
elif in_A == True and in_C == False:
A.add(i+1)
else:
print("No")
break
else:
print("Yes")
ans = ""
for i in range(1, n+1):
if i in A:
ans += 'a'
if i in B:
ans += 'b'
if i in C:
ans += 'c'
print(ans)
```
No
| 93,128 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Submitted Solution:
```
#!/usr/bin/python3
(n, m) = tuple(map(int, input().split()))
edges = []
for i in range(m):
(u, v) = tuple(map(int, input().split()))
edges.append((u, v))
edge_set = set(edges)
A = set()
B = set()
C = set()
for i in range(n):
nums = set(range(1, n+1))
for j in edges:
if j[0] == i+1:
nums.remove(j[1])
if j[1] == i+1:
nums.remove(j[0])
if len(nums) == 1 :
B.add(i+1)
else:
if len(A) == 0 and len(C) == 0:
A.add(i+1)
elif len(A) == 0 and len(C) != 0:
for c in C:
if ((c, i+1) not in edge_set):
A.add(i+1)
break
else:
C.add(i+1)
elif len(A) != 0 and len(C) == 0:
for a in A:
if ((a, i+1) not in edge_set):
C.add(i+1)
break
else:
A.add(i+1)
else:
in_A = True
in_C = True
for a in A:
if ((a, i+1) not in edge_set):
in_A = False
for c in C:
if ((c, i+1) not in edge_set):
in_C = False
if in_A == False and in_C == True:
C.add(i+1)
elif in_A == True and in_C == False:
A.add(i+1)
else:
print("No")
break
else:
print("Yes")
ans = ""
for i in range(1, n+1):
if i in A:
ans += 'a'
if i in B:
ans += 'b'
if i in C:
ans += 'c'
print(ans)
```
No
| 93,129 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to n.
* For all pairs of vertices i and j, where i β j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not.
Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.
Input
The first line of the input contains two integers n and m <image> β the number of vertices and edges in the graph found by Petya, respectively.
Each of the next m lines contains two integers ui and vi (1 β€ ui, vi β€ n, ui β vi) β the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.
Output
In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.
If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.
Examples
Input
2 1
1 2
Output
Yes
aa
Input
4 3
1 2
1 3
1 4
Output
No
Note
In the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions.
In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Submitted Solution:
```
from collections import defaultdict,deque,Counter,OrderedDict
def main():
n,m = map(int,input().split())
adj = [[] for i in range(n+1)]
for i in range(m):
a,b = map(int,input().split())
adj[a].append(b)
adj[b].append(a)
ans = ["d"]*(n+1)
visited = [0] * (n + 1)
for i in range(1,n+1):
if len(adj[i]) == n-1:
visited[i] = 1
ans[i] = "b"
st = ans.index("d")
def dfs(st,ck):
if visited[st]: return
visited[st] = 1
ans[st] = ck
for i in adj[st]:
dfs(i,ck)
dfs(st,"a")
if "d" in ans:
st = ans.index("d")
dfs(st,"c")
if "d" in ans:
print("No")
else:
print("Yes")
print("".join(ans[1:]))
if __name__ == "__main__":
main()
```
No
| 93,130 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Tags: dp
Correct Solution:
```
n=int(input())
arr=[]
p=list(map(int,input().split()))
for i in range(n):
arr.append([10000,10000,10000,p[i]])
arr[0][0]=1
if(arr[0][3]==1 or arr[0][3]==3):
arr[0][1]=0
if(arr[0][3]==2 or arr[0][3]==3):
arr[0][2]=0
for i in range(1,n):
arr[i][0]=1+min(arr[i-1][0], arr[i-1][1], arr[i-1][2])
if(arr[i][3]==1 or arr[i][3]==3):
arr[i][1]=min(arr[i-1][0], arr[i-1][2])
if(arr[i][3]==2 or arr[i][3]==3):
arr[i][2]=min(arr[i-1][0], arr[i-1][1])
least=10000
for i in range(0,3):
least=min(least,arr[n-1][i])
print(least)
```
| 93,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Tags: dp
Correct Solution:
```
n = int(input())
x = [int(x) for x in input().split()]
x.append(-1)
rest = 0
if x[0] == 0:
rest = rest + 1
for i in range(1 , n):
if x[i] == 0:
rest = rest + 1
elif x[i] == 1 and x[i - 1] == 1:
rest = rest + 1
x[i] = 0
elif x[i] == 2 and x[i - 1] == 2:
rest = rest + 1
x[i] = 0
elif x[i] == 3:
if x[i - 1] == 1:
x[i] = 2
elif x[i - 1] == 2:
x[i] = 1
elif x[i - 1] == 0 and x[i + 1] == 2:
x[i] == 1
elif x[i - 1] == 0 and x[i + 1] == 1:
x[i] == 2
print(rest)
```
| 93,132 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Tags: dp
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
d = [[10 ** 6] * 3 for i in range(n)]
d[0][0] = 1
if a[0] & 1:
d[0][1] = 0
if a[0] & 2:
d[0][2] = 0
for i in range(1, n):
d[i][0] = min(d[i - 1]) + 1
if a[i] & 1:
d[i][1] = min(d[i - 1][0], d[i - 1][2])
if a[i] & 2:
d[i][2] = min(d[i - 1][0], d[i - 1][1])
print(min(d[-1]))
```
| 93,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Tags: dp
Correct Solution:
```
n = int(input())
l = list(map(int,input().split()))
if n == 1:
if l[0]==0:
print(1)
else:
print(0)
else:
dp = [[float('inf') for i in range(3)] for j in range(n)]
for i in range(n):
for j in range(3):
if i==0:
dp[i][0] = 1
if l[i] == 1:
dp[i][1] = 0
elif l[i]==2:
dp[i][2] = 0
elif l[i]==3:
dp[i][1] = 0
dp[i][2] = 0
else:
dp[i][0] = 1 + min(dp[i-1])
if l[i]==1:
dp[i][1] = min(dp[i-1][0],dp[i-1][2])
elif l[i]==2:
dp[i][2] = min(dp[i-1][0],dp[i-1][1])
elif l[i] == 3:
dp[i][1] = min(dp[i-1][0],dp[i-1][2])
dp[i][2] = min(dp[i-1][0],dp[i-1][1])
print(min(dp[-1]))
```
| 93,134 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Tags: dp
Correct Solution:
```
#not done yet
n = int(input())
alist = list(map(int, input().split()))
dp = [[101 for _ in range(4)] for _ in range(n+1)]
for i in range(4):
dp[0][i] = 0
for i in range(1,n+1):
dp[i][0] = min(dp[i-1][0], min(dp[i-1][1],dp[i-1][2]))+1
if alist[i-1] == 1:
dp[i][2] = min(dp[i-1][0], dp[i-1][1])
elif alist[i-1] == 2:
dp[i][1]=min(dp[i-1][0],dp[i-1][2])
elif alist[i-1] == 3:
dp[i][1]=min(dp[i-1][2],dp[i-1][0])
dp[i][2]=min(dp[i-1][1],dp[i-1][0])
print(min(dp[n][0],min(dp[n][1],dp[n][2])))
```
| 93,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Tags: dp
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
dp = [[0]*n for i in range(2)] #top = gym, bottom = contest, 1 = closed/rest
if a[0] == 0:
dp[0][0] = 1
dp[1][0] = 1
elif a[0] == 1:
dp[0][0] = 1
elif a[0] == 2:
dp[1][0] = 1
for i in range(1, n):
if a[i] == 0:
dp[0][i] = 1+min(dp[0][i-1], dp[1][i-1])
dp[1][i] = 1+min(dp[0][i-1], dp[1][i-1])
elif a[i] == 1:
dp[0][i] = 1+min(dp[0][i-1], dp[1][i-1])
dp[1][i] = dp[0][i-1]
elif a[i] == 2:
dp[0][i] = dp[1][i-1]
dp[1][i] = 1+min(dp[0][i-1], dp[1][i-1])
else:
dp[0][i] = dp[1][i-1]
dp[1][i] = dp[0][i-1]
print(min(dp[0][-1], dp[1][-1]))
```
| 93,136 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Tags: dp
Correct Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/698/A
n = int(input())
l_n = list(map(int, input().split()))
p = l_n[0]
t = 1 if p == 0 else 0
for i in range(1, n):
if l_n[i] == p and p != 3:
l_n[i] = 0
elif l_n[i] == 3 and p != 3:
l_n[i] -= p
if l_n[i] == 0:
t += 1
p = l_n[i]
print(t)
```
| 93,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Tags: dp
Correct Solution:
```
n = int(input())
ls = list(map(int, input().split()))
ary = [[0, 0, 0] for j in range(n + 1)]
# 1 for contest
# 2 for gym
for i in range(1, n+ 1):
ma = max(ary[i - 1])
ary[i][0] = ma
ary[i][1] = max(ary[i-1][0], ary[i-1][2]) + (ls[i-1] == 1 or ls[i-1] == 3)
ary[i][2] = max(ary[i-1][0], ary[i-1][1]) + (ls[i-1] == 2 or ls[i-1] == 3)
print(n - max(ary[-1]))
```
| 93,138 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Submitted Solution:
```
n = int(input())
a = list(map(int,input().split()))
memo = [[-1]*4 for i in range(n)]
def dp(i,prev):
if i == n:
return 0
if memo[i][prev] == -1:
memo[i][prev] = 1 + dp(i+1,0)
if a[i] == 1 or a[i] == 2:
if a[i] != prev:
memo[i][prev] = min(memo[i][prev],dp(i+1,a[i]))
elif a[i] == 3:
for x in range(1,3):
if x != prev:
memo[i][prev] = min(memo[i][prev],dp(i+1,x))
return memo[i][prev]
print(dp(0,0))
```
Yes
| 93,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Submitted Solution:
```
input()
l = list(map(int,input().split()))
r = 0
prev = 3
for i in l:
if (i == prev and prev != 3):
i = 0
elif (i == 3 and prev != 3):
i -= prev
if i == 0:
r = r + 1
prev = i
print(r)
```
Yes
| 93,140 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Submitted Solution:
```
# from sys import stdout
log = lambda *x: print(*x)
def cin(*fn, def_fn=str):
i,r = 0,[]
for c in input().split(' '):
r+=[(fn[i] if len(fn)>i else fn[0]) (c)]
i+=1
return r
INF = 1 << 33
def solve(a, n):
dp = []
for i in range(n+1):
dp += [[]]
for j in range(n+1):
dp[i] += [{1:0,10:0,11:0}]
for i in range(n, -1, -1):
for t in range(n-1, -1, -1):
for tf in [11, 10, 1]:
if i == n:
dp[i][t][tf] = i-t
continue
cc = (tf//10) and (a[i]==1 or a[i]==3)
cg = (tf%10) and (a[i]==2 or a[i]==3)
if not (cc or cg):
dp[i][t][tf] = dp[i+1][t][11]
continue
a1,a2=INF,INF
if cc: a1 = dp[i+1][t+1][1]
if cg: a2 = dp[i+1][t+1][10]
dp[i][t][tf] = min(a1, a2)
#}
#}
return min(dp[0][0][1], dp[0][0][10])
n, = cin(int)
a = cin(int)
log(solve(a, n))
```
Yes
| 93,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Submitted Solution:
```
# DEFINING SOME GOOD STUFF
from math import *
import threading
import sys
from collections import defaultdict
sys.setrecursionlimit(300000)
# threading.stack_size(10**5) # remember it cause mle
mod = 10 ** 9
inf = 10 ** 15
yes = 'YES'
no = 'NO'
# ------------------------------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")
# _______________________________________________________________#
def npr(n, r):
return factorial(n) // factorial(n - r) if n >= r else 0
def ncr(n, r):
return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0
def lower_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] >= num:
answer = middle
end = middle - 1
else:
start = middle + 1
return answer # min index where x is not less than num
def upper_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] <= num:
answer = middle
start = middle + 1
else:
end = middle - 1
return answer # max index where x is not greater than num
def abs(x):
return x if x >= 0 else -x
def binary_search(li, val):
# print(lb, ub, li)
ans = -1
lb = 0
ub = len(li) - 1
while (lb <= ub):
mid = (lb + ub) // 2
# print('mid is',mid, li[mid])
if li[mid] > val:
ub = mid - 1
elif val > li[mid]:
lb = mid + 1
else:
ans = mid # return index
break
return ans
def kadane(x): # maximum sum contiguous subarray
sum_so_far = 0
current_sum = 0
for i in x:
current_sum += i
if current_sum < 0:
current_sum = 0
else:
sum_so_far = max(sum_so_far, current_sum)
return sum_so_far
def pref(li):
pref_sum = [0]
for i in li:
pref_sum.append(pref_sum[-1] + i)
return pref_sum
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
li = []
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
for p in range(2, len(prime)):
if prime[p]:
li.append(p)
return li
def primefactors(n):
factors = []
while (n % 2 == 0):
factors.append(2)
n //= 2
for i in range(3, int(sqrt(n)) + 1, 2): # only odd factors left
while n % i == 0:
factors.append(i)
n //= i
if n > 2: # incase of prime
factors.append(n)
return factors
def prod(li):
ans = 1
for i in li:
ans *= i
return ans
def dist(a, b):
d = abs(a[1] - b[1]) + abs(a[2] - b[2])
return d
def power_of_n(x, n):
cnt = 0
while (x % n == 0):
cnt += 1
x //= n
return cnt
def check(u,r,d,l):
f = 1
if u == 0 or d == 0:
if l == n or r == n:
f = 0
# print('1')
if l == 0 or r == 0:
if d == n or u == n:
f = 0
# print('2')
if u == 0 and d == 0:
if l >= n-1 or r >= n-1:
f = 0
# print('3')
if l == 0 and r == 0:
if d >= n-1 or u >= n-1:
f = 0
# print(4)
return f
# _______________________________________________________________#
# def main():
for _ in range(1):
# for _ in range(int(input()) if True else 1):
n = int(input())
# n, u, r, d, l = map(int, input().split())
a = list(map(int, input().split()))
# b = list(map(int, input().split()))
# c = list(map(int, input().split()))
# s = list(input())
# s = input()
# t = input()
# c = list(map(int,input().split()))
# adj = graph(n,m)
dp = [[0, 0, 0]]*(n+1)
for i in range(1, n+1):
dp[i] = [min(dp[i-1]) + 1] + dp[i][1:]
# print(dp)
if a[i-1] == 0:
dp[i][1] = dp[i-1][1] + 1
dp[i][2] = dp[i-1][2] + 1
elif a[i-1] == 1:
dp[i][1] = min(dp[i - 1][0], dp[i-1][2])
dp[i][2] = dp[i - 1][2] + 1
elif a[i-1] == 2:
dp[i][1] = dp[i-1][1]+1
dp[i][2] = min(dp[i-1][0], dp[i-1][1])
else:
dp[i][1] = min(dp[i-1][0], dp[i-1][2])
dp[i][2] = min(dp[i-1][0], dp[i-1][1])
# print(dp)
print(min(dp[-1]))
'''
t = threading.Thread(target=main)
t.start()
t.join()
'''
```
Yes
| 93,142 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Submitted Solution:
```
z,zz=input,lambda:list(map(int,z().split()))
zzz=lambda:[int(i) for i in stdin.readline().split()]
szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz())
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac
def lcd(xnum1,xnum2):return (xnum1*xnum2//gcd(xnum1,xnum2))
def prime(x):
p=ceil(x**.5)+1
for i in range(2,p):
if (x%i==0 and x!=2) or x==0:return 0
return 1
def dfs(u,visit,graph):
visit[u]=True
for i in graph[u]:
if not visit[i]:
dfs(i,visit,graph)
###########################---Test-Case---#################################
"""
"""
###########################---START-CODING---##############################
n=int(z())
l=zzz()
cur=ans=0
for i in l:
if i==0:
cur=0
ans+=1
if i==1:
if cur in (0,1):
cur=2
else:
cur=0
ans+=1
if i==2:
if cur in(0,2):
cur=1
else:
ans+=1
cur=1
if i==3:
cur={0:0,1:2,2:1}[cur]
print(ans)
```
No
| 93,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Submitted Solution:
```
n = int(input())
mat = input().split()
flg = 0
res = 0
for i in mat:
if i == "0":
flg = 0
res +=1
elif i == "1":
if flg != 1: flg = 1
else: res+=1
elif i == "2":
if flg != -1: flg = -1
else: res+=1
elif i == "3":
if flg == 1: flg = -1
else: flg = 1
print(res)
```
No
| 93,144 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Submitted Solution:
```
n = int(input())
ls = list(map(int, input().split()))
from functools import lru_cache
@lru_cache(maxsize=None)
def f(i, last=''):
if i == n:
return 0
c = 0
for j in range(i, n):
if ls[j] == 0:
c += 1
last = ''
elif ls[j] == 1:
if last == 'contest':
c += 1
last = 'contest'
elif ls[j] == 2:
if last == 'gym':
c += 1
last = 'gym'
else:
if last == 'contest':
last = 'gym'
elif last == 'gym':
last = 'contest'
else:
return min(c + f(j + 1, 'contest'), c + f(j + 1, 'gym'))
return c
print(f(0))
```
No
| 93,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:
1. on this day the gym is closed and the contest is not carried out;
2. on this day the gym is closed and the contest is carried out;
3. on this day the gym is open and the contest is not carried out;
4. on this day the gym is open and the contest is carried out.
On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).
Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has β he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.
Input
The first line contains a positive integer n (1 β€ n β€ 100) β the number of days of Vasya's vacations.
The second line contains the sequence of integers a1, a2, ..., an (0 β€ ai β€ 3) separated by space, where:
* ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;
* ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;
* ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;
* ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.
Output
Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:
* to do sport on any two consecutive days,
* to write the contest on any two consecutive days.
Examples
Input
4
1 3 2 0
Output
2
Input
7
1 3 3 2 1 2 3
Output
0
Input
2
2 2
Output
1
Note
In the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.
In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.
In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
a.insert(0, 4)
vix = [0] * (n + 1)
for i in range(n):
if a[i] == 3:
a[i] = 3 - a[i - 1]
for m in range(1, n + 1):
if a[m] == a[m - 1]:
vix[m] += 1
a[m] = 0
elif a[m] == 0:
vix[m] += 1
vix[m] += vix[m - 1]
print(vix[-1])
```
No
| 93,146 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Tags: implementation
Correct Solution:
```
n=int(input())
l=list(map(int,input().split()))
if len(l)>1:
if l[-1]==15:
print('DOWN')
elif l[-1]==0:
print('UP')
elif l[-1]-l[-2]==1:
print('UP')
elif l[-1]-l[-2]==-1:
print('DOWN')
else:
print(-1)
else:
if l[-1]==15:
print('DOWN')
elif l[-1]==0:
print('UP')
else:
print(-1)
```
| 93,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split(" ")))
l = a.pop()
if l == 15:
print("DOWN")
elif l == 0:
print("UP")
else:
if n == 1:
print(-1)
else:
p = a.pop()
print("UP" if p < l else "DOWN")
```
| 93,148 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Tags: implementation
Correct Solution:
```
n = int(input())
d = list(map(int, input().split()))
if len(d) < 2:
if d[0] == 15:
print('DOWN')
elif d[0] == 0:
print('UP')
else:
print(-1)
else:
if d[-1] > d[-2]:
if d[-1] == 15:
print('DOWN')
else:
print('UP')
elif d[-1] == 0:
print('UP')
else:
print('DOWN')
```
| 93,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Tags: implementation
Correct Solution:
```
from sys import exit
n = int(input())
t = [int(x) for x in input().split()]
if n == 1:
if t[0] == 15:
print("DOWN")
elif t[0] == 0:
print("UP")
else:
print(-1)
exit()
if t[n-1] - t[n-2] > 0:
if t[n-1] == 15:
print("DOWN")
else:
print("UP")
elif t[n-1] - t[n-2] < 0:
if t[n-1] == 0:
print("UP")
else:
print("DOWN")
```
| 93,150 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Tags: implementation
Correct Solution:
```
l=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
input()
s=list(map(int,input().split()))
if(len(s)==1):
if(s[0]==15):
print("DOWN")
elif(s[0]==0):
print("UP")
else:
print("-1")
else:
a=s[len(s)-2]
b=s[len(s)-1]
if(a==1 and b==0):
print("UP")
elif(a==14 and b==15):
print("DOWN")
elif(b>a):
print("UP")
else:
print("DOWN")
```
| 93,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Tags: implementation
Correct Solution:
```
n = int(input())
days = [int(x) for x in input().split()]
up = True
if n == 1:
if days[0] == 0:
print("UP")
elif days[0] == 15:
print("DOWN")
else:
print(-1)
else:
yesterday = days[0]
for i in range (1, n):
today = days[i]
if today > yesterday:
up = True
else:
up = False
if today == 15 or today == 0:
up = not up
yesterday = today
if up:
print("UP")
else:
print("DOWN")
```
| 93,152 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Tags: implementation
Correct Solution:
```
n=int(input())
w=input().split()
w=list(w)
if n==1:
if w[-1]=='15':
print('DOWN')
elif w[-1]=='0':
print('UP')
else:
print('-1')
else:
if w[-1]=='15':
print('DOWN')
elif w[-1]=='0':
print('UP')
else:
if int(w[-1])<int(w[-2]):
print('DOWN')
elif int(w[-1])>int(w[-2]):
print('UP')
```
| 93,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Tags: implementation
Correct Solution:
```
n = int(input())
t = [int(i) for i in input().split()]
if n == 1 and t[n-1] != 0 and t[n-1] != 15:
print("-1")
if t[n-1] == 15:
print("DOWN")
if t[n-1] == 0:
print("UP")
if (t[n-1] > t[n-2]) and t[n-1] != 15:
print("UP")
if (t[n-1] < t[n-2]) and t[n-1] != 0:
print("DOWN")
```
| 93,154 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Submitted Solution:
```
n = int(input().strip())
arr = [int(x) for x in input().strip().split(' ')]
if n == 1:
if arr[0] == 0:
print('UP')
elif arr[0] == 15:
print('DOWN')
else:
print(-1)
else:
if arr[n-1] == 0:
print('UP')
elif arr[n-1] == 15:
print('DOWN')
else:
print('UP' if arr[n-1] > arr[n-2] else 'DOWN')
```
Yes
| 93,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Submitted Solution:
```
n = int(input())
l = list(map(int, input().rstrip().split(" ")))
if n ==1:
if l[0]==0:
print("UP")
elif l[0]==15:
print("DOWN")
else:
print(-1)
else:
if l[-1]==15:
print("DOWN")
elif l[-1]==0:
print("UP")
elif l[-1]-l[-2]<0:
print("DOWN")
else:
print("UP")
```
Yes
| 93,156 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Submitted Solution:
```
n = int(input())
a = input()
A = []
if a == '0' and n == 1:
print('UP')
elif a == '15' and n == 1:
print('DOWN')
elif n == 1 and a !='0' and a != '15':
print(-1)
else:
for i in a.split():
A.append(int(i))
if A[-1] == 0:
print('UP')
elif A[-1] == 15:
print('DOWN')
else:
if A[-1] > A[-2]:
print('UP')
elif A[-1] < A[-2]:
print('DOWN')
```
Yes
| 93,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Submitted Solution:
```
N = int(input())
X = list(int(I) for I in (input()).split(' '))
if X[-1]==15:
print("DOWN")
exit(0)
elif X[-1]==0:
print("UP")
exit(0)
else:
if len(X)==1:
print(-1)
exit(0)
else:
W = X[-1]-X[-2]
if W == 1:
print("UP")
exit(0)
else:
print("DOWN")
exit(0)
```
Yes
| 93,158 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Submitted Solution:
```
n=int(input())
a=input()
l=a.split(" ")
print(l)
l1=[]
for i in l:
l1.append(int(i))
print(l1)
e=-1
val=""
n1=l1[0]
for i in range(1,len(l1)):
if n1<l1[i]:
val="UP"
else:
val="DOWN"
n1=l1[i]
if len(l1)==1:
print(e)
else:
if n1==0:
val="UP"
elif n1==15:
val="DOWN"
print(val)
```
No
| 93,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Submitted Solution:
```
n = int(input())
d = list(map(int, input().split()))
if n == 1 and (d[0] != 15 or d[0] != 0):
print(-1)
elif d[-1] > d[-2] and d[-1] != 15:
print('UP')
else:
print('DOWN')
```
No
| 93,160 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
if a[-1] == 15:
print("UP")
elif a[-1] == 0:
print("DOWN")
elif n == 1:
print("-1")
else:
print("UP" if a[-2] < a[-1] else "DOWN")
```
No
| 93,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.
As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.
Input
The first line of the input contains a single integer n (1 β€ n β€ 92) β the number of consecutive days Vitya was watching the size of the visible part of the moon.
The second line contains n integers ai (0 β€ ai β€ 15) β Vitya's records.
It's guaranteed that the input data is consistent.
Output
If Vitya can be sure that the size of visible part of the moon on day n + 1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.
Examples
Input
5
3 4 5 6 7
Output
UP
Input
7
12 13 14 15 14 13 12
Output
DOWN
Input
1
8
Output
-1
Note
In the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".
In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".
In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
k=0
for i in range(len(a)-1):
if a[i]+1!=a[i+1]:k=k+1
if k==0 and len(a)>1:print('UP')
elif len(a) % 2==1 and len(a)>1:
b,p,s,l='',[],0,0
for i in range(int(len(a)/2)):
if (a[i]+1)!=a[i+1]:s=s+1
b=b+str(a[i])
print(b,s)
if s==0:
b=b+str(a[int(len(a)/2)])
for i in range(int(len(a)/2),len(a)-1):
if a[i]-1!=a[i+1]:l=l+1
p.append(a[i])
print(b,p,l)
if l==0:
p.append(a[len(a)-1])
print(p,1)
r=''
for i in range(len(p)-1,-1,-1):r=r+str(p[i])
print(r)
if r==b:print('DOWN')
else:print('-1')
```
No
| 93,162 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Tags: brute force, implementation, math, number theory
Correct Solution:
```
def solve(n, m, a):
if n == 0:
return 0, 1
if n == 1:
return a[0], 1
d = (a[1]-a[0]) % m
if d < 0: d += m
st = set(a)
cnt = 0
for v in a:
cnt += ((v + d) % m) in st
cnt = n-cnt
d = (d * pow(cnt, m-2, m)) % m
now = a[0]
while (now + m - d) % m in st:
now = (now + m - d) % m
for i in range(n):
if (now + i*d) % m not in st:
return -1, -1
return now, d
m, n = map(int, input().split())
a = list(map(int, input().split()))
if n * 2 > m:
st = set(a)
b = [i for i in range(m) if i not in st]
f, d = solve(len(b), m, b)
f = (f + d * (m-n)) % m
else:
f, d = solve(n, m, a)
if f < 0 or d < 0:
print(-1)
else:
print(f, d)
# Made By Mostafa_Khaled
```
| 93,163 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Tags: brute force, implementation, math, number theory
Correct Solution:
```
from collections import defaultdict
dic = defaultdict(int)
def pow_mod(a,b,c):
n = 1
m = a
v = b
if a == 1:
return 1
while v > 0:
if v%2 == 1:
n *= m%c
n %= c
m *= m
m %= c
v //= 2
return n%c
def pow(a,b):
n = 1
m = a
v = b
if a == 1:
return 1
while v > 0:
if v%2 == 1:
n *= m
m *= m
v //= 2
return n
def tonelli_shanks(a,p):
if a == 0:
return 0
q = p-1
s = 0
while q%2 == 0:
s += 1
q //= 2
z = 2
while pow_mod(z,(p-1)//2,p) != p-1:
z += 1
m = s
c = pow_mod(z,q,p)
t = pow_mod(a,q,p)
r = pow_mod(a,(q+1)//2,p)
while m > 1:
if pow_mod(t,pow(2,m-2),p) == 1:
c = c**2%p
m -= 1
else:
t = (c**2%p)*t%p
r = c*r%p
c = c**2%p
m -= 1
return r%p
m,n = map(int, input().split())
a = list(map(int, input().split()))
for i in a:
dic[i] += 1
if n == 1:
d = 0
x = a[0]
print(x,d)
elif n == m-1:
d = 1
a.sort()
if a[0] != (a[-1]+d)%m:
print(a[0],d)
for i in range(1,n):
if a[i] != (a[i-1]+d)%m:
print(a[i],d)
quit()
elif n == m:
d = 1
x = 0
print(x,d)
elif m == 2:
a.sort()
print(a[0],a[1]-a[0])
elif m == 3:
a.sort()
d = a[1]-a[0]
for i in range(1,n):
if a[i] != a[i-1]+d:
print(-1)
quit()
print(a[0],d)
else:
ave = sum(a)*pow_mod(n,m-2,m)%m
b = [(a[i]-ave)**2%m for i in range(n)]
s = sum(b)*pow_mod(n,m-2,m)%m
k = n**2-1
d2 = s*12*pow_mod(k,m-2,m)%m
d = tonelli_shanks(d2,m)
x = (ave-d*(n-1)*pow_mod(2,m-2,m)%m)%m
if x != int(x):
print(-1)
quit()
x = int(x)
for i in range(n):
if not dic[(x+i*d)%m]:
print(-1)
quit()
print(x,d)
```
| 93,164 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Tags: brute force, implementation, math, number theory
Correct Solution:
```
import sys
def modInverse(x, y, mod):
res = 1
x = x % mod
while(y > 0):
if(y&1):
res = (res * x) % mod
y = y // 2
x = (x * x) % mod
return res
def isEqual(a, b):
for i in range(len(a)):
if (a[i] != b[i]):
return False
return True
m, n = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
s = [0, 0]
for x in arr:
s[0] = s[0] + x
s[1] = s[1] + x*x
if (n==1):
print(arr[0], 0)
sys.exit()
if (n==m):
print("0 1")
sys.exit()
arr.sort()
for i in range(1, n):
d = arr[i]-arr[0];
x = (s[0] - (n*(n-1) // 2) * d + m)%m * modInverse(n, m-2, m) % m
Sum = (n*x*x + n*(n-1)*d*x + n*(n-1)*(2*n-1)//6*d*d) % m
if(Sum == (s[1]%m)):
b = [x]
for j in range(1, n):
b.append((b[j-1] + d) % m)
b.sort()
if (isEqual(arr, b)):
print(x, d)
sys.exit()
print("-1")
```
| 93,165 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Tags: brute force, implementation, math, number theory
Correct Solution:
```
def solve(n, m, a):
if n == 0:
return 0, 1
if n == 1:
return a[0], 1
d = (a[1]-a[0]) % m
if d < 0: d += m
st = set(a)
cnt = 0
for v in a:
cnt += ((v + d) % m) in st
cnt = n-cnt
d = (d * pow(cnt, m-2, m)) % m
now = a[0]
while (now + m - d) % m in st:
now = (now + m - d) % m
for i in range(n):
if (now + i*d) % m not in st:
return -1, -1
return now, d
m, n = map(int, input().split())
a = list(map(int, input().split()))
if n * 2 > m:
st = set(a)
b = [i for i in range(m) if i not in st]
f, d = solve(len(b), m, b)
f = (f + d * (m-n)) % m
else:
f, d = solve(n, m, a)
if f < 0 or d < 0:
print(-1)
else:
print(f, d)
```
| 93,166 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Tags: brute force, implementation, math, number theory
Correct Solution:
```
from functools import reduce
def gcd_extended(bigger, less):
if less == 0:
return(bigger, 1, 0)
mod = bigger % less
div = bigger // less
gcd, c_less, c_mod = gcd_extended(less, mod)
#gcd == c_less * less + c_mod * mod
#mod == bigger - div * less
#gcd = (c_less - c_mod * div) * less
# + c_mod * bigger
c_bigger = c_mod
c_less = c_less - c_mod * div
return(gcd, c_bigger, c_less)
def mlp_inverse(x, p):
one, c_p, c_x = gcd_extended(p, x) #one == c_x * x + c_p * p
return (c_x + p) % p
def tests(x, d, p, row):
_row = set(row)
n = len(row)
if d == 0:
return False
for i in range(n):
elem = x + i * d
elem = (elem % p + p) % p
if elem not in _row:
return False
return True
p, n = (int(x) for x in input().split())
row = [int(x) for x in input().split()]
if p == n:
print(1, 1)
exit()
if n == 1:
print(row[0], 0)
exit()
#precounting constants
c1 = reduce(lambda x, y: (x + y) % p, row, 0)
c2 = reduce(lambda x, y: (x + y * y) % p, row, 0)
sum_i = reduce(lambda x, y: (x + y) % p, range(0, n), 0)
sum_i_sq = reduce(lambda x, y: (x + y * y) % p, range(0, n), 0)
inv_sum_i = mlp_inverse(sum_i, p)
inv_sum_i_sq = mlp_inverse(sum_i_sq, p)
#algorythm
for x in row:
#
d = (c1 - n * x) * inv_sum_i
d = (d % p + p) % p
equasion = n * x * x + 2 * d * x * sum_i + d * d * sum_i_sq
equasion = (equasion % p + p) % p
# print(x, d)
# print(c2, equasion)
if (equasion == c2
and tests(x, d, p, row)
):
print(x, d)
exit()
print(-1)
```
| 93,167 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Tags: brute force, implementation, math, number theory
Correct Solution:
```
import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
from collections import Counter,deque,defaultdict
from functools import lru_cache,reduce
from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max
def _heappush_max(heap,item):
heap.append(item)
heapq._siftdown_max(heap, 0, len(heap)-1)
def _heappushpop_max(heap, item):
if heap and item < heap[0]:
item, heap[0] = heap[0], item
heapq._siftup_max(heap, 0)
return item
from math import e, gcd as GCD, modf
read=sys.stdin.read
readline=sys.stdin.readline
readlines=sys.stdin.readlines
def Extended_Euclid(n,m):
stack=[]
while m:
stack.append((n,m))
n,m=m,n%m
if n>=0:
x,y=1,0
else:
x,y=-1,0
for i in range(len(stack)-1,-1,-1):
n,m=stack[i]
x,y=y,x-(n//m)*y
return x,y
class MOD:
def __init__(self,mod):
self.mod=mod
def Pow(self,a,n):
a%=self.mod
if n>=0:
return pow(a,n,self.mod)
else:
assert math.gcd(a,self.mod)==1
x=Extended_Euclid(a,self.mod)[0]
return pow(x,-n,self.mod)
def Build_Fact(self,N):
assert N>=0
self.factorial=[1]
for i in range(1,N+1):
self.factorial.append((self.factorial[-1]*i)%self.mod)
self.factorial_inv=[None]*(N+1)
self.factorial_inv[-1]=self.Pow(self.factorial[-1],-1)
for i in range(N-1,-1,-1):
self.factorial_inv[i]=(self.factorial_inv[i+1]*(i+1))%self.mod
return self.factorial_inv
def Fact(self,N):
return self.factorial[N]
def Fact_Inv(self,N):
return self.factorial_inv[N]
def Comb(self,N,K):
if K<0 or K>N:
return 0
s=self.factorial[N]
s=(s*self.factorial_inv[K])%self.mod
s=(s*self.factorial_inv[N-K])%self.mod
return s
M,N=map(int,readline().split())
A=list(map(int,readline().split()))
set_A=set(A)
MD=MOD(M)
if N==M:
print(0,1)
exit()
if 2*N<M:
if N==1:
print(A[0],0)
exit()
a=(A[0]-A[1])%M
cnt=0
for i in range(N):
if (A[i]+a)%M in set_A:
cnt+=1
d=a*MD.Pow(N-cnt,-1)%M
cnt=0
for i in range(N):
if (A[i]-d)%M in set_A:
cnt+=1
else:
ans=A[i]
if cnt==N-1:
print(ans,d)
exit()
else:
A=[a for a in range(M) if not a in set_A]
N=len(A)
if N==1:
print((A[0]+1)%M,1)
exit()
set_A=set(A)
a=(A[0]-A[1])%M
cnt=0
for i in range(N):
if (A[i]+a)%M in set_A:
cnt+=1
d=a*MD.Pow(N-cnt,-1)%M
cnt=0
for i in range(N):
if (A[i]+d)%M in set_A:
cnt+=1
else:
ans=A[i]
if cnt==N-1:
print((ans+d)%M,d)
exit()
print(-1)
```
| 93,168 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Submitted Solution:
```
#Soru 1
#n = input()
#lst = list(map(int,n.split()))
#num1 = lst[0]
#num2 = lst[1]
#num3 = lst[2]
#while True:
# if num1 > num2:
# if num1//num2 == num1/num2:
# ebob = num2
# break
# num1 = num1%num2
# else:
# if num2//num1 == num2/num1:
# ebob = num1
# break
# num2 = num2%num1
#
#div = lst[0]*lst[1]/ebob
#res = int(num3/div)
#print(res)
#####################################################
# Soru 2
#def swap(lst,n,i):
# temp = lst[i]
# lst[i] = lst[n-i-1]
# lst[n-i-1] = temp
# return lst
#n = int(input())
#arr = list(map(int,input().split()))
#i = 0
#for i in range(n//2):
# if i%2 == 0:
# arr = swap(arr,n,i)
#print(*arr)
#####################################################
#Soru 3
first_line = list(map(int, input().split()))
prime_m = first_line[0]
seq_n = first_line[1]
seq = list(map(int, input().split()))
if seq_n%2 == 1:
x = seq_n//2+1
for i in seq[seq_n//2+1:]:
seq[x] = i%prime_m - prime_m
x = x + 1
else:
x = seq_n//2
for i in seq[seq_n//2:]:
seq[x] = i%prime_m - prime_m
x = x + 1
seq = sorted(seq)
length = len(seq)
#Tek sayΔ±lΔ± sequence ler iΓ§indir Γ§ift iΓ§in denenmemiΕtir.
fark = seq[-1] - seq[0]
progress = int(fark/(len(seq)-1))
if seq[length//2] - seq[length//2 - 1] != progress:
x = seq[length//2]
seq.remove(x)
seq.append(x+prime_m)
fark = seq[-1] - seq[0]
progress = int(fark/(len(seq)-1))
print(seq)
indd = 1
for i in seq[:-1]:
if seq[indd] - i == progress:
indd = indd+1
else:
if indd == len(seq)//2:
if seq[indd]+prime_m - seq[-1] == progress:
indd = indd+1
else:
print(-1)
break
else:
print(-1)
break
if indd == len(seq):
print(seq[0]+prime_m,progress)
```
No
| 93,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Submitted Solution:
```
import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
from collections import Counter,deque,defaultdict
from functools import lru_cache,reduce
from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max
def _heappush_max(heap,item):
heap.append(item)
heapq._siftdown_max(heap, 0, len(heap)-1)
def _heappushpop_max(heap, item):
if heap and item < heap[0]:
item, heap[0] = heap[0], item
heapq._siftup_max(heap, 0)
return item
from math import e, gcd as GCD, modf
read=sys.stdin.read
readline=sys.stdin.readline
readlines=sys.stdin.readlines
def Extended_Euclid(n,m):
stack=[]
while m:
stack.append((n,m))
n,m=m,n%m
if n>=0:
x,y=1,0
else:
x,y=-1,0
for i in range(len(stack)-1,-1,-1):
n,m=stack[i]
x,y=y,x-(n//m)*y
return x,y
class MOD:
def __init__(self,mod):
self.mod=mod
def Pow(self,a,n):
a%=self.mod
if n>=0:
return pow(a,n,self.mod)
else:
assert math.gcd(a,self.mod)==1
x=Extended_Euclid(a,self.mod)[0]
return pow(x,-n,self.mod)
def Build_Fact(self,N):
assert N>=0
self.factorial=[1]
for i in range(1,N+1):
self.factorial.append((self.factorial[-1]*i)%self.mod)
self.factorial_inv=[None]*(N+1)
self.factorial_inv[-1]=self.Pow(self.factorial[-1],-1)
for i in range(N-1,-1,-1):
self.factorial_inv[i]=(self.factorial_inv[i+1]*(i+1))%self.mod
return self.factorial_inv
def Fact(self,N):
return self.factorial[N]
def Fact_Inv(self,N):
return self.factorial_inv[N]
def Comb(self,N,K):
if K<0 or K>N:
return 0
s=self.factorial[N]
s=(s*self.factorial_inv[K])%self.mod
s=(s*self.factorial_inv[N-K])%self.mod
return s
M,N,*A=map(int,read().split())
set_A=set(A)
MD=MOD(M)
if N==1:
print(A[0],0)
exit()
a=(A[0]-A[1])%M
cnt=0
for i in range(N):
if (A[i]+a)%M in set_A:
cnt+=1
d=a*MD.Pow(N-cnt,-1)
cnt=0
for i in range(N):
if (A[i]-d)%M in set_A:
cnt+=1
else:
ans=A[i]
if cnt!=N-1:
print(-1)
else:
print(ans,d)
```
No
| 93,170 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Submitted Solution:
```
def solve(n, m, a):
if n == 0:
return 0, 1
if n == 1:
return a[0], 1
d = (m+a[1]-a[0]) % m
st = set(a)
cnt = 0
for v in a:
cnt += ((v + d) % m) in st
cnt = n-cnt
d = (d * pow(cnt, m-2, m)) % m
now = a[0]
while (now + m - d) % m in st:
now = (now + m - d) % m
for i in range(n):
if (now + i*d) % m not in st:
return -1, -1
return now, d
m, n = map(int, input().split())
a = list(map(int, input().split()))
if n * 2 > m:
st = set(a)
b = [i for i in range(m) if i not in st]
f, d = solve(m-n, m, b)
f = (f + d * (m-n)) % m
else:
f, d = solve(n, m, a)
if f < 0:
print(f)
else:
print(f, d)
```
No
| 93,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not.
Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m.
Input
The first line contains two integers m and n (2 β€ m β€ 109 + 7, 1 β€ n β€ 105, m is prime) β Timofey's favorite prime module and the length of the sequence.
The second line contains n distinct integers a1, a2, ..., an (0 β€ ai < m) β the elements of the sequence.
Output
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m.
Otherwise, print two integers β the first element of the obtained progression x (0 β€ x < m) and its difference d (0 β€ d < m).
If there are multiple answers, print any of them.
Examples
Input
17 5
0 2 4 13 15
Output
13 2
Input
17 5
0 2 4 13 14
Output
-1
Input
5 3
1 2 3
Output
3 4
Submitted Solution:
```
import bisect
import copy
import decimal
import fractions
import heapq
import itertools
import math
import random
import sys
from collections import Counter,deque,defaultdict
from functools import lru_cache,reduce
from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max
def _heappush_max(heap,item):
heap.append(item)
heapq._siftdown_max(heap, 0, len(heap)-1)
def _heappushpop_max(heap, item):
if heap and item < heap[0]:
item, heap[0] = heap[0], item
heapq._siftup_max(heap, 0)
return item
from math import e, gcd as GCD, modf
read=sys.stdin.read
readline=sys.stdin.readline
readlines=sys.stdin.readlines
M,N,*A=map(int,read().split())
set_A=set(A)
if N**2<10**7:
cnt=defaultdict(int)
for i in range(N):
for j in range(N):
if i==j:
continue
cnt[(A[i]-A[j])%M]+=1
else:
cnt=defaultdict(int)
n=int(N**.5)
lst=[[] for i in range(n)]
for i in range(N):
lst[i].append(A[i%n])
for k in range(n):
l=len(lst[n])
for i in range(l):
for j in range(l):
if i==j:
continue
cnt[(A[i]-A[j])%M]+=1
for a,c in cnt.items():
if c==N-1:
for i in range(N):
if not (A[i]-a)%M in set_A:
print(A[i],a)
exit()
print(-1)
```
No
| 93,172 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ALT is a planet in a galaxy called "Encore". Humans rule this planet but for some reason there's no dog in their planet, so the people there are sad and depressed. Rick and Morty are universal philanthropists and they want to make people in ALT happy.
ALT has n cities numbered from 1 to n and n - 1 bidirectional roads numbered from 1 to n - 1. One can go from any city to any other city using these roads.
There are two types of people in ALT:
1. Guardians. A guardian lives in a house alongside a road and guards the road.
2. Citizens. A citizen lives in a house inside a city and works in an office in another city.
Every person on ALT is either a guardian or a citizen and there's exactly one guardian alongside each road.
<image>
Rick and Morty talked to all the people in ALT, and here's what they got:
* There are m citizens living in ALT.
* Citizen number i lives in city number xi and works in city number yi.
* Every day each citizen will go through all roads along the shortest path from his home to his work.
* A citizen will be happy if and only if either he himself has a puppy himself or all of guardians along his path to his work has a puppy (he sees the guardian's puppy in each road and will be happy).
* A guardian is always happy.
You need to tell Rick and Morty the minimum number of puppies they need in order to make all people in ALT happy, and also provide an optimal way to distribute these puppies.
Input
The first line of input contains two integers n and m (2 β€ n β€ 2 Γ 104, 1 β€ m β€ 104) β number of cities and number of citizens respectively.
The next n - 1 lines contain the roads, i-th line contains endpoint of i-th edge, v and u (1 β€ v, u β€ n, v β u).
The next m lines contain the information about citizens. i-th line contains two integers xi and yi (1 β€ xi, yi β€ n, xi β yi).
Output
In the first line of input print a single integer k, the total number of puppies they need (1 β€ k β€ n).
In the second line print an integer q, the number of puppies to give to citizens, followed by q distinct integers a1, a2, ..., aq, index of citizens to give puppy to (0 β€ q β€ min(m, k), 1 β€ ai β€ m).
In the third line print an integer e, the number of puppies to give to guardians, followed by e distinct integers b1, b2, ..., be, index of road of guardians to give puppy to (0 β€ e β€ min(n - 1, k), 1 β€ bi β€ n - 1).
Sum of q and e should be equal to k.
Examples
Input
4 5
2 4
3 4
1 4
2 4
2 1
2 4
1 2
2 3
Output
3
1 5
2 3 1
Input
4 7
3 4
1 4
2 1
4 2
4 2
2 4
1 4
2 1
3 1
4 2
Output
3
1 6
2 2 3
Note
Map of ALT in the first sample testcase (numbers written on a road is its index):
<image>
Map of ALT in the second sample testcase (numbers written on a road is its index):
<image>
Submitted Solution:
```
from functools import reduce
def bfs(user_, adj):
a, b = user_
tracks = [None] * len(adj)
tracks[a] = [a] # ΡΡΠΎΠ²Π΅Π½Ρ Π½Π°ΡΠ°Π»ΡΠ½ΠΎΠΉ Π²Π΅ΡΡΠΈΠ½Ρ
stack = [a] # Π΄ΠΎΠ±Π°Π²Π»ΡΠ΅ΠΌ Π½Π°ΡΠ°Π»ΡΠ½ΡΡ Π²Π΅ΡΡΠΈΠ½Ρ Π² ΠΎΡΠ΅ΡΠ΅Π΄Ρ
while stack: # ΠΏΠΎΠΊΠ° ΡΠ°ΠΌ ΡΡΠΎ-ΡΠΎ Π΅ΡΡΡ
node = stack.pop() # ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ Π²Π΅ΡΡΠΈΠ½Ρ
for i in adj[node]: # Π·Π°ΠΏΡΡΠΊΠ°Π΅ΠΌ ΠΎΠ±Ρ
ΠΎΠ΄ ΠΈΠ· Π²Π΅ΡΡΠΈΠ½Ρ node
if tracks[i] is None: # ΠΏΡΠΎΠ²Π΅ΡΠΊΠ° Π½Π° ΠΏΠΎΡΠ΅ΡΠ΅Π½Π½ΠΎΡΡΡ
stack.append(i) # Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠ΅ Π²Π΅ΡΡΠΈΠ½Ρ Π² ΠΎΡΠ΅ΡΠ΅Π΄Ρ
tracks[i] = tracks[node] + [i] # ΠΏΠΎΠ΄ΡΡΠΈΡΡΠ²Π°Π΅ΠΌ ΡΡΠΎΠ²Π΅Π½Ρ Π²Π΅ΡΡΠΈΠ½Ρ
return next(filter(lambda t: t[-1] == b, tracks))
def func(tmp):
users = [set(bfs(user, city)) for user in tmp]
inc = []
using = [0] * (n - 1)
for user in users:
inc.append(set())
i = 0
for admin in admins:
if admin.issubset(user):
inc[-1].add(i)
using[i] += 1
i += 1
print(inc)
adm = reduce(lambda res, e: res | e if len(e) > 1 else res, inc, set())
if len(adm) < n + n // 2:
return range(1, m + 1), ()
else:
u = 1
res_u = []
res_a = set()
for admin in inc:
for a in admin:
if using[a] <= 1:
res_u.append(u)
else:
res_a.add(a + 1)
u += 1
return res_u, res_a
n, m = map(int, input().split())
city = [[] for _ in range(n)]
admins = []
for _ in range(n - 1):
x, y = map(int, input().split())
x -= 1
y -= 1
city[x].append(y)
city[y].append(x)
admins.append({x, y})
users_ = [tuple(map(lambda p: int(p) - 1, input().split())) for _ in range(m)]
res_user, res_admin = func(users_)
print(len(res_user) + len(res_admin))
print(len(res_user), *res_user)
print(len(res_admin), *res_admin)
```
No
| 93,173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ALT is a planet in a galaxy called "Encore". Humans rule this planet but for some reason there's no dog in their planet, so the people there are sad and depressed. Rick and Morty are universal philanthropists and they want to make people in ALT happy.
ALT has n cities numbered from 1 to n and n - 1 bidirectional roads numbered from 1 to n - 1. One can go from any city to any other city using these roads.
There are two types of people in ALT:
1. Guardians. A guardian lives in a house alongside a road and guards the road.
2. Citizens. A citizen lives in a house inside a city and works in an office in another city.
Every person on ALT is either a guardian or a citizen and there's exactly one guardian alongside each road.
<image>
Rick and Morty talked to all the people in ALT, and here's what they got:
* There are m citizens living in ALT.
* Citizen number i lives in city number xi and works in city number yi.
* Every day each citizen will go through all roads along the shortest path from his home to his work.
* A citizen will be happy if and only if either he himself has a puppy himself or all of guardians along his path to his work has a puppy (he sees the guardian's puppy in each road and will be happy).
* A guardian is always happy.
You need to tell Rick and Morty the minimum number of puppies they need in order to make all people in ALT happy, and also provide an optimal way to distribute these puppies.
Input
The first line of input contains two integers n and m (2 β€ n β€ 2 Γ 104, 1 β€ m β€ 104) β number of cities and number of citizens respectively.
The next n - 1 lines contain the roads, i-th line contains endpoint of i-th edge, v and u (1 β€ v, u β€ n, v β u).
The next m lines contain the information about citizens. i-th line contains two integers xi and yi (1 β€ xi, yi β€ n, xi β yi).
Output
In the first line of input print a single integer k, the total number of puppies they need (1 β€ k β€ n).
In the second line print an integer q, the number of puppies to give to citizens, followed by q distinct integers a1, a2, ..., aq, index of citizens to give puppy to (0 β€ q β€ min(m, k), 1 β€ ai β€ m).
In the third line print an integer e, the number of puppies to give to guardians, followed by e distinct integers b1, b2, ..., be, index of road of guardians to give puppy to (0 β€ e β€ min(n - 1, k), 1 β€ bi β€ n - 1).
Sum of q and e should be equal to k.
Examples
Input
4 5
2 4
3 4
1 4
2 4
2 1
2 4
1 2
2 3
Output
3
1 5
2 3 1
Input
4 7
3 4
1 4
2 1
4 2
4 2
2 4
1 4
2 1
3 1
4 2
Output
3
1 6
2 2 3
Note
Map of ALT in the first sample testcase (numbers written on a road is its index):
<image>
Map of ALT in the second sample testcase (numbers written on a road is its index):
<image>
Submitted Solution:
```
from functools import reduce
def bfs(user_, adj):
a, b = user_
tracks = [None] * len(adj)
tracks[a] = [a] # ΡΡΠΎΠ²Π΅Π½Ρ Π½Π°ΡΠ°Π»ΡΠ½ΠΎΠΉ Π²Π΅ΡΡΠΈΠ½Ρ
stack = [a] # Π΄ΠΎΠ±Π°Π²Π»ΡΠ΅ΠΌ Π½Π°ΡΠ°Π»ΡΠ½ΡΡ Π²Π΅ΡΡΠΈΠ½Ρ Π² ΠΎΡΠ΅ΡΠ΅Π΄Ρ
while stack: # ΠΏΠΎΠΊΠ° ΡΠ°ΠΌ ΡΡΠΎ-ΡΠΎ Π΅ΡΡΡ
node = stack.pop() # ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ Π²Π΅ΡΡΠΈΠ½Ρ
for i in adj[node]: # Π·Π°ΠΏΡΡΠΊΠ°Π΅ΠΌ ΠΎΠ±Ρ
ΠΎΠ΄ ΠΈΠ· Π²Π΅ΡΡΠΈΠ½Ρ node
if tracks[i] is None: # ΠΏΡΠΎΠ²Π΅ΡΠΊΠ° Π½Π° ΠΏΠΎΡΠ΅ΡΠ΅Π½Π½ΠΎΡΡΡ
stack.append(i) # Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠ΅ Π²Π΅ΡΡΠΈΠ½Ρ Π² ΠΎΡΠ΅ΡΠ΅Π΄Ρ
tracks[i] = tracks[node] + [i] # ΠΏΠΎΠ΄ΡΡΠΈΡΡΠ²Π°Π΅ΠΌ ΡΡΠΎΠ²Π΅Π½Ρ Π²Π΅ΡΡΠΈΠ½Ρ
return next(filter(lambda t: t[-1] == b, tracks))
def func(tmp):
users = [set(bfs(user, city)) for user in tmp]
inc = []
using = [0] * (n - 1)
for user in users:
inc.append([])
i = 0
for admin in admins:
if admin.issubset(user):
inc[-1].append(i)
using[i] += 1
i += 1
u = 1
res_u = set()
res_a = set()
for admin in inc:
for a in admin:
if using[a] <= 1:
res_u.add(u)
else:
res_a.add(a + 1)
u += 1
return res_u, res_a
n, m = map(int, input().split())
city = [[] for _ in range(n)]
admins = []
for _ in range(n - 1):
x, y = map(int, input().split())
x -= 1
y -= 1
city[x].append(y)
city[y].append(x)
admins.append({x, y})
users_ = [tuple(map(lambda p: int(p) - 1, input().split())) for _ in range(m)]
res_user, res_admin = func(users_)
length = len(set(users_))
length1 = len(res_user) + len(res_admin)
if length < length1:
length1 = length
res_user = range(1, m + 1)
res_admin = ()
print(len(res_user) + len(res_admin))
print(len(res_user), *res_user)
print(len(res_admin), *res_admin)
```
No
| 93,174 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ALT is a planet in a galaxy called "Encore". Humans rule this planet but for some reason there's no dog in their planet, so the people there are sad and depressed. Rick and Morty are universal philanthropists and they want to make people in ALT happy.
ALT has n cities numbered from 1 to n and n - 1 bidirectional roads numbered from 1 to n - 1. One can go from any city to any other city using these roads.
There are two types of people in ALT:
1. Guardians. A guardian lives in a house alongside a road and guards the road.
2. Citizens. A citizen lives in a house inside a city and works in an office in another city.
Every person on ALT is either a guardian or a citizen and there's exactly one guardian alongside each road.
<image>
Rick and Morty talked to all the people in ALT, and here's what they got:
* There are m citizens living in ALT.
* Citizen number i lives in city number xi and works in city number yi.
* Every day each citizen will go through all roads along the shortest path from his home to his work.
* A citizen will be happy if and only if either he himself has a puppy himself or all of guardians along his path to his work has a puppy (he sees the guardian's puppy in each road and will be happy).
* A guardian is always happy.
You need to tell Rick and Morty the minimum number of puppies they need in order to make all people in ALT happy, and also provide an optimal way to distribute these puppies.
Input
The first line of input contains two integers n and m (2 β€ n β€ 2 Γ 104, 1 β€ m β€ 104) β number of cities and number of citizens respectively.
The next n - 1 lines contain the roads, i-th line contains endpoint of i-th edge, v and u (1 β€ v, u β€ n, v β u).
The next m lines contain the information about citizens. i-th line contains two integers xi and yi (1 β€ xi, yi β€ n, xi β yi).
Output
In the first line of input print a single integer k, the total number of puppies they need (1 β€ k β€ n).
In the second line print an integer q, the number of puppies to give to citizens, followed by q distinct integers a1, a2, ..., aq, index of citizens to give puppy to (0 β€ q β€ min(m, k), 1 β€ ai β€ m).
In the third line print an integer e, the number of puppies to give to guardians, followed by e distinct integers b1, b2, ..., be, index of road of guardians to give puppy to (0 β€ e β€ min(n - 1, k), 1 β€ bi β€ n - 1).
Sum of q and e should be equal to k.
Examples
Input
4 5
2 4
3 4
1 4
2 4
2 1
2 4
1 2
2 3
Output
3
1 5
2 3 1
Input
4 7
3 4
1 4
2 1
4 2
4 2
2 4
1 4
2 1
3 1
4 2
Output
3
1 6
2 2 3
Note
Map of ALT in the first sample testcase (numbers written on a road is its index):
<image>
Map of ALT in the second sample testcase (numbers written on a road is its index):
<image>
Submitted Solution:
```
from functools import reduce
def bfs(user_, adj):
a, b = user_
tracks = [None] * len(adj)
tracks[a] = [a] # ΡΡΠΎΠ²Π΅Π½Ρ Π½Π°ΡΠ°Π»ΡΠ½ΠΎΠΉ Π²Π΅ΡΡΠΈΠ½Ρ
stack = [a] # Π΄ΠΎΠ±Π°Π²Π»ΡΠ΅ΠΌ Π½Π°ΡΠ°Π»ΡΠ½ΡΡ Π²Π΅ΡΡΠΈΠ½Ρ Π² ΠΎΡΠ΅ΡΠ΅Π΄Ρ
while stack: # ΠΏΠΎΠΊΠ° ΡΠ°ΠΌ ΡΡΠΎ-ΡΠΎ Π΅ΡΡΡ
node = stack.pop() # ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ Π²Π΅ΡΡΠΈΠ½Ρ
for i in adj[node]: # Π·Π°ΠΏΡΡΠΊΠ°Π΅ΠΌ ΠΎΠ±Ρ
ΠΎΠ΄ ΠΈΠ· Π²Π΅ΡΡΠΈΠ½Ρ node
if tracks[i] is None: # ΠΏΡΠΎΠ²Π΅ΡΠΊΠ° Π½Π° ΠΏΠΎΡΠ΅ΡΠ΅Π½Π½ΠΎΡΡΡ
stack.append(i) # Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠ΅ Π²Π΅ΡΡΠΈΠ½Ρ Π² ΠΎΡΠ΅ΡΠ΅Π΄Ρ
tracks[i] = tracks[node] + [i] # ΠΏΠΎΠ΄ΡΡΠΈΡΡΠ²Π°Π΅ΠΌ ΡΡΠΎΠ²Π΅Π½Ρ Π²Π΅ΡΡΠΈΠ½Ρ
return next(filter(lambda t: t[-1] == b, tracks))
def func(tmp):
users = [set(bfs(user, city)) for user in tmp]
inc = []
using = [0] * (n - 1)
for user in users:
inc.append([])
i = 0
for admin in admins:
if admin.issubset(user):
inc[-1].append(i)
using[i] += 1
i += 1
# adm = reduce(lambda res, e: res | e if len(e) > 1 else res, inc, set())
#print(sum(using) / float(len(using)))
if sum(using) / float(len(using)) < float(n - 1) / 2.0:
return range(1, m + 1), ()
else:
u = 1
res_u = []
res_a = set()
for admin in inc:
for a in admin:
if using[a] <= 1:
res_u.append(u)
else:
res_a.add(a + 1)
u += 1
return res_u, res_a
n, m = map(int, input().split())
city = [[] for _ in range(n)]
admins = []
for _ in range(n - 1):
x, y = map(int, input().split())
x -= 1
y -= 1
city[x].append(y)
city[y].append(x)
admins.append({x, y})
users_ = [tuple(map(lambda p: int(p) - 1, input().split())) for _ in range(m)]
res_user, res_admin = func(users_)
print(len(res_user) + len(res_admin))
print(len(res_user), *res_user)
print(len(res_admin), *res_admin)
```
No
| 93,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ALT is a planet in a galaxy called "Encore". Humans rule this planet but for some reason there's no dog in their planet, so the people there are sad and depressed. Rick and Morty are universal philanthropists and they want to make people in ALT happy.
ALT has n cities numbered from 1 to n and n - 1 bidirectional roads numbered from 1 to n - 1. One can go from any city to any other city using these roads.
There are two types of people in ALT:
1. Guardians. A guardian lives in a house alongside a road and guards the road.
2. Citizens. A citizen lives in a house inside a city and works in an office in another city.
Every person on ALT is either a guardian or a citizen and there's exactly one guardian alongside each road.
<image>
Rick and Morty talked to all the people in ALT, and here's what they got:
* There are m citizens living in ALT.
* Citizen number i lives in city number xi and works in city number yi.
* Every day each citizen will go through all roads along the shortest path from his home to his work.
* A citizen will be happy if and only if either he himself has a puppy himself or all of guardians along his path to his work has a puppy (he sees the guardian's puppy in each road and will be happy).
* A guardian is always happy.
You need to tell Rick and Morty the minimum number of puppies they need in order to make all people in ALT happy, and also provide an optimal way to distribute these puppies.
Input
The first line of input contains two integers n and m (2 β€ n β€ 2 Γ 104, 1 β€ m β€ 104) β number of cities and number of citizens respectively.
The next n - 1 lines contain the roads, i-th line contains endpoint of i-th edge, v and u (1 β€ v, u β€ n, v β u).
The next m lines contain the information about citizens. i-th line contains two integers xi and yi (1 β€ xi, yi β€ n, xi β yi).
Output
In the first line of input print a single integer k, the total number of puppies they need (1 β€ k β€ n).
In the second line print an integer q, the number of puppies to give to citizens, followed by q distinct integers a1, a2, ..., aq, index of citizens to give puppy to (0 β€ q β€ min(m, k), 1 β€ ai β€ m).
In the third line print an integer e, the number of puppies to give to guardians, followed by e distinct integers b1, b2, ..., be, index of road of guardians to give puppy to (0 β€ e β€ min(n - 1, k), 1 β€ bi β€ n - 1).
Sum of q and e should be equal to k.
Examples
Input
4 5
2 4
3 4
1 4
2 4
2 1
2 4
1 2
2 3
Output
3
1 5
2 3 1
Input
4 7
3 4
1 4
2 1
4 2
4 2
2 4
1 4
2 1
3 1
4 2
Output
3
1 6
2 2 3
Note
Map of ALT in the first sample testcase (numbers written on a road is its index):
<image>
Map of ALT in the second sample testcase (numbers written on a road is its index):
<image>
Submitted Solution:
```
def bfs(user_, adj):
a, b = user_
tracks = [None] * len(adj)
tracks[a] = [a] # ΡΡΠΎΠ²Π΅Π½Ρ Π½Π°ΡΠ°Π»ΡΠ½ΠΎΠΉ Π²Π΅ΡΡΠΈΠ½Ρ
stack = [a] # Π΄ΠΎΠ±Π°Π²Π»ΡΠ΅ΠΌ Π½Π°ΡΠ°Π»ΡΠ½ΡΡ Π²Π΅ΡΡΠΈΠ½Ρ Π² ΠΎΡΠ΅ΡΠ΅Π΄Ρ
while stack: # ΠΏΠΎΠΊΠ° ΡΠ°ΠΌ ΡΡΠΎ-ΡΠΎ Π΅ΡΡΡ
node = stack.pop() # ΠΈΠ·Π²Π»Π΅ΠΊΠ°Π΅ΠΌ Π²Π΅ΡΡΠΈΠ½Ρ
for i in adj[node]: # Π·Π°ΠΏΡΡΠΊΠ°Π΅ΠΌ ΠΎΠ±Ρ
ΠΎΠ΄ ΠΈΠ· Π²Π΅ΡΡΠΈΠ½Ρ node
if tracks[i] is None: # ΠΏΡΠΎΠ²Π΅ΡΠΊΠ° Π½Π° ΠΏΠΎΡΠ΅ΡΠ΅Π½Π½ΠΎΡΡΡ
stack.append(i) # Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠ΅ Π²Π΅ΡΡΠΈΠ½Ρ Π² ΠΎΡΠ΅ΡΠ΅Π΄Ρ
tracks[i] = tracks[node] + [i] # ΠΏΠΎΠ΄ΡΡΠΈΡΡΠ²Π°Π΅ΠΌ ΡΡΠΎΠ²Π΅Π½Ρ Π²Π΅ΡΡΠΈΠ½Ρ
return next(filter(lambda t: t[-1] == b, tracks))
def func(tmp):
users = [set(bfs(user, city)) for user in tmp]
inc = []
using = [0] * (n - 1)
for user in users:
inc.append([])
i = 0
for admin in admins:
if admin.issubset(user):
inc[-1].append(i)
using[i] += 1
i += 1
if sum(using) // len(using) < len(using) // 2:
return range(1, m + 1), ()
else:
u = 1
res_u = []
res_a = set()
for admin in inc:
for a in admin:
if using[a] <= 1:
res_u.append(u)
else:
res_a.add(a + 1)
u += 1
return res_u, res_a
n, m = map(int, input().split())
city = [[] for _ in range(n)]
admins = []
for _ in range(n - 1):
x, y = map(int, input().split())
x -= 1
y -= 1
city[x].append(y)
city[y].append(x)
admins.append({x, y})
users_ = [tuple(map(lambda p: int(p) - 1, input().split())) for _ in range(m)]
res_user, res_admin = func(users_)
print(len(res_user) + len(res_admin))
print(len(res_user), *res_user)
print(len(res_admin), *res_admin)
```
No
| 93,176 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Tags: binary search, data structures, implementation
Correct Solution:
```
def find(ar: list) -> bool:
p = [0]
s = sum(ar)
if s % 2 != 0:
return False
for elm in ar:
p.append(p[-1] + elm)
if p[-1] == (s >> 1):
return True
lk = set()
n = len(ar)
for i in range(1, n):
lk.add(ar[i - 1])
elm = -(s >> 1) + (p[i] + ar[i])
if elm in lk:
return True
return False
if __name__ == '__main__':
n = int(input())
ar = list(map(int, input().split()))
rar = ar[::-1]
if find(ar) or find(rar):
print("YES")
else:
print("NO")
```
| 93,177 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Tags: binary search, data structures, implementation
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=300006, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <=key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def 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------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n=int(input())
l=list(map(int,input().split()))
su=sum(l)
if su%2!=0:
print("NO")
sys.exit(0)
su//=2
tr=0
done=set()
for i in range(n):
done.add(l[i])
tr+=l[i]
if tr-su in done:
print("YES")
sys.exit(0)
tr=0
done=set()
for i in range(n-1,-1,-1):
done.add(l[i])
tr+=l[i]
if tr-su in done:
print("YES")
sys.exit(0)
print("NO")
```
| 93,178 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Tags: binary search, data structures, implementation
Correct Solution:
```
n=int(input())
l=[int(i) for i in input().split()]
tot=sum(l)
if tot&1:
print('NO')
exit()
#dont remove
sm=0
mid=tot//2
for i in l:
sm+=i
if sm==tot-sm:
print("YES")
exit()
#simulaate pref
from collections import defaultdict
def check(l):
d=defaultdict(int)
sm=0
for i in range(n-1):
d[l[i]]+=1
sm+=l[i]
add=l[i+1]
curr=sm+add
rem=tot-curr
#print(curr,rem)
if d[mid-rem]:
print('YES')
exit()
#d[l[i]]+=1
if check(l):
pass
l=l[::-1]
if check(l):
pass
print("NO")
```
| 93,179 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Tags: binary search, data structures, implementation
Correct Solution:
```
import os,io
from sys import stdout
import collections
import random
import math
from operator import itemgetter
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import Counter
# import sys
# sys.setrecursionlimit(10**6)
def binomial_coefficient(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def powerOfK(k, max):
if k == 1:
return [1]
if k == -1:
return [-1, 1]
result = []
n = 1
while n <= max:
result.append(n)
n *= k
return result
def prefixSum(arr):
for i in range(1, len(arr)):
arr[i] = arr[i] + arr[i-1]
return arr
def divisors(n):
i = 1
result = []
while i*i <= n:
if n%i == 0:
if n/i == i:
result.append(i)
else:
result.append(i)
result.append(n/i)
i+=1
return result
# from functools import lru_cache
# @lru_cache(maxsize=None)
n = int(input())
l = list(map(int, input().split()))
rs = Counter(l)
ls = collections.defaultdict(int)
left = prefixSum(l[:])
right = prefixSum(l[::-1])[::-1]
found = False
for i in range(0, n):
#print(rs, ls, l[i])
rs[l[i]] -= 1
ls[l[i]] += 1
#print(left[i], right[i]-l[i])
if left[i] == right[i] - l[i]:
found = True
print("YES")
break
if left[i] > right[i] - l[i]:
diff = left[i] - (right[i] - l[i])
if diff % 2 != 0:
continue
if diff // 2 in ls and ls[diff//2] > 0:
found = True
print("YES")
break
else:
diff = (right[i] - l[i]) - left[i]
if diff % 2 != 0:
continue
if diff // 2 in rs and rs[diff//2] > 0:
found = True
print("YES")
break
if not found:
print("NO")
```
| 93,180 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Tags: binary search, data structures, implementation
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
sum=[0]*n
sum[0]=a[0]
for i in range(1,n):
sum[i]=sum[i-1]+a[i]
s=sum[n-1]
found=0
if(s%2==0):
half=s//2
u=0
l=n-1
while(u<=l):
mid=(u+l)//2
if(sum[mid]==half):
print("YES")
exit()
elif(sum[mid]>half):
l=mid-1
else:
u=mid+1
for i in range(0,n):
u=i
l=n-1
if((2*a[i]+s)%2==0):
check=(s+2*a[i])//2
while(u<=l):
mid=(u+l)//2
if(sum[mid]==check):
found=1
break
elif(sum[mid]>check):
l=mid-1
else:
u=mid+1
if(found==1):
break
if(found==0 and n<10000):
for i in range(n-1,-1,-1):
u=0
l=i-1
if((s-2*a[i])%2==0 and (s-2*a[i])>0):
check=(s-2*a[i])//2
while(u<=l):
mid=(u+l)//2
if(sum[mid]==check):
found=1
break
elif(sum[mid]>check):
l=mid-1
else:
u=mid+1
if(found==1):
break
if(found==1):
print("YES")
else:
print("NO")
```
| 93,181 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Tags: binary search, data structures, implementation
Correct Solution:
```
n = int(input())
arr = [int(x) for x in input().split()]
if n==1:
print("NO")
exit(0)
s = sum(arr)
sp = 0
ss = s
setq = {}
setp = {}
for i in arr:
setq[i] = setq.get(i,0)+1
setp[i] = 0
for i in range(n):
sp += arr[i]
ss -= arr[i]
setp[arr[i]] += 1
setq[arr[i]] -= 1
val = ss-sp
if val>0 and not val&1:
val //= 2
ans = setq.get(val,0)
if ans>0:
print("YES")
exit(0)
elif val<0 and not (-val)&1:
val = -val
val //= 2
ans = setp.get(val,0)
if ans>0:
print("YES")
exit(0)
elif val==0:
print("YES")
exit(0)
print("NO")
```
| 93,182 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Tags: binary search, data structures, implementation
Correct Solution:
```
# |
# _` | __ \ _` | __| _ \ __ \ _` | _` |
# ( | | | ( | ( ( | | | ( | ( |
# \__,_| _| _| \__,_| \___| \___/ _| _| \__,_| \__,_|
import sys
def read_line():
return sys.stdin.readline()[:-1]
def read_int():
return int(sys.stdin.readline())
def read_int_line():
return [int(v) for v in sys.stdin.readline().split()]
n = read_int()
a = read_int_line()
d = {}
d[0] = -1
pref = [0]*(n+1)
for i in range(1,n+1):
pref[i]=pref[i-1]+a[i-1]
if a[i-1] not in d:
d[a[i-1]] = i-1
tot = pref[n]
req = tot//2
f = False
for i in range(1,n+1):
if pref[i]>=req:
if pref[i]-req in d:
if d[pref[i]-req] < i:
f = True
break
a = a[::-1]
d = {}
d[0] = -1
pref = [0]*(n+1)
for i in range(1,n+1):
pref[i]=pref[i-1]+a[i-1]
if a[i-1] not in d:
d[a[i-1]] = i-1
tot = pref[n]
req = tot//2
f1 = False
for i in range(1,n+1):
if pref[i]>=req:
if pref[i]-req in d:
if d[pref[i]-req] < i:
f1 = True
break
if (f or f1) and tot%2==0:
print("YES")
else:
print("NO")
```
| 93,183 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Tags: binary search, data structures, implementation
Correct Solution:
```
n = int(input())
A = list(map(int,input().split()))
d = dict()
acc = 0
for i,j in enumerate(A):
acc += j
d[acc] = i
if acc % 2 == 1:
print("NO")
exit()
for i,j in enumerate(A):
v = acc // 2 - j
if v in d and d[v] < i:
print("YES")
exit()
v = acc / 2 + j
if v in d and d[v] >= i:
print("YES")
exit()
print("NO")
```
| 93,184 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Submitted Solution:
```
a = int(input())
nums = [int(i) for i in input().split()]
tot = sum(nums)
def runner(lpr):
total = 0
used = {}
for i in range(*lpr):
used[nums[i]] = 1
total += nums[i]
distance = 2 * total - tot
if distance % 2 == 0 and used.get(distance // 2, -1) != -1:
print("YES")
exit(0)
runner((0, a))
runner((a - 1, -1, -1))
print("NO")
```
Yes
| 93,185 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Submitted Solution:
```
from itertools import *
n = int(input())
l = list(map(int, input().split()))
for j in range(0, 2):
m = {}
l = [0] + list(reversed(l))
for i in range(len(l)):
m[l[i]] = i
ac = list(accumulate(l))
s = ac[-1]
for i in range(0, len(ac)-1):
if ac[i] == s/2 or (s/2-ac[i] in m.keys() and m[s/2-ac[i]] > i):
print('YES')
quit()
print('NO')
```
Yes
| 93,186 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
e = set([0])
p = 0
s = sum(a)
if s % 2:
st = False
else:
st = True
if st:
st = False
for j in range(2):
for i in a:
p += i
e.add(i)
if p - s // 2 in e:
st = True
break
e = set([0])
p = 0
a.reverse()
print('YES' if st else 'NO')
```
Yes
| 93,187 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Submitted Solution:
```
def func():
n = int(input())
array = []
sum = 0
for index,number in enumerate(input().split()):
num = int(number)
array.append(num)
sum += num
if sum%1 ==1:
print("NO")
return
setn = set()
sumSub = 0
indexdict = {}
for indexm,number in enumerate(array):
sumSub += number
sum2 = sumSub * 2 - sum
if sum2%2 == 1:
continue
sum2 /= 2
setn.add(sum2)
indexdict[sum2] = indexm
i = 0
if 0 in setn:
print("YES")
return
while i < n:
num = array[i]
if num in setn and num in indexdict and i < indexdict[num]:
print("YES")
return
if -num in setn and -num in indexdict and i > indexdict[-num]:
print("YES")
return
i+=1
print("NO")
func()
```
Yes
| 93,188 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Submitted Solution:
```
def process(A):
d = {}
S = 0
for x in A:
if x not in d:
d[x] = 0
d[x]+=1
S+=x
if S % 2==1:
return 'NO'
S1 = 0
for x in A:
S1+=x
d[x]-=1
y = S//2-S1
if y==0:
return 'YES'
if y in d and d[y] > 0:
return 'YES'
return 'NO'
n = int(input())
A = [int(x) for x in input().split()]
print(process(A))
```
No
| 93,189 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Submitted Solution:
```
def solve(a):
s = sum(a)
if s % 2 == 1:
return False
s //= 2
elements = set()
cs = 0
n = len(a)
for i in range(n):
cs += a[i]
if cs == s:
return True
elements.add(a[i])
if i > 0 and cs > s and cs - s in elements:
return True
return False
def main():
n = int(input())
a = list(map(int, input().split()))
if solve(a):
print("YES")
else:
print("NO")
if __name__ == '__main__':
main()
```
No
| 93,190 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Submitted Solution:
```
def isthat(list1):
flag=False
for i in range(1,len(list1)):
if sum(list1[0:i])==sum(list1[i:]):
flag=True
return flag
n=int(input())
list1=list(map(int,input().strip().split(' ')))
flag=False
for i in range(n):
for j in range(n):
list2=list1[:]
t=list2[i]
list2[i]=list2[j]
list2[j]=t
if isthat(list2):
flag=True
break
if flag:
break
if flag:
print("YES")
else:
print("NO")
```
No
| 93,191 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).
Inserting an element in the same position he was erased from is also considered moving.
Can Vasya divide the array after choosing the right element to move and its new position?
Input
The first line contains single integer n (1 β€ n β€ 100000) β the size of the array.
The second line contains n integers a1, a2... an (1 β€ ai β€ 109) β the elements of the array.
Output
Print YES if Vasya can divide the array after moving one element. Otherwise print NO.
Examples
Input
3
1 3 2
Output
YES
Input
5
1 2 3 4 5
Output
NO
Input
5
2 2 3 4 5
Output
YES
Note
In the first example Vasya can move the second element to the end of the array.
In the second example no move can make the division possible.
In the third example Vasya can move the fourth element by one position to the left.
Submitted Solution:
```
n = int(input())
ls = input().split()
ls = list(map(int, ls))
psum = []
psum.append(ls[0])
ch = 0
for i in range(1, n):
psum.append(psum[i-1] + ls[i])
#print(len(psum), psum)
half = psum[n-1]//2
#print(half)
if psum[n-1] % 2 != 0:
print("No")
else:
for i in range(n-1):
temp = psum[i]
#print(temp)
if temp < half:
diff = half - temp
#print("inner %d" % ls[j])
if diff == ls[i+1]:
print(ls[i], diff)
print("Yes")
ch = 1
break
elif temp == half:
ch = 1
print("Yes")
break
if ch == 1:
break
if ch == 0:
print("No")
```
No
| 93,192 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a set of 4n strings of equal length, consisting of lowercase English letters "a", "b", "c", "d" and "e". Moreover, the set is split into n groups of 4 equal strings each. Vasya also has one special string a of the same length, consisting of letters "a" only.
Vasya wants to obtain from string a some fixed string b, in order to do this, he can use the strings from his set in any order. When he uses some string x, each of the letters in string a replaces with the next letter in alphabet as many times as the alphabet position, counting from zero, of the corresponding letter in string x. Within this process the next letter in alphabet after "e" is "a".
For example, if some letter in a equals "b", and the letter on the same position in x equals "c", then the letter in a becomes equal "d", because "c" is the second alphabet letter, counting from zero. If some letter in a equals "e", and on the same position in x is "d", then the letter in a becomes "c". For example, if the string a equals "abcde", and string x equals "baddc", then a becomes "bbabb".
A used string disappears, but Vasya can use equal strings several times.
Vasya wants to know for q given strings b, how many ways there are to obtain from the string a string b using the given set of 4n strings? Two ways are different if the number of strings used from some group of 4 strings is different. Help Vasya compute the answers for these questions modulo 109 + 7.
Input
The first line contains two integers n and m (1 β€ n, m β€ 500) β the number of groups of four strings in the set, and the length of all strings.
Each of the next n lines contains a string s of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e". This means that there is a group of four strings equal to s.
The next line contains single integer q (1 β€ q β€ 300) β the number of strings b Vasya is interested in.
Each of the next q strings contains a string b of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e" β a string Vasya is interested in.
Output
For each string Vasya is interested in print the number of ways to obtain it from string a, modulo 109 + 7.
Examples
Input
1 1
b
2
a
e
Output
1
1
Input
2 4
aaaa
bbbb
1
cccc
Output
5
Note
In the first example, we have 4 strings "b". Then we have the only way for each string b: select 0 strings "b" to get "a" and select 4 strings "b" to get "e", respectively. So, we have 1 way for each request.
In the second example, note that the choice of the string "aaaa" does not change anything, that is we can choose any amount of it (from 0 to 4, it's 5 different ways) and we have to select the line "bbbb" 2 times, since other variants do not fit. We get that we have 5 ways for the request.
Submitted Solution:
```
# E
print(1)
print(1)
```
No
| 93,193 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a set of 4n strings of equal length, consisting of lowercase English letters "a", "b", "c", "d" and "e". Moreover, the set is split into n groups of 4 equal strings each. Vasya also has one special string a of the same length, consisting of letters "a" only.
Vasya wants to obtain from string a some fixed string b, in order to do this, he can use the strings from his set in any order. When he uses some string x, each of the letters in string a replaces with the next letter in alphabet as many times as the alphabet position, counting from zero, of the corresponding letter in string x. Within this process the next letter in alphabet after "e" is "a".
For example, if some letter in a equals "b", and the letter on the same position in x equals "c", then the letter in a becomes equal "d", because "c" is the second alphabet letter, counting from zero. If some letter in a equals "e", and on the same position in x is "d", then the letter in a becomes "c". For example, if the string a equals "abcde", and string x equals "baddc", then a becomes "bbabb".
A used string disappears, but Vasya can use equal strings several times.
Vasya wants to know for q given strings b, how many ways there are to obtain from the string a string b using the given set of 4n strings? Two ways are different if the number of strings used from some group of 4 strings is different. Help Vasya compute the answers for these questions modulo 109 + 7.
Input
The first line contains two integers n and m (1 β€ n, m β€ 500) β the number of groups of four strings in the set, and the length of all strings.
Each of the next n lines contains a string s of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e". This means that there is a group of four strings equal to s.
The next line contains single integer q (1 β€ q β€ 300) β the number of strings b Vasya is interested in.
Each of the next q strings contains a string b of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e" β a string Vasya is interested in.
Output
For each string Vasya is interested in print the number of ways to obtain it from string a, modulo 109 + 7.
Examples
Input
1 1
b
2
a
e
Output
1
1
Input
2 4
aaaa
bbbb
1
cccc
Output
5
Note
In the first example, we have 4 strings "b". Then we have the only way for each string b: select 0 strings "b" to get "a" and select 4 strings "b" to get "e", respectively. So, we have 1 way for each request.
In the second example, note that the choice of the string "aaaa" does not change anything, that is we can choose any amount of it (from 0 to 4, it's 5 different ways) and we have to select the line "bbbb" 2 times, since other variants do not fit. We get that we have 5 ways for the request.
Submitted Solution:
```
# E
n, m = map(int, input().split())
strings = []
for i in range(n):
strings.append(input())
cross = []
for i in range(m):
cross.append('')
for j in range(n):
cross[i] += strings[j][i]
dups = [[] for i in range(m)]
for i in range(m):
for j in range(i):
if cross[i] == cross[j]:
if dups[j] == []:
dups[j] = [j, i]
else:
dups[j].append(i)
break
count = 0
for i in range(m):
if len(dups[i]) > 0:
count += len(dups[i])-1
ans = 5**(n-m+count) % (10**9+7)
q = int(input())
for i in range(q):
test = input()
print(ans)
```
No
| 93,194 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a set of 4n strings of equal length, consisting of lowercase English letters "a", "b", "c", "d" and "e". Moreover, the set is split into n groups of 4 equal strings each. Vasya also has one special string a of the same length, consisting of letters "a" only.
Vasya wants to obtain from string a some fixed string b, in order to do this, he can use the strings from his set in any order. When he uses some string x, each of the letters in string a replaces with the next letter in alphabet as many times as the alphabet position, counting from zero, of the corresponding letter in string x. Within this process the next letter in alphabet after "e" is "a".
For example, if some letter in a equals "b", and the letter on the same position in x equals "c", then the letter in a becomes equal "d", because "c" is the second alphabet letter, counting from zero. If some letter in a equals "e", and on the same position in x is "d", then the letter in a becomes "c". For example, if the string a equals "abcde", and string x equals "baddc", then a becomes "bbabb".
A used string disappears, but Vasya can use equal strings several times.
Vasya wants to know for q given strings b, how many ways there are to obtain from the string a string b using the given set of 4n strings? Two ways are different if the number of strings used from some group of 4 strings is different. Help Vasya compute the answers for these questions modulo 109 + 7.
Input
The first line contains two integers n and m (1 β€ n, m β€ 500) β the number of groups of four strings in the set, and the length of all strings.
Each of the next n lines contains a string s of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e". This means that there is a group of four strings equal to s.
The next line contains single integer q (1 β€ q β€ 300) β the number of strings b Vasya is interested in.
Each of the next q strings contains a string b of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e" β a string Vasya is interested in.
Output
For each string Vasya is interested in print the number of ways to obtain it from string a, modulo 109 + 7.
Examples
Input
1 1
b
2
a
e
Output
1
1
Input
2 4
aaaa
bbbb
1
cccc
Output
5
Note
In the first example, we have 4 strings "b". Then we have the only way for each string b: select 0 strings "b" to get "a" and select 4 strings "b" to get "e", respectively. So, we have 1 way for each request.
In the second example, note that the choice of the string "aaaa" does not change anything, that is we can choose any amount of it (from 0 to 4, it's 5 different ways) and we have to select the line "bbbb" 2 times, since other variants do not fit. We get that we have 5 ways for the request.
Submitted Solution:
```
n,m=[int(i) for i in input().split()]
a='a'*m
s=[['abcde'.index(j) for j in input()] for i in range(n)]
b=[['abcde'.index(j) for j in input()] for i in range(int(input()))]
from itertools import product
def comb(n, k):
d=list(range(0, k))
yield d
while True:
i=k-1
while i>=0 and d[i]+k-i+1>n:
i-=1
if i<0:
return
d[i]+=1
for j in range(i+1, k):
d[j]=d[j-1]+1
yield d
def combs(sets, m):
for ci in comb(len(sets), m):
for cj in product(*(sets[i] for i in ci)):
yield cj
def num(p, u):
k=0
ss=[] if b[p][u] else ['0']
o=[str(i[u]) for i in s]*4
for i in range(1, n*4+1):
for j in combs(o, i):
if sum([int(l) for l in j])%5==int(b[p][u]):
j=sorted(list(j))
if j not in ss:
ss.append(j)
k+=1
return [str().join(i) for i in ss]
for p in range(len(b)):
t=None
for u in range(m):
if t==None:
t=set(num(p, u))
else:
t=t&set(num(p, u))
print(len(t))
```
No
| 93,195 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a set of 4n strings of equal length, consisting of lowercase English letters "a", "b", "c", "d" and "e". Moreover, the set is split into n groups of 4 equal strings each. Vasya also has one special string a of the same length, consisting of letters "a" only.
Vasya wants to obtain from string a some fixed string b, in order to do this, he can use the strings from his set in any order. When he uses some string x, each of the letters in string a replaces with the next letter in alphabet as many times as the alphabet position, counting from zero, of the corresponding letter in string x. Within this process the next letter in alphabet after "e" is "a".
For example, if some letter in a equals "b", and the letter on the same position in x equals "c", then the letter in a becomes equal "d", because "c" is the second alphabet letter, counting from zero. If some letter in a equals "e", and on the same position in x is "d", then the letter in a becomes "c". For example, if the string a equals "abcde", and string x equals "baddc", then a becomes "bbabb".
A used string disappears, but Vasya can use equal strings several times.
Vasya wants to know for q given strings b, how many ways there are to obtain from the string a string b using the given set of 4n strings? Two ways are different if the number of strings used from some group of 4 strings is different. Help Vasya compute the answers for these questions modulo 109 + 7.
Input
The first line contains two integers n and m (1 β€ n, m β€ 500) β the number of groups of four strings in the set, and the length of all strings.
Each of the next n lines contains a string s of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e". This means that there is a group of four strings equal to s.
The next line contains single integer q (1 β€ q β€ 300) β the number of strings b Vasya is interested in.
Each of the next q strings contains a string b of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e" β a string Vasya is interested in.
Output
For each string Vasya is interested in print the number of ways to obtain it from string a, modulo 109 + 7.
Examples
Input
1 1
b
2
a
e
Output
1
1
Input
2 4
aaaa
bbbb
1
cccc
Output
5
Note
In the first example, we have 4 strings "b". Then we have the only way for each string b: select 0 strings "b" to get "a" and select 4 strings "b" to get "e", respectively. So, we have 1 way for each request.
In the second example, note that the choice of the string "aaaa" does not change anything, that is we can choose any amount of it (from 0 to 4, it's 5 different ways) and we have to select the line "bbbb" 2 times, since other variants do not fit. We get that we have 5 ways for the request.
Submitted Solution:
```
# Efjewioaj
print(1)
print(1)
```
No
| 93,196 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.
Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.
Input
The first line contains an integer n (1 β€ n β€ 5Β·105) β the number of lines.
Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 β€ xi β€ 1023.
Output
Output an integer k (0 β€ k β€ 5) β the length of your program.
Next k lines must contain commands in the same format as in the input.
Examples
Input
3
| 3
^ 2
| 1
Output
2
| 3
^ 2
Input
3
& 1
& 3
& 5
Output
1
& 1
Input
3
^ 1
^ 2
^ 3
Output
0
Note
You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>.
Second sample:
Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.
Tags: bitmasks, constructive algorithms
Correct Solution:
```
z = 0
o = 1023
n = int(input())
for i in range(n):
a,b = input().split()
b = int(b)
if(a == "&"):
z = z&b
o = o&b
if (a == "^"):
z = z ^ b
o = o ^ b
if (a == "|"):
z = z | b
o = o | b
z = '{:010b}'.format(z)
o = '{:010b}'.format(o)
an = 0
r = 0
xo = 0
pw = 512
for i in range(10):
an+=pw
if(o[i]=='0' and z[i] == '0'): an-=pw
if (o[i] == '1' and z[i] == '1'): r+=pw
if (o[i] == '0' and z[i] == '1'): xo+=pw
pw//=2
print(3)
print("&",an)
print("|",r)
print("^",xo)
```
| 93,197 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.
Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.
Input
The first line contains an integer n (1 β€ n β€ 5Β·105) β the number of lines.
Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 β€ xi β€ 1023.
Output
Output an integer k (0 β€ k β€ 5) β the length of your program.
Next k lines must contain commands in the same format as in the input.
Examples
Input
3
| 3
^ 2
| 1
Output
2
| 3
^ 2
Input
3
& 1
& 3
& 5
Output
1
& 1
Input
3
^ 1
^ 2
^ 3
Output
0
Note
You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>.
Second sample:
Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.
Tags: bitmasks, constructive algorithms
Correct Solution:
```
from sys import stdin
data = stdin.readlines()
remain = -10
invert = -20
m = [remain] * 10
for i, st in enumerate(data):
if i == 0: continue
op, x = st.strip().split()
x = int(x)
for j in range(10):
bit = x % 2
if op == '&' and bit == 0:
m[j] = 0
elif op == '|' and bit == 1:
m[j] = 1
elif op == '^' and bit == 1:
if m[j] == 0:
m[j] = 1
elif m[j] == 1:
m[j] = 0
elif m[j] == remain:
m[j] = invert
elif m[j] == invert:
m[j] = remain
x = x // 2
print(3)
and_const = 0
for i, v in enumerate(m):
if v != 0:
and_const += 2**i
or_const = 0
for i, v in enumerate(m):
if v == 1:
or_const += 2**i
xor_const = 0
for i, v in enumerate(m):
if v == invert:
xor_const += 2**i
print('&', and_const)
print('|', or_const)
print('^', xor_const)
```
| 93,198 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.
Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.
Input
The first line contains an integer n (1 β€ n β€ 5Β·105) β the number of lines.
Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 β€ xi β€ 1023.
Output
Output an integer k (0 β€ k β€ 5) β the length of your program.
Next k lines must contain commands in the same format as in the input.
Examples
Input
3
| 3
^ 2
| 1
Output
2
| 3
^ 2
Input
3
& 1
& 3
& 5
Output
1
& 1
Input
3
^ 1
^ 2
^ 3
Output
0
Note
You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>.
Second sample:
Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.
Tags: bitmasks, constructive algorithms
Correct Solution:
```
from math import*
n = int(input())
x = 0
y = 1023
for i in range(n):
gg = input().split()
if gg[0] == '&':
x &= int(gg[1])
y &= int(gg[1])
if gg[0] == '|':
x |= int(gg[1])
y |= int(gg[1])
if gg[0] == '^':
x ^= int(gg[1])
y ^= int(gg[1])
print(3)
print('|', x & y)
print('&', x | y)
print('^', x & (y ^ 1023))
```
| 93,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.