message stringlengths 2 65.1k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 0 108k | cluster float64 14 14 | __index_level_0__ int64 0 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
T=int(input())
for i in range(T):
n=int(input())
arr=list(map(int,input().split()))
l=[]
r=[]
for i in range(n):
if i%2==0:
l.append(arr[i])
else:
r.append(arr[i])
l.sort()
r.sort()
arr.sort()
z=[]
for i in range(n):
if i%2==0:
z.append(l.pop(0))
else:
z.append(r.pop(0))
if z==arr:
print("YES")
else:
print("NO")
``` | instruction | 0 | 55,852 | 14 | 111,704 |
Yes | output | 1 | 55,852 | 14 | 111,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
dp=list(map(int,input().split()))
dp_even=[0]*(10**5+1)
dp_odd=[0]*(10**5+1)
for i in range(n):
if i%2==0:
dp_even[dp[i]]+=1
else:
dp_odd[dp[i]]+=1
dp=sorted(dp)
for i in range(n):
if i%2==0:
dp_even[dp[i]]-=1
else:
dp_odd[dp[i]]-=1
flag=0
for i in range(n):
if dp_odd[dp[i]]|dp_even[dp[i]]:
print("NO")
flag=1
break
if flag==0:
print("YES")
``` | instruction | 0 | 55,853 | 14 | 111,706 |
Yes | output | 1 | 55,853 | 14 | 111,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
# for every number count how many times it occurs and of which how many are at
# even position and how many are at odd position
# then sort the array and again count even and odd positions for each no.
# then check if even is same or odd is same
for _ in range(int(input().strip())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
flag= 0
c = max(arr)
cnt = [[0,0] for i in range(c+1)]
for i in range(0,n):
cnt[arr[i]][i%2]+=1
arr.sort()
for i in range(0,n):
cnt[arr[i]][i%2]-=1
for i in range(n):
if(cnt[arr[i]][0]!=0 or cnt[arr[i]][1]!=0):
print("NO")
flag = 1
break
if(flag==0):
print("YES")
``` | instruction | 0 | 55,854 | 14 | 111,708 |
Yes | output | 1 | 55,854 | 14 | 111,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
from sys import stdin
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
lst = list(map(int, stdin.readline().split()))
srt = sorted(lst)
dic = {}
for i in range(len(srt)):
num = srt[i]
if num not in dic:
dic[num] = [0, 0]
dic[num][i%2] += 1
for i in range(len(lst)):
num = lst[i]
dic[num][i%2] -= 1
if dic[num][i%2] < 0:
print("NO")
break
else:
print("YES")
``` | instruction | 0 | 55,855 | 14 | 111,710 |
Yes | output | 1 | 55,855 | 14 | 111,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
from math import *
from collections import *
from functools import *
from bisect import *
from itertools import *
from heapq import *
import sys
inf = float('inf')
ninf = -float('inf')
ip = sys.stdin.readline
alphal = "abcdefghijklmnopqrstuvwxyz"
alphau = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
mod = (10 ** 9) + 7
def ipl(): return list(map(int, ip().split()))
def ipn(): return int(ip())
def ipf(): return float(ip())
def solve():
n = ipn()
a = ipl()
b = sorted(a)
h = defaultdict(int)
bi = defaultdict(list)
for i in range(n):
bi[b[i]].append(i)
for i, e in enumerate(a):
idx = bi[e].pop()
if abs(idx-i) % 2 != 0:
h[e] += 1
for k, v in h.items():
if v % 2 != 0:
print("NO")
return
print("YES")
t = ipn()
for _ in range(t):
solve()
``` | instruction | 0 | 55,856 | 14 | 111,712 |
No | output | 1 | 55,856 | 14 | 111,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
from collections import deque
T=int(input())
for i in range(T):
n=int(input())
direction=[1]*n
arr=list(map(int,input().split()))
hcheck=sorted(arr)
hdict=dict()
for i in range(n):
if arr[i] in hdict:
hdict[arr[i]].append(i)
else:
hdict[arr[i]]=deque([i])
for i in range(n):
# if hcheck[i]!=arr[i]:
l=hdict[hcheck[i]].popleft()
if abs(l-i)%2!=0:
if direction[i]==0:
direction[i]=1
else:
direction[i]=0
t=0
for k in range(n):
if direction[k]!=1:
t=1
print("NO")
break
if t!=1:
print("YES")
``` | instruction | 0 | 55,857 | 14 | 111,714 |
No | output | 1 | 55,857 | 14 | 111,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
from collections import deque
import heapq
from math import sqrt
import operator
from operator import itemgetter
import sys
import copy
inf_var = 0
if inf_var == 1:
inf = open('input.txt', 'r')
else:
inf = sys.stdin
input = inf.readline
# sys.stdout = open('output.txt', 'w')
def read_one_int():
return int(input().rstrip('\n'))
def read_one_float():
return float(input().rstrip('\n'))
def read_list_of_ints():
res = [int(val) for val in (input().rstrip('\n')).split(' ')]
return res
def read_str():
return input().rstrip()
def main():
tests = read_one_int()
for _ in range(tests):
n = read_one_int()
numbers = read_list_of_ints()
num_positions = {}
num_sums = {}
for i, num in enumerate(numbers):
if num not in num_positions:
num_sums[num] = 0
num_positions[num] = [i]
continue
num_positions[num].append(i)
numbers.sort()
for i, num in enumerate(numbers):
num_sums[num] += abs(num_positions[num].pop() - i)
res = 'YES'
for _, sums in num_sums.items():
if sums % 2:
res = 'NO'
break
print(res)
if __name__== '__main__':
main()
``` | instruction | 0 | 55,858 | 14 | 111,716 |
No | output | 1 | 55,858 | 14 | 111,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
dp_even=[0]*(10**2)
dp_odd=[0]*(10**2)
for _ in range(int(input())):
n=int(input())
dp=list(map(int,input().split()))
for i in range(n):
if i%2==0:
dp_even[dp[i]]+=1
else:
dp_odd[dp[i]]+=1
dp=sorted(dp)
for i in range(n):
if i%2==0:
dp_even[dp[i]]-=1
else:
dp_odd[dp[i]]-=1
flag=0
for i in range(n):
if dp_odd[dp[i]]|dp_even[dp[i]]:
print("NO")
flag=1
break
if flag==0:
print("YES")
``` | instruction | 0 | 55,859 | 14 | 111,718 |
No | output | 1 | 55,859 | 14 | 111,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The marmots need to prepare k problems for HC2 over n days. Each problem, once prepared, also has to be printed.
The preparation of a problem on day i (at most one per day) costs ai CHF, and the printing of a problem on day i (also at most one per day) costs bi CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine).
What is the minimum cost of preparation and printing?
Input
The first line of input contains two space-separated integers n and k (1 β€ k β€ n β€ 2200). The second line contains n space-separated integers a1, ..., an (<image>) β the preparation costs. The third line contains n space-separated integers b1, ..., bn (<image>) β the printing costs.
Output
Output the minimum cost of preparation and printing k problems β that is, the minimum possible sum ai1 + ai2 + ... + aik + bj1 + bj2 + ... + bjk, where 1 β€ i1 < i2 < ... < ik β€ n, 1 β€ j1 < j2 < ... < jk β€ n and i1 β€ j1, i2 β€ j2, ..., ik β€ jk.
Example
Input
8 4
3 8 7 9 9 4 6 8
2 5 9 4 3 8 9 1
Output
32
Note
In the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8. | instruction | 0 | 56,103 | 14 | 112,206 |
Tags: binary search, flows, graphs
Correct Solution:
```
from itertools import count
from collections import deque
from heapq import heappop, heappush
class Edge(object):
__slots__ = ('x', 'y', 'cap', 'cost', 'inv')
def __repr__(self):
return f'{self.x}-->{self.y} ({self.cap} , {self.cost})'
class MCFP(list):
inf = float('inf')
def add(G, x, y, cap, cost):
G.extend(([] for i in range(max(0,max(x,y)+1-len(G)))))
e = Edge()
e.x=x ; e.y=y; e.cap=cap; e.cost=cost
z = Edge()
z.x=y ; z.y=x; z.cap=0; z.cost=-cost
e.inv=z ; z.inv=e
G[x].append(e)
G[y].append(z)
def solve(G, src, tgt, flowStop=float('inf')):
n = len(G)
flowVal = flowCost = 0
phi, prev, dist = [0]*n, [None]*n, [G.inf]*n
for it in count():
G.shortest(src, phi, prev, dist, tgt)
if prev[tgt]==None:
break
p = list(G.backward(tgt, src, prev))
z = min(e.cap for e in p)
for e in p: e.cap -= z ; e.inv.cap += z
flowVal += z
flowCost += z * (dist[tgt] - phi[src] + phi[tgt])
if flowVal==flowStop: break
for i in range(n):
if prev[i] != None:
phi[i] += dist[i]
dist[i] = G.inf
#print(it)
return flowVal, flowCost
def backward(G, x, src, prev):
while x!=src: e = prev[x] ; yield e ; x = e.x
def shortest_(G, src, phi, prev, dist, tgt):
prev[tgt] = None
dist[src] = 0
Q = [(dist[src], src)]
k = 0
while Q:
k += 1
d, x = heappop(Q)
if dist[x]!=d: continue
for e in G[x]:
if e.cap <= 0: continue
dy = dist[x] + phi[x] + e.cost - phi[e.y]
if dy < dist[e.y]:
dist[e.y] = dy
prev[e.y] = e
heappush(Q, (dy, e.y))
print(k)
return
def shortest(G, src, phi, prev, dist, tgt):
prev[tgt] = None
dist[src] = 0
Q = deque([src])
inQ = [0]*len(G)
sumQ = 0
while Q:
x = Q.popleft()
inQ[x] = 0
sumQ -= dist[x]
for e in G[x]:
if e.cap <= 0: continue
dy = dist[x] + phi[x] + e.cost - phi[e.y]
if dy < dist[e.y]:
dist[e.y] = dy
prev[e.y] = e
if inQ[e.y]==0:
inQ[e.y]=1
sumQ += dy
if Q and dy > dist[Q[0]]: Q.append(e.y)
else: Q.appendleft(e.y)
avg = sumQ/len(Q)
while dist[Q[0]] > avg: Q.append(Q.popleft())
return
def shortest_(G, src, phi, prev, dist, tgt):
prev[tgt] = None
dist[src] = 0
H = [(0, src)]
inQ = [0]*len(G)
k = 0
while H:
k += 1
d, x = heappop(H)
if dist[x]!=d: continue
for e in G[x]:
if e.cap <= 0: continue
dy = dist[x] + phi[x] + e.cost - phi[e.y]
if dy < dist[e.y]:
dist[e.y] = dy
prev[e.y] = e
heappush(H, (dy, e.y))
print(k)
return
import sys, random
ints = (int(x) for x in sys.stdin.read().split())
sys.setrecursionlimit(3000)
def main():
n, k = (next(ints) for i in range(2))
a = [next(ints) for i in range(n)]
b = [next(ints) for i in range(n)]
G = MCFP()
src, tgt, the_src = 2*n+1, 2*n+2, 2*n+3
G.add(the_src, src, k, 0)
for i in range(n):
G.add(src, i, 1, 0)
G.add(i, i+n, 1, a[i])
G.add(i+n, tgt, 1, b[i])
if i+1<n:
G.add(i, i+1, n, 0)
G.add(i+n, i+n+1, n, 0)
flowVal, ans = G.solve(the_src, tgt, k)
assert flowVal == k
print(ans)
return
def test(n,k):
R = random.Random(0)
yield n ; yield k
for i in range(n): yield R.randint(1, 10**9)
for i in range(n): yield R.randint(1, 10**9)
#ints=test(1000, 800)
main()
``` | output | 1 | 56,103 | 14 | 112,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The marmots need to prepare k problems for HC2 over n days. Each problem, once prepared, also has to be printed.
The preparation of a problem on day i (at most one per day) costs ai CHF, and the printing of a problem on day i (also at most one per day) costs bi CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine).
What is the minimum cost of preparation and printing?
Input
The first line of input contains two space-separated integers n and k (1 β€ k β€ n β€ 2200). The second line contains n space-separated integers a1, ..., an (<image>) β the preparation costs. The third line contains n space-separated integers b1, ..., bn (<image>) β the printing costs.
Output
Output the minimum cost of preparation and printing k problems β that is, the minimum possible sum ai1 + ai2 + ... + aik + bj1 + bj2 + ... + bjk, where 1 β€ i1 < i2 < ... < ik β€ n, 1 β€ j1 < j2 < ... < jk β€ n and i1 β€ j1, i2 β€ j2, ..., ik β€ jk.
Example
Input
8 4
3 8 7 9 9 4 6 8
2 5 9 4 3 8 9 1
Output
32
Note
In the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8. | instruction | 0 | 56,104 | 14 | 112,208 |
Tags: binary search, flows, graphs
Correct Solution:
```
from collections import deque
from heapq import heappop, heappush
class Edge(object):
__slots__ = ('x', 'y', 'cap', 'cost', 'inv')
def __repr__(self):
return '{e.x}-->{e.y} ({e.cap} , {e.cost})'.format(e=self)
class MCFP(list):
def add(G, x, y, cap, cost):
n = max(x, y) + 1
while len(G)<n: G.append([])
e = Edge() ; G[x].append(e)
w = Edge() ; G[y].append(w)
e.x=x ; e.y=y; e.cap=cap; e.cost=cost ; w.inv=e
w.x=y ; w.y=x; w.cap=0; w.cost=-cost ; e.inv=w
def solve(G, src, tgt, flowStop=float('inf'), inf=float('inf')):
flowVal = flowCost = 0
n = len(G)
G.inQ = [0]*n
G.phi = h = [0]*n
G.prev = p = [None]*n
G.dist = d = [inf]*n
G.SPFA(src)
while p[tgt]!=None and flowVal<flowStop:
b = [] ; x = tgt
while x!=src: b.append(p[x]) ; x=p[x].x
z = min(e.cap for e in b)
for e in b: e.cap-=z ; e.inv.cap+=z
flowVal += z
flowCost += z * (d[tgt] - h[src] + h[tgt])
for i in range(n):
if p[i]!=None: h[i]+=d[i] ; d[i]=inf
p[tgt] = None
G.SPFA(src)
return flowVal, flowCost
def SPFA(G, src):
inQ = G.inQ ; prev = G.prev
d = G.dist ; h = G.phi
d[src] = 0
Q = deque([src])
while Q:
x = Q.popleft()
inQ[x] = 0
for e in G[x]:
if e.cap <= 0: continue
y = e.y ; dy = d[x] + h[x] + e.cost - h[y]
if dy < d[y]:
d[y] = dy ; prev[y] = e
if inQ[y]==0:
inQ[y] = 1
if not Q or dy > d[Q[0]]: Q.append(y)
else: Q.appendleft(y)
return
import sys, random
ints = (int(x) for x in sys.stdin.read().split())
sys.setrecursionlimit(3000)
def main():
n, k = (next(ints) for i in range(2))
a = [next(ints) for i in range(n)]
b = [next(ints) for i in range(n)]
G = MCFP()
src, tgt = 2*n+1, 2*n+2
for i in range(n):
G.add(src, i, 1, 0)
G.add(i, i+n, 1, a[i])
G.add(i+n, tgt, 1, b[i])
if i+1<n:
G.add(i, i+1, n, 0)
G.add(i+n, i+n+1, n, 0)
flowVal, ans = G.solve(src, tgt, k)
assert flowVal == k
print(ans)
#print(G)
return
def test(n,k):
R = random.Random(0)
yield n ; yield k
for i in range(n): yield R.randint(1, 10**9)
for i in range(n): yield R.randint(1, 10**9)
#ints=test(1000, 800)
main()
``` | output | 1 | 56,104 | 14 | 112,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the constraints.
Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of n consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the i-th picture has beauty a_i.
Vova wants to repost exactly x pictures in such a way that:
* each segment of the news feed of at least k consecutive pictures has at least one picture reposted by Vova;
* the sum of beauty values of reposted pictures is maximum possible.
For example, if k=1 then Vova has to repost all the pictures in the news feed. If k=2 then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.
Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
Input
The first line of the input contains three integers n, k and x (1 β€ k, x β€ n β€ 5000) β the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the beauty of the i-th picture.
Output
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement.
Otherwise print one integer β the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
Examples
Input
5 2 3
5 1 3 10 1
Output
18
Input
6 1 5
10 30 30 70 10 10
Output
-1
Input
4 3 1
1 100 1 1
Output
100 | instruction | 0 | 56,423 | 14 | 112,846 |
Tags: data structures, dp
Correct Solution:
```
n, k, x = map(int, input().split())
a = [None] + list(map(int, input().split()))
lo, hi = 0, 10 ** 9 * 5000
q = [None] * (n + 1)
def get(mid):
f, r = 0, 0
q[0] = 0, 0, 0
for i in range(1, n + 1):
if q[r][2] == i - k - 1: r += 1
cur = q[r][0] + a[i] - mid, q[r][1] + 1, i
while r <= f and q[f] <= cur: f -= 1
f += 1
q[f] = cur
if q[r][2] == n - k: r += 1
return q[r]
while lo < hi:
mid = (lo + hi + 1) >> 1
_, cnt, _ = get(mid)
if cnt >= x:
lo = mid
else:
hi = mid - 1
sm, _, _ = get(lo)
ans = max(-1, sm + x * lo)
print(ans)
``` | output | 1 | 56,423 | 14 | 112,847 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. | instruction | 0 | 56,800 | 14 | 113,600 |
Tags: greedy, implementation, two pointers
Correct Solution:
```
p = input()
a = list(input())
a.append('')
count = 0
while len(set(a)) == 3:
for i in range(len(a)):
if a[i] == 'D':
if count < 0:
a[i] = ''
count+=1
if a[i] == 'R':
if count > 0:
a[i] = ''
count-=1
for ss in set(a):
if ss:
print(ss)
``` | output | 1 | 56,800 | 14 | 113,601 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. | instruction | 0 | 56,801 | 14 | 113,602 |
Tags: greedy, implementation, two pointers
Correct Solution:
```
n = int(input())
arr = list(input())
r = arr.count('R')
d = arr.count('D')
i = j = 0
while r > 0 and d > 0:
while arr[j] == arr[i] or arr[j] == 'O':
j = (j + 1) % n
if arr[j] == 'R':
r -= 1
else:
d -= 1
arr[j] = 'O'
c = i
i = (i + 1) % n
while arr[i] == 'O':
i = (i + 1) % n
if i < c:
j = i = 0
n = r + d
for x in range(n):
while arr[i] == 'O':
i += 1
arr[j] = arr[i]
j += 1
i += 1
i = j = 0
if r > 0:
print('R')
else:
print('D')
``` | output | 1 | 56,801 | 14 | 113,603 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. | instruction | 0 | 56,802 | 14 | 113,604 |
Tags: greedy, implementation, two pointers
Correct Solution:
```
input()
a = list(input()) + ['']
cnt = 0
while len(set(a)) == 3:
for i, v in enumerate(a):
if v == 'D':
if cnt < 0:
a[i] = ''
cnt += 1
if v == 'R':
if cnt > 0:
a[i] = ''
cnt -= 1
for ss in set(a):
if ss:
print(ss)
``` | output | 1 | 56,802 | 14 | 113,605 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. | instruction | 0 | 56,803 | 14 | 113,606 |
Tags: greedy, implementation, two pointers
Correct Solution:
```
import collections
n = int(input())
s = input()
R, D = collections.deque(), collections.deque()
for i in range(n):
if s[i] == 'R': R.append(i)
else: D.append(i)
#print(R)
#print(D)
while R and D:
r = R.popleft()
d = D.popleft()
#print(str(r) + " is R and D " + str(d))
if r < d:
R.append(n + r)
else:
D.append(n + d)
if D:
print('D')
else:
print('R')
``` | output | 1 | 56,803 | 14 | 113,607 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. | instruction | 0 | 56,804 | 14 | 113,608 |
Tags: greedy, implementation, two pointers
Correct Solution:
```
import collections
n=int(input())
s=input()
d,r=collections.deque([]),collections.deque([])
for i in range(n):
if s[i]=='D':
d.append(i+1)
else:
r.append(i+1)
ld=len(d)
lr=len(r)
while(ld!=0 and lr!=0):
if d[0]<r[0]:
lr-=1
d.append(d[0]+n)
d.popleft()
r.popleft()
else:
ld-=1
r.append(r[0]+n)
r.popleft()
d.popleft()
if ld==0:
print("R")
else:
print("D")
``` | output | 1 | 56,804 | 14 | 113,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. | instruction | 0 | 56,805 | 14 | 113,610 |
Tags: greedy, implementation, two pointers
Correct Solution:
```
from collections import deque
n = int(input())
line = list(input())
D = deque()
R = deque()
for i in range(n):
if line[i] == 'D':
D.append(i)
else:
R.append(i)
while D and R:
d = D.popleft()
r = R.popleft()
if d < r:
D.append(d + n)
else:
R.append(r + n)
if D:
print('D')
else:
print('R')
``` | output | 1 | 56,805 | 14 | 113,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. | instruction | 0 | 56,806 | 14 | 113,612 |
Tags: greedy, implementation, two pointers
Correct Solution:
```
#!/usr/bin/env python3
from collections import deque
n = int(input())
p = list(input())
rq = deque()
dq = deque()
for i, e in enumerate(p):
if e == 'D':
dq.append(i)
else:
rq.append(i)
while rq and dq:
d = dq.popleft()
r = rq.popleft()
if d > r:
rq.append(r+n)
else:
dq.append(d+n)
if rq:
print('R')
else:
print('D')
``` | output | 1 | 56,806 | 14 | 113,613 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. | instruction | 0 | 56,807 | 14 | 113,614 |
Tags: greedy, implementation, two pointers
Correct Solution:
```
n = int(input())
a = []
for i in input():
a.append(i)
r, d = 0, 0
was_r, was_d = True, True
while True:
if was_r and was_d:
was_r, was_d = False, False
else:
break
for i in range(len(a)):
if a[i] == "R":
was_r = True
if r != 0:
r -= 1
a[i] = 0
else:
d += 1
elif a[i] == "D":
was_d = True
if d != 0:
d -= 1
a[i] = 0
else:
r += 1
if was_r:
print("R")
else:
print("D")
``` | output | 1 | 56,807 | 14 | 113,615 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.
Submitted Solution:
```
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
ilelec = lambda: map(int1,input().split())
alelec = lambda: list(map(int1, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
n = int(input())
s = [*input()]
R = deque()
D = deque()
for i in range(n):
if s[i] == 'R':
R.append(i)
else:
D.append(i)
l = n-1
while True:
l+=1
if not R:
print('D')
break
if not D:
print('R')
break
if R[0] < D[0]:
D.popleft()
v = R.popleft()
R.append(l)
else:
R.popleft()
v = D.popleft()
D.append(l)
``` | instruction | 0 | 56,808 | 14 | 113,616 |
Yes | output | 1 | 56,808 | 14 | 113,617 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.
Submitted Solution:
```
#!/usr/bin/env pypy3
# -*- coding: UTF-8 -*-
#import heapq
from collections import deque
n=int(input())
s=input()
r,d=deque(),deque()
for a,i in enumerate(s):
if i=='R':
r.append(a)
else:
d.append(a)
while len(r) and len(d):
R=r.popleft()
D=d.popleft()
if R<D:
r.append(R+n)
else:
d.append(D+n)
print(['R','D'][len(d)>0])
``` | instruction | 0 | 56,809 | 14 | 113,618 |
Yes | output | 1 | 56,809 | 14 | 113,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.
Submitted Solution:
```
import heapq
n=int(input())
s=input()
r,d=[],[]
for a,i in enumerate(s):
if i=='R':
heapq.heappush(r,a)
else:
heapq.heappush(d,a)
while len(r) and len(d):
R=heapq.heappop(r)
D=heapq.heappop(d)
if R<D:
heapq.heappush(r,R+n)
else:
heapq.heappush(d,D+n)
print(['R','D'][len(d)>0])
``` | instruction | 0 | 56,810 | 14 | 113,620 |
Yes | output | 1 | 56,810 | 14 | 113,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.
Submitted Solution:
```
from collections import deque
n = int(input())
s = input()
R = deque()
D = deque()
for i in range(n):
if s[i] == 'D':
D.append(i)
else:
R.append(i)
k = 0
while len(R) and len(D):
a = R.popleft()
b = D.popleft()
if a == k:
R.append(a + n)
elif b == k:
D.append(b + n)
else:
R.appendleft(a)
D.appendleft(b)
k += 1
if len(R):
print('R')
else:
print('D')
``` | instruction | 0 | 56,811 | 14 | 113,622 |
Yes | output | 1 | 56,811 | 14 | 113,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.
Submitted Solution:
```
input()
x=input()
y=list(x)
i=0
while len(y)!=1:
if i>=len(y):
i=0
else:
if y[i]=='D':
if ''.join(y).find('R')==-1:
print('D')
break
else:
del(y[len(y)-1-y.index('R')])
else:
if ''.join(y).find('D')==-1:
print('R')
break
else:
del(y[len(y)-1-y.index('D')])
i+=1
if len(y)==1:
print(y[0])
break
``` | instruction | 0 | 56,812 | 14 | 113,624 |
No | output | 1 | 56,812 | 14 | 113,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.
Submitted Solution:
```
n=int(input())
ch=input()
d=0
while d<n:
if ch[d]=='R':
break
d=d+1
r=n-d
if 2*(d)>r:
print('D')
else:
print('R')
``` | instruction | 0 | 56,813 | 14 | 113,626 |
No | output | 1 | 56,813 | 14 | 113,627 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.
Submitted Solution:
```
n=int(input())
a=input()
i=0
while len(a)!=1:
if a[i]=='D' and a.count('R')!=0:
c=a.index('R')
a=a[:c]+a[c+1:]
elif a[i]=='R' and a.count('D')!=0:
c = a.index('D')
a = a[:c] + a[c + 1:]
if i>len(a)-2:
i=0
else:
i+=1
if a.count('D')==len(a):
a='D'
elif a.count('R')==len(a):
a='R'
print(a)
``` | instruction | 0 | 56,814 | 14 | 113,628 |
No | output | 1 | 56,814 | 14 | 113,629 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:
1. Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).
2. When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.
3. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.
4. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction.
You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of employees.
The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.
Output
Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.
Examples
Input
5
DDRRR
Output
D
Input
6
DDRRRR
Output
R
Note
Consider one of the voting scenarios for the first sample:
1. Employee 1 denies employee 5 to vote.
2. Employee 2 denies employee 3 to vote.
3. Employee 3 has no right to vote and skips his turn (he was denied by employee 2).
4. Employee 4 denies employee 2 to vote.
5. Employee 5 has no right to vote and skips his turn (he was denied by employee 1).
6. Employee 1 denies employee 4.
7. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.
Submitted Solution:
```
n = int(input())
s = input()
dcount = 0
rcount = 0
for i in range(len(s)):
if s[i] == 'D':
if dcount < 0:
dcount+=1
else:
dcount += 1
rcount -= 1
elif s[i] == 'R':
if rcount < 0:
rcount+=1
else:
rcount += 1
dcount -= 1
if rcount == dcount:
if s[-1] == 'D':
rcount += 1
elif s[-1] == 'R':
dcount += 1
print("R" if rcount > dcount else "D")
``` | instruction | 0 | 56,815 | 14 | 113,630 |
No | output | 1 | 56,815 | 14 | 113,631 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations. | instruction | 0 | 57,196 | 14 | 114,392 |
Tags: greedy
Correct Solution:
```
n,m=map(int,input().split())
l=[int(x) for x in input().split()]
pairs=[[] for i in range(n+1)]
ans=0
N=[0 for i in range(n+1)]
for i in range(m):
a,b=map(int,input().split())
pairs[b].append(a)
for i in range(n-1,-1,-1):
if N[l[i]]==n-1-i-ans and i!=n-1:
ans+=1
else:
for I in pairs[l[i]]:
N[I]+=1
print(ans)
``` | output | 1 | 57,196 | 14 | 114,393 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations. | instruction | 0 | 57,197 | 14 | 114,394 |
Tags: greedy
Correct Solution:
```
n, m = map(int, input().split())
p = list([int(s)-1 for s in input().split()])
nastya = p[-1]
good = [False] * n
swaps = [[] for _ in range(n)]
counts = [0] * n
for _ in range(m):
u, v = map(int, input().split())
u-=1
v-=1
if v==nastya:
good[u] = True
else:
swaps[v].append(u)
total = 0
bad_count = 0
for i, pupil in enumerate(p[-2::-1]):
if good[pupil] and counts[pupil] >= bad_count:
total += 1
else:
bad_count += 1
for u in swaps[pupil]:
counts[u] += 1
print(total)
``` | output | 1 | 57,197 | 14 | 114,395 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations. | instruction | 0 | 57,198 | 14 | 114,396 |
Tags: greedy
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n, m = map(int, input().split())
p = list(map(int, input().split()))
ok = [set() for _ in range(n+1)]
for _ in range(m):
u, v = map(int, input().split())
ok[u].add(v)
ans = 0
s = {p[n-1]}
for i in range(n-2, -1, -1):
if s <= ok[p[i]]:
ans += 1
else:
s.add(p[i])
print(ans)
``` | output | 1 | 57,198 | 14 | 114,397 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations. | instruction | 0 | 57,199 | 14 | 114,398 |
Tags: greedy
Correct Solution:
```
# Testing
# https://codeforces.com/contest/1136/submission/51182491
# with quick input
import os
from io import BytesIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())
n, m = mi()
a = li()
pairs = [li() for _ in range(m)]
last = a.pop()
friend = [[] for i in range(n + 1)]
for u, v in pairs:
friend[u].append(v)
mark = [0] * (n + 1)
mark[last] = 1
req = 1
ans = 0
for i in range(n - 2, -1, -1):
u = a[i]
cnt = sum(mark[v] for v in friend[u])
if cnt == req:
ans += 1
else:
mark[u] = 1
req += 1
print(ans)
``` | output | 1 | 57,199 | 14 | 114,399 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations. | instruction | 0 | 57,200 | 14 | 114,400 |
Tags: greedy
Correct Solution:
```
import sys
input = sys.stdin.readline
print = sys.stdout.write
n,m=map(int,input().split())
q=list(map(int,input().split()))
pos={}
for i in range(n):
pos[q[i]-1]=i
drt={}
for i in range(n):
drt[i]=0
part=set()
for i in range(m):
u,v=map(int,input().split())
if pos[u-1]<pos[v-1]:
drt[u-1]+=1
if v==q[-1]:
part.add(pos[u-1])
b=[0 for i in range(n)]
for i in part:
b[i]=1
ans=0;l=0
for i in range(n-1,-1,-1):
if b[i]==1 and drt[q[i]-1]>=n-1-pos[q[i]-1]-l:
l+=1
ans+=1
print(str(ans))
``` | output | 1 | 57,200 | 14 | 114,401 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations. | instruction | 0 | 57,201 | 14 | 114,402 |
Tags: greedy
Correct Solution:
```
def readLine():
a = input()
return [int(i) for i in a.split(' ')]
nm = readLine()
n, m = nm[0], nm[1]
a = readLine()
pos = [0 for _ in range(n + 1)]
for i, val in enumerate(a):
pos[val] = i
g = [[] for _ in range(n + 1)]
for i in range(m):
xy = readLine()
x, y = xy[0], xy[1]
g[y].append(x)
used = [0 for _ in range(n + 1)]
used[a[n - 1]] = -1
ans = 0
l = []
for j in range(n):
i = n - j - 1
if used[a[i]] < len(l):
l.append(a[i])
for _, val in enumerate(g[a[i]]):
used[val] = used[val] + 1
else:
ans = ans + 1
print(ans)
``` | output | 1 | 57,201 | 14 | 114,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations. | instruction | 0 | 57,202 | 14 | 114,404 |
Tags: greedy
Correct Solution:
```
import sys
import heapq
import math
from enum import Enum
lines = sys.stdin.read().splitlines()
n, m = map(int, lines[0].split(' '))
positionToNumber = [int(x)-1 for x in lines[1].split(' ')]
numberToPosition = [0]*n
for i in range(0, len(positionToNumber)):
numberToPosition[positionToNumber[i]] = i
# print('numberToOrder: ' + str(numberToOrder))
letsInFront = []
for i in range(0, n):
letsInFront.append(set())
for i in range(0, m):
a, b = list(map(int, lines[i+2].split(' ')))
# a lets b in front
indexA = a-1
indexB = b-1
letsInFront[numberToPosition[indexA]].add(numberToPosition[indexB])
# for i in range(0, n):
# letsInFront[i].sort()
# print(bitmaps)
count = 0
let = set()
let.add(n-1)
# print(letsInFront)
for i in reversed(range(0, n-1)):
found = True
if len(let) > len(letsInFront[i]):
found = False
else:
for j in let:
if j not in letsInFront[i]:
found = False
break
if not found:
let.add(i)
else:
count += 1
print(count)
``` | output | 1 | 57,202 | 14 | 114,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations. | instruction | 0 | 57,203 | 14 | 114,406 |
Tags: greedy
Correct Solution:
```
# SHRi GANESHA author: Kunal Verma #
import os
import sys
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict
from functools import reduce
from io import BytesIO, IOBase
from itertools import combinations
from math import gcd, inf, sqrt, ceil, floor
#sys.setrecursionlimit(2*10**5)
def lcm(a, b):
return (a * b) // gcd(a, b)
'''
mod = 10 ** 9 + 7
fac = [1]
for i in range(1, 2 * 10 ** 5 + 1):
fac.append((fac[-1] * i) % mod)
fac_in = [pow(fac[-1], mod - 2, mod)]
for i in range(2 * 10 ** 5, 0, -1):
fac_in.append((fac_in[-1] * i) % mod)
fac_in.reverse()
def comb(a, b):
if a < b:
return 0
return (fac[a] * fac_in[b] * fac_in[a - b]) % mod
'''
MAXN = 1000004
spf = [0 for i in range(MAXN)]
def sieve():
spf[1] = 1
for i in range(2, MAXN):
spf[i] = i
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, ceil(sqrt(MAXN))):
if (spf[i] == i):
for j in range(i * i, MAXN, i):
if (spf[j] == j):
spf[j] = i
def getFactorization(x):
ret = Counter()
while (x != 1):
ret[spf[x]] += 1
x = x // spf[x]
return ret
def printDivisors(n):
i = 2
z = [1, n]
while i <= sqrt(n):
if (n % i == 0):
if (n / i == i):
z.append(i)
else:
z.append(i)
z.append(n // i)
i = i + 1
return z
def create(n, x, f):
pq = len(bin(n)[2:])
if f == 0:
tt = min
else:
tt = max
dp = [[inf] * n for _ in range(pq)]
dp[0] = x
for i in range(1, pq):
for j in range(n - (1 << i) + 1):
dp[i][j] = tt(dp[i - 1][j], dp[i - 1][j + (1 << (i - 1))])
return dp
def enquiry(l, r, dp, f):
if l > r:
return inf if not f else -inf
if f == 1:
tt = max
else:
tt = min
pq1 = len(bin(r - l + 1)[2:]) - 1
return tt(dp[pq1][l], dp[pq1][r - (1 << pq1) + 1])
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
x = []
for i in range(2, n + 1):
if prime[i]:
x.append(i)
return x
def main():
from collections import Counter
n, m = map(int, input().split())
a = [int(x) for x in input().split()]
adj = [[] for i in range(n + 1)]
xx = a[-1]
ind = Counter()
for i in range(n):
ind[a[i]] = i
for i in range(m):
u, v = map(int, input().split())
if ind[v] > ind[u]:
adj[v].append(u)
# print(adj)
s = set()
an = 0
vis = [0] * (n + 1)
c = 1
for j in adj[a[-1]]:
vis[j] += 1
for i in range(n - 2, -1, -1):
if vis[a[i]] == c:
an += 1
else:
for j in adj[a[i]]:
vis[j] += 1
c += 1
# print(vis,c)
print(an)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | output | 1 | 57,203 | 14 | 114,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Submitted Solution:
```
import sys
sys.setrecursionlimit(20000000)
input = sys.stdin.readline
n,m = map(int,input().split())
a = list(map(int,input().split()))
for i in range(n):
a[i]-=1
b = [list(map(int,input().split())) for i in range(m)]
na = a[-1]
g = [set() for i in range(n)]
nani = set()
for i,j in b:
i-=1
j-=1
g[i].add(j)
if j == na:
nani.add(i)
ans = 0
usi = set()
for i in range(n-2,-1,-1):
if a[i] in nani:
if len(g[a[i]]) == len(g[a[i]].union(usi)):
ans += 1
else:
usi.add(a[i])
else:
usi.add(a[i])
print(ans)
``` | instruction | 0 | 57,204 | 14 | 114,408 |
Yes | output | 1 | 57,204 | 14 | 114,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Submitted Solution:
```
import sys
from collections import defaultdict
def move(arr,l,num,i):
for j in range(i,n-1):
if arr[j+1] in l:
arr[j+1],arr[j]=arr[j],arr[j+1]
else:
return
n,m=map(int,sys.stdin.readline().split())
arr=list(map(int,sys.stdin.readline().split()))
graph1=defaultdict(set)
for i in range(m):
u,v=map(int,sys.stdin.readline().split())
graph1[u].add(v)
num=arr[n-1]
for i in range(n-1,-1,-1):
move(arr,graph1[arr[i]],arr[i],i)
for i in range(n):
if arr[i]==num:
break
print(n-1-i)
``` | instruction | 0 | 57,205 | 14 | 114,410 |
Yes | output | 1 | 57,205 | 14 | 114,411 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Submitted Solution:
```
n, m = map(int, input().split())
p = [int(i) for i in input().split()]
gr = [0] * (n + 1)
for i in range(n + 1) :
gr[i] = []
for i in range(m) :
u, v = map(int, input().split())
gr[u].append(v)
can = [0] * (n + 1)
can[p[n-1]] = 1
idx = n-2; good = 1; ans = 0;
while (idx >= 0) :
cur = 0
for i in gr[p[idx]] :
cur += can[i]
if (cur == good) :
ans += 1
else :
good += 1
can[p[idx]] = 1
idx-=1
print(ans)
``` | instruction | 0 | 57,206 | 14 | 114,412 |
Yes | output | 1 | 57,206 | 14 | 114,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Submitted Solution:
```
n, m = map(int, input().split())
p = [int(i) - 1 for i in input().split()]
not_pass = set()
t = [set() for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
t[a - 1].add(b - 1)
for ell in p[-2::-1]:
# print(ell)
k = 0
for el in t[ell]:
if el in not_pass:
k += 1
if k != len(not_pass) or p[-1] not in t[ell]:
not_pass.add(ell)
print(n - 1 - len(not_pass))
# print(not_pass)
``` | instruction | 0 | 57,207 | 14 | 114,414 |
Yes | output | 1 | 57,207 | 14 | 114,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Submitted Solution:
```
n,m=map(int,input().split())
l=[int(x) for x in input().split()]
pairs=[]
for i in range(m):
pairs.append([int(x) for x in input().split()])
pos=n-1
#print(l,pairs)
while 1:
k=pos
if [l[pos-1],l[pos]] in pairs:
pos-=1
k=pos
elif k-2>=0 and [l[k-2],l[k-1]]in pairs:
temp=l[k-1]
l[k-1]=l[k-2]
l[k-2]=temp
k-=1
else:
break
print(n-1-pos)
``` | instruction | 0 | 57,208 | 14 | 114,416 |
No | output | 1 | 57,208 | 14 | 114,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Submitted Solution:
```
from collections import defaultdict
n, m = list(map(int, input().split(' ')))
if m == 451094:
transmisions = defaultdict(lambda: set())
pupils = list(map(int, input().split()))
tanya = pupils[-1]
tanya_ind = n - 1
for k in range(m):
a, b = list(map(int, input().split()))
transmisions[a].add(b)
index = tanya_ind - 1
ans = 0
else:
transmisions = defaultdict(lambda: set())
pupils = list(map(int, input().split()))
tanya = pupils[-1]
tanya_ind = n - 1
for k in range(m):
a, b = list(map(int, input().split()))
transmisions[a].add(b)
index = tanya_ind - 1
ans = 0
while index >= 0:
tmp_index = index
made_move = False
while 0 <= tmp_index < tanya_ind:
if pupils[tmp_index + 1] in transmisions[pupils[tmp_index]]:
pupils[tmp_index], pupils[tmp_index + 1] = pupils[tmp_index + 1], pupils[tmp_index]
if tmp_index + 1 == tanya_ind:
made_move = True
tanya_ind -= 1
ans += 1
break
tmp_index += 1
else:
break
index -= 1
print(ans)
``` | instruction | 0 | 57,209 | 14 | 114,418 |
No | output | 1 | 57,209 | 14 | 114,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Submitted Solution:
```
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
# TAIWAN NUMBER ONE!!!!!!!!!!!!!!!!!!!
from sys import stdin, stdout
import collections
#Q = int(input())
#ans = [0]*Q
#s = input()
#N = len(s)
#arr = [int(x) for x in stdin.readline().split()]
N,M = [int(x) for x in stdin.readline().split()]
P = [int(x) for x in stdin.readline().split()]
idx = {}
for i in range(N):
idx[P[i]] = i
swap = [0]*N
for i in range(M):
x,y = [int(x) for x in stdin.readline().split()]
A = idx[x]
B = idx[y]
if A<B:
swap[A] += 1
k = N-1
#print(swap)
res = 0
for i in range(N-2,-1,-1):
#print(swap[i],k)
if swap[i]>= k-i:
k -= 1
print(N-1-k)
``` | instruction | 0 | 57,210 | 14 | 114,420 |
No | output | 1 | 57,210 | 14 | 114,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the big break Nastya came to the school dining room. There are n pupils in the school, numbered from 1 to n. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs u, v such that if the pupil with number u stands directly in front of the pupil with number v, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^{5}, 0 β€ m β€ 5 β
10^{5}) β the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains n integers p_1, p_2, ..., p_n β the initial arrangement of pupils in the queue, from the queue start to its end (1 β€ p_i β€ n, p is a permutation of integers from 1 to n). In other words, p_i is the number of the pupil who stands on the i-th position in the queue.
The i-th of the following m lines contains two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i), denoting that the pupil with number u_i agrees to change places with the pupil with number v_i if u_i is directly in front of v_i. It is guaranteed that if i β j, than v_i β v_j or u_i β u_j. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number p_n.
Output
Print a single integer β the number of places in queue she can move forward.
Examples
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
Note
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is
* change places for pupils with numbers 1 and 3.
* change places for pupils with numbers 3 and 2.
* change places for pupils with numbers 1 and 2.
The queue looks like [3, 1, 2], then [1, 3, 2], then [1, 2, 3], and finally [2, 1, 3] after these operations.
Submitted Solution:
```
from collections import Counter
n,m=map(int,input().split())
a=[int(x) for x in input().split()]
adj=[set() for i in range(n+1)]
xx=a[-1]
ind=Counter()
for i in range(n):
ind[a[i]]=i
for i in range(m):
u,v=map(int,input().split())
if ind[v]>ind[u]:
adj[v].add(u)
print(adj)
s=set()
an=0
vis=[0]*(n+1)
c=1
for j in adj[a[-1]]:
vis[j]+=1
for i in range(n-2,-1,-1):
if vis[a[i]]==c :
an+=1
else:
for j in adj[a[i]]:
vis[j] += 1
c+=1
# print(vis,c)
print(an)
``` | instruction | 0 | 57,211 | 14 | 114,422 |
No | output | 1 | 57,211 | 14 | 114,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test. | instruction | 0 | 57,428 | 14 | 114,856 |
Tags: dfs and similar, dp
Correct Solution:
```
import math
import sys
from bisect import bisect_right, bisect_left, insort_right
from collections import Counter, defaultdict
from heapq import heappop, heappush
from itertools import accumulate, permutations
from sys import stdout
R = lambda: map(int, input().split())
n, s = R()
seq = [0] + list(R())
incm = [0] * (n + 1)
for x in seq:
if x:
incm[x] = 1
sz = [0] * (n + 1)
st = []
bs = 1
x = s
while seq[x]:
bs += 1
x = seq[x]
for i, x in enumerate(incm):
foundx = False
if not x:
l = i
while i:
foundx = foundx or i == s
sz[l] += 1
i = seq[i]
if seq[l] and not foundx:
st.append(sz[l])
nz = seq.count(0) - 1 - len(st) - 1
pos = [0] * (n + 1)
for p in st:
for i in range(n, -1, -1):
if bs + i + p < n + 1 and pos[bs + i]:
pos[bs + i + p] = 1
pos[bs + p] = 1
rp = [0] * (n + 1)
rp[bs] = 1
if bs + nz + 1 < n + 1:
rp[bs + nz + 1] = -1
for i in range(n + 1):
if pos[i]:
rp[i] += 1
if i + nz + 1 < n + 1:
rp[i + nz + 1] -= 1
for i in range(1, n + 1):
rp[i] += rp[i - 1]
for i in range(1, n + 1):
if rp[i]:
print(i)
``` | output | 1 | 57,428 | 14 | 114,857 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test. | instruction | 0 | 57,429 | 14 | 114,858 |
Tags: dfs and similar, dp
Correct Solution:
```
def put(): return map(int, input().split())
n,x = put()
a = list(put())
parent = list(range(n+1))
for i in range(n):
if a[i]!=0:
parent[a[i]] = i+1
cnt = []
z = 0
#print(parent)
for i in range(n):
if a[i]==0:
j = i+1
c = 1
found = False
if j==x:
z=c
found = True
while j != parent[j]:
j = parent[j]
c+=1
if j==x:
z=c
found = True
if not found:
cnt.append(c)
#print(cnt,z)
n,m = len(cnt)+1, sum(cnt)+1
dp = [[0]*(m+1) for i in range(n+1)]
dp[0][0]=1
s = set()
s.add(0)
for i in range(1,n):
for j in range(m):
if j==0 or dp[i-1][j]==1 or (j-cnt[i-1]>=0 and dp[i-1][j-cnt[i-1]]==1) :
dp[i][j] = 1
s.add(j)
l = []
for i in s:
l.append(i+z)
l.sort()
print(*l)
``` | output | 1 | 57,429 | 14 | 114,859 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test. | instruction | 0 | 57,430 | 14 | 114,860 |
Tags: dfs and similar, dp
Correct Solution:
```
def f(x, p):
q = []
while x:
q.append(x)
x = p[x]
return q
from collections import defaultdict
n, k = map(int, input().split())
t = list(map(int, input().split()))
p = [0] * (n + 1)
for i, j in enumerate(t, 1):
p[j] = i
p = [f(i, p) for i, j in enumerate(t, 1) if j == 0]
s = defaultdict(int)
for i in p:
if k in i: t = {i.index(k) + 1}
else: s[len(i)] += 1
s = [list(range(i, k * i + 1, i)) for i, k in s.items()]
for q in s:
t |= {x + y for x in q for y in t}
print('\n'.join(map(str, sorted(list(t)))))
``` | output | 1 | 57,430 | 14 | 114,861 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test. | instruction | 0 | 57,431 | 14 | 114,862 |
Tags: dfs and similar, dp
Correct Solution:
```
import sys
sys.setrecursionlimit(100000)
def solve():
n, x, = rv()
x -= 1
a, = rl(1)
a = [val - 1 for val in a]
nxt = [True] * n
index = [-1] * n
for i in range(len(a)):
index[i] = get(i, a, nxt)
curindex = index[x] - 1
others = list()
for i in range(n):
if not bad(i, a, x) and nxt[i]:
others.append(index[i])
others.sort()
possible = [False] * (n + 1)
possible[0] = True
for val in others:
pcopy = list(possible)
for i in range(n + 1):
if possible[i]:
both = i + val
if both < n + 1:
pcopy[both] = True
possible = pcopy
res = list()
for i in range(n + 1):
if possible[i]:
comb = i + curindex
if comb < n:
res.append(comb)
print('\n'.join(map(str, [val + 1 for val in res])))
def bad(index, a, x):
if index == x: return True
if a[index] == -1: return False
return bad(a[index], a, x)
def get(index, a, nxt):
if a[index] == -1:
return 1
else:
nxt[a[index]] = False
return get(a[index], a, nxt) + 1
def prt(l): return print(' '.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
``` | output | 1 | 57,431 | 14 | 114,863 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test. | instruction | 0 | 57,432 | 14 | 114,864 |
Tags: dfs and similar, dp
Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import collections
def find(parents, i):
if parents[i] == i:
return i
result = find(parents, parents[i])
parents[i] = result
return result
def union(parents, i, j):
i, j = find(parents, i), find(parents, j)
parents[i] = j
if __name__ == '__main__':
n, x = map(int, input().split())
a = {i + 1: int(ai) for i, ai in enumerate(input().split())}
parents = {i: i for i in a}
x_order = 1
x_current = x
while a[x_current] != 0:
x_order += 1
x_current = a[x_current]
for source, target in a.items():
if target != 0:
union(parents, source, target)
del a
x_representative = find(parents, x)
sizes = collections.Counter()
for i in parents:
i_representative = find(parents, i)
if i_representative != x_representative:
sizes[i_representative] += 1
del parents
adds = collections.Counter()
for size in sizes.values():
adds[size] += 1
del sizes
sieve = {0: 1}
for add, count in adds.items():
sieve_update = {}
for i, j in sieve.items():
if j != 0:
for k in range(1, count + 1):
if i + add * k <= n:
sieve_update[i + add * k] = 1
sieve.update(sieve_update)
del adds
for position, value in sorted(sieve.items()):
if value:
print(position + x_order)
``` | output | 1 | 57,432 | 14 | 114,865 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test. | instruction | 0 | 57,433 | 14 | 114,866 |
Tags: dfs and similar, dp
Correct Solution:
```
import sys
sys.setrecursionlimit(100000)
def solve():
n, x, = rv()
x -= 1
a, = rl(1)
a = [val - 1 for val in a]
nxt = [True] * n
index = [-1] * n
for i in range(len(a)):
index[i] = get(i, a, nxt)
curindex = index[x] - 1
others = list()
for i in range(n):
if not bad(i, a, x) and nxt[i]:
others.append(index[i])
others.sort()
possible = [False] * (n + 1)
possible[0] = True
for val in others:
pcopy = list(possible)
for i in range(n + 1):
if possible[i]:
both = i + val
if both < n + 1:
pcopy[both] = True
possible = pcopy
res = list()
for i in range(n + 1):
if possible[i]:
comb = i + curindex
if comb < n:
res.append(comb)
print('\n'.join(map(str, [val + 1 for val in res])))
def bad(index, a, x):
if index == x: return True
if a[index] == x: return True
if a[index] == -1: return False
return bad(a[index], a, x)
def get(index, a, nxt):
if a[index] == -1:
return 1
else:
nxt[a[index]] = False
return get(a[index], a, nxt) + 1
def prt(l): return print(' '.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
``` | output | 1 | 57,433 | 14 | 114,867 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.
(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.
The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.
Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...
As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.
Input
The first line contains two integers n (1 β€ n β€ 103) and x (1 β€ x β€ n) β the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.
The second line contains n integers a1, a2, ..., an (0 β€ ai β€ n) β the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.
The input limits for scoring 30 points are (subproblem B1):
* It is guaranteed that the number of zero elements ai doesn't exceed 20.
The input limits for scoring 100 points are (subproblems B1+B2):
* The number of zero elements ai is arbitrary.
Output
Print all possible positions of the Smart Beaver in the line in the increasing order.
Examples
Input
6 1
2 0 4 0 6 0
Output
2
4
6
Input
6 2
2 3 0 5 6 0
Output
2
5
Input
4 1
0 0 0 0
Output
1
2
3
4
Input
6 2
0 0 1 0 4 5
Output
1
3
4
6
Note
<image> Picture for the fourth test.
Submitted Solution:
```
import math
import sys
from bisect import bisect_right, bisect_left, insort_right
from collections import Counter, defaultdict
from heapq import heappop, heappush
from itertools import accumulate, permutations
from sys import stdout
R = lambda: map(int, input().split())
n, s = R()
seq = [0] + list(R())
incm = [0] * (n + 1)
for x in seq:
if x:
incm[x] = 1
sz = [0] * (n + 1)
st = []
bs = 1
x = s
while seq[x]:
bs += 1
x = seq[x]
for i, x in enumerate(incm):
foundx = False
if not x:
l = i
while i:
foundx = foundx or i == s
sz[l] += 1
i = seq[i]
if seq[l] and not foundx:
st.append(sz[l])
nz = seq.count(0) - 1 - len(st) - 1
pos = [0] * (n + 1)
for p in st:
for i in range(n + 1):
if bs + i + p < n + 1 and pos[bs + i]:
pos[bs + i + p] = 1
pos[bs + p] = 1
rp = [0] * (n + 1)
rp[bs] = 1
if bs + nz + 1 < n + 1:
rp[bs + nz + 1] = -1
for i in range(n + 1):
if pos[i]:
rp[i] += 1
if i + nz + 1 < n + 1:
rp[i + nz + 1] -= 1
for i in range(1, n + 1):
rp[i] += rp[i - 1]
for i in range(1, n + 1):
if rp[i]:
print(i)
``` | instruction | 0 | 57,434 | 14 | 114,868 |
No | output | 1 | 57,434 | 14 | 114,869 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.