message stringlengths 2 39.6k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 450 109k | cluster float64 2 2 | __index_level_0__ int64 900 217k |
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000 | instruction | 0 | 53,721 | 2 | 107,442 |
"Correct Solution:
```
import fractions, functools;input();print(functools.reduce(fractions.gcd, list(map(int, input().split()))))
``` | output | 1 | 53,721 | 2 | 107,443 |
Provide a correct Python 3 solution for this coding contest problem.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000 | instruction | 0 | 53,722 | 2 | 107,444 |
"Correct Solution:
```
import fractions
N=int(input())
A=[int(i) for i in input().split()]
d=A[0]
for x in A[1:]:
d=fractions.gcd(d,x)
print(d)
``` | output | 1 | 53,722 | 2 | 107,445 |
Provide a correct Python 3 solution for this coding contest problem.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000 | instruction | 0 | 53,723 | 2 | 107,446 |
"Correct Solution:
```
N = int(input())
A = list(map(int, input().split()))
g = A[0]
import math
for i in range(1, N):
g = math.gcd(g, A[i])
print(g)
``` | output | 1 | 53,723 | 2 | 107,447 |
Provide a correct Python 3 solution for this coding contest problem.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000 | instruction | 0 | 53,724 | 2 | 107,448 |
"Correct Solution:
```
import fractions
n=int(input())
a=list(map(int,input().split()))
ans=a[0]
for i in a:
ans=fractions.gcd(ans,i)
print(ans)
``` | output | 1 | 53,724 | 2 | 107,449 |
Provide a correct Python 3 solution for this coding contest problem.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000 | instruction | 0 | 53,725 | 2 | 107,450 |
"Correct Solution:
```
from functools import reduce
from fractions import gcd
input()
X=list(map(int,input().split()))
print(reduce(gcd,X))
``` | output | 1 | 53,725 | 2 | 107,451 |
Provide a correct Python 3 solution for this coding contest problem.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000 | instruction | 0 | 53,726 | 2 | 107,452 |
"Correct Solution:
```
import math
N = int(input())
A = list(map(int, input().split()))
ans = A[0]
for a in A[1:]:
ans = math.gcd(ans, a)
print(ans)
``` | output | 1 | 53,726 | 2 | 107,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000
Submitted Solution:
```
from functools import reduce
from fractions import gcd
N = int(input())
l = list(map(int, input().split()))
print(reduce(gcd,l))
``` | instruction | 0 | 53,727 | 2 | 107,454 |
Yes | output | 1 | 53,727 | 2 | 107,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000
Submitted Solution:
```
from functools import reduce
from fractions import gcd
n = input()
a = list(map(int, input().split()))
print(reduce(gcd, a))
``` | instruction | 0 | 53,728 | 2 | 107,456 |
Yes | output | 1 | 53,728 | 2 | 107,457 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000
Submitted Solution:
```
import fractions
import functools
n = int(input())
A = [int(x) for x in input().split()]
print(functools.reduce(fractions.gcd, A))
``` | instruction | 0 | 53,729 | 2 | 107,458 |
Yes | output | 1 | 53,729 | 2 | 107,459 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000
Submitted Solution:
```
from fractions import gcd
n=int(input())
a=list(map(int,input().split()))
c=a[0]
for i in range(1,n):
c=gcd(c,a[i])
print(c)
``` | instruction | 0 | 53,730 | 2 | 107,460 |
Yes | output | 1 | 53,730 | 2 | 107,461 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000
Submitted Solution:
```
import math
n=int(input())
a=list(map(int,input().split()))
gcd=float('inf')
for i in range(n-1):
gcd=min(gcd,math.gcd(a[i],a[i+1]))
print(gcd)
``` | instruction | 0 | 53,731 | 2 | 107,462 |
No | output | 1 | 53,731 | 2 | 107,463 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000
Submitted Solution:
```
input_int = lambda:int(input())
input_ints = lambda:map(int,input().split())
input_ints_list = lambda:list(input_ints())
input_str = lambda:input()
input_strs = lambda:input().split()
input_lines = lambda n,f:[f() for _ in range(n)]
import functools,fractions
import numpy as np
gcd = lambda a:functools.reduce(fractions.gcd,a) # 最大公約数(リスト)
lcm_base = lambda a,b:(a*b)//fractions.gcd(a,b) # 最小公倍数(2値)
lcm = lambda a:functools.reduce(lcm_base,a,1) # 最小公倍数(リスト)
init_dp = lambda v,n:[v]*(n)
import math
# 四捨五入はround
ceil = lambda a:math.ceil(a) # 切り上げ
floor = lambda a:math.floor(a) # 切り捨て
def solution():
N,M = input_ints()
As = input_ints_list()
w = [0,2,5,5,4,5,6,3,7,6]
dp = init_dp(-1,N+1)
dp[0] = 0
for i in range(N+1):
for v in As:
if i+w[v] < N+1:
dp[i+w[v]] = max(dp[i+w[v]],dp[i]*10+v)
print(dp[N])
if __name__ == '__main__':
solution()
``` | instruction | 0 | 53,732 | 2 | 107,464 |
No | output | 1 | 53,732 | 2 | 107,465 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000
Submitted Solution:
```
import numpy as np
n = int(input())
a = list(map(int, input().split()))
a.sort()
a = np.array(a)
min_index = a.argmin()
for i in range(5):
damaged = a % a[min_index]
nonzero_index = damaged.nonzero()
nonzero = damaged[nonzero_index]
if nonzero.size == 0:
break
target = nonzero.argmin()
min_index = nonzero_index[0][target]
a[min_index] = nonzero[target]
print(a[min_index])
``` | instruction | 0 | 53,733 | 2 | 107,466 |
No | output | 1 | 53,733 | 2 | 107,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible final health of the last monster alive.
Examples
Input
4
2 10 8 40
Output
2
Input
4
5 13 8 1000000000
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1000000000
Submitted Solution:
```
# coding: utf-8
# Your code here!
import heapq
N = int(input())
a = list(map(int, input().split()))
heapq.heapify(a)
tmp = 0
tmp2 = 0
for i in range(N):
tmp = heapq.heappop(a)
if tmp == 1:
print(tmp)
exit()
a = list(map(lambda x: x % tmp, a))
if sum(a) == 0:
print(tmp)
exit()
else:
a = [j for j in a if j != 0]
heapq.heappush(a, tmp)
``` | instruction | 0 | 53,734 | 2 | 107,468 |
No | output | 1 | 53,734 | 2 | 107,469 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Red Kingdom is attacked by the White King and the Black King!
The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.
Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.
Each attack must target a castle with at least one alive defender in it. There are three types of attacks:
* a mixed attack decreases the number of defenders in the targeted castle by x (or sets it to 0 if there are already less than x defenders);
* an infantry attack decreases the number of defenders in the targeted castle by y (or sets it to 0 if there are already less than y defenders);
* a cavalry attack decreases the number of defenders in the targeted castle by z (or sets it to 0 if there are already less than z defenders).
The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.
The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
Then, the test cases follow. Each test case is represented by two lines.
The first line contains four integers n, x, y and z (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y, z ≤ 5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}).
It is guaranteed that the sum of values of n over all test cases in the input does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer to it: the number of possible options for the first attack of the White King (or 0, if the Black King can launch the last attack no matter how the White King acts).
Examples
Input
3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
Output
2
3
0
Input
10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
Output
0
2
1
2
5
12
5
0
0
2 | instruction | 0 | 54,070 | 2 | 108,140 |
Tags: games, two pointers
Correct Solution:
```
import sys
readline = sys.stdin.buffer.readline
T = int(readline())
Ans = [None]*T
for qu in range(T):
N, x, y, z = map(int, readline().split())
A = list(map(int, readline().split()))
ts = 200
dp = [[0]*3 for _ in range(ts)]
table = [[[0]*4 for _ in range(3)] for _ in range(ts+8)]
for hp in range(ts):
if 0 < hp <= x:
table[hp][0][0] = 1
table[hp][1][0] = 1
table[hp][2][0] = 1
if 0 < hp <= y:
table[hp][0][0] = 1
table[hp][2][0] = 1
if 0 < hp <= z:
table[hp][0][0] = 1
table[hp][1][0] = 1
for ty in range(3):
dp[hp][ty] = table[hp][ty].index(0)
val0 = dp[hp][0]
val1 = dp[hp][1]
val2 = dp[hp][2]
table[hp+x][0][val0] = 1
table[hp+x][1][val0] = 1
table[hp+x][2][val0] = 1
table[hp+y][0][val1] = 1
table[hp+y][2][val1] = 1
table[hp+z][0][val2] = 1
table[hp+z][1][val2] = 1
cl = None
for loop in range(10, 61):
for i in range(loop):
if dp[ts-1-i] != dp[ts-1-i-loop]:
break
else:
cl = loop
break
continue
A1 = [None]*N
for i in range(N):
a = A[i]
if a < ts:
A1[i] = a
else:
k = 1 + (a-ts)//cl
A1[i] = a - k*cl
xx = 0
for a in A1:
xx ^= dp[a][0]
res = 0
for a in A1:
da = dp[a][0]
if dp[max(0, a-x)][0]^da == xx:
res += 1
if dp[max(0, a-y)][1]^da == xx:
res += 1
if dp[max(0, a-z)][2]^da == xx:
res += 1
Ans[qu] = res
print('\n'.join(map(str, Ans)))
``` | output | 1 | 54,070 | 2 | 108,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Red Kingdom is attacked by the White King and the Black King!
The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.
Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.
Each attack must target a castle with at least one alive defender in it. There are three types of attacks:
* a mixed attack decreases the number of defenders in the targeted castle by x (or sets it to 0 if there are already less than x defenders);
* an infantry attack decreases the number of defenders in the targeted castle by y (or sets it to 0 if there are already less than y defenders);
* a cavalry attack decreases the number of defenders in the targeted castle by z (or sets it to 0 if there are already less than z defenders).
The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.
The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
Then, the test cases follow. Each test case is represented by two lines.
The first line contains four integers n, x, y and z (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y, z ≤ 5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}).
It is guaranteed that the sum of values of n over all test cases in the input does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer to it: the number of possible options for the first attack of the White King (or 0, if the Black King can launch the last attack no matter how the White King acts).
Examples
Input
3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
Output
2
3
0
Input
10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
Output
0
2
1
2
5
12
5
0
0
2 | instruction | 0 | 54,071 | 2 | 108,142 |
Tags: games, two pointers
Correct Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
if n==1:
return 0
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):#排他的論理和の階乗
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[digit[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[digit[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=0):
self.BIT = [0]*(n+1)
self.num = n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class Matrix():
mod=10**9+7
def set_mod(m):
Matrix.mod=m
def __init__(self,L):
self.row=len(L)
self.column=len(L[0])
self._matrix=L
for i in range(self.row):
for j in range(self.column):
self._matridigit[i][j]%=Matrix.mod
def __getitem__(self,item):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
return self._matridigit[i][j]
def __setitem__(self,item,val):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
self._matridigit[i][j]=val
def __add__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matridigit[i][j]+other._matridigit[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __sub__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matridigit[i][j]-other._matridigit[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __mul__(self,other):
if type(other)!=int:
if self.column!=other.row:
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(other.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(other.column):
temp=0
for k in range(self.column):
temp+=self._matridigit[i][k]*other._matrix[k][j]
res[i][j]=temp%Matrix.mod
return Matrix(res)
else:
n=other
res=[[(n*self._matridigit[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)]
return Matrix(res)
def __pow__(self,m):
if self.column!=self.row:
raise MatrixPowError("the size of row must be the same as that of column")
n=self.row
res=Matrix([[int(i==j) for i in range(n)] for j in range(n)])
while m:
if m%2==1:
res=res*self
self=self*self
m//=2
return res
def __str__(self):
res=[]
for i in range(self.row):
for j in range(self.column):
res.append(str(self._matridigit[i][j]))
res.append(" ")
res.append("\n")
res=res[:len(res)-1]
return "".join(res)
from collections import deque
class Dinic:
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap):
forward = [to, cap, None]
forward[2] = backward = [fr, 0, forward]
self.G[fr].append(forward)
self.G[to].append(backward)
def add_multi_edge(self, v1, v2, cap1, cap2):
edge1 = [v2, cap1, None]
edge1[2] = edge2 = [v1, cap2, edge1]
self.G[v1].append(edge1)
self.G[v2].append(edge2)
def bfs(self, s, t):
self.level = level = [None]*self.N
deq = deque([s])
level[s] = 0
G = self.G
while deq:
v = deq.popleft()
lv = level[v] + 1
for w, cap, _ in G[v]:
if cap and level[w] is None:
level[w] = lv
deq.append(w)
return level[t] is not None
def dfs(self, v, t, f):
if v == t:
return f
level = self.level
for e in self.it[v]:
w, cap, rev = e
if cap and level[v] < level[w]:
d = self.dfs(w, t, min(f, cap))
if d:
e[1] -= d
rev[1] += d
return d
return 0
def flow(self, s, t):
flow = 0
INF = 10**9 + 7
G = self.G
while self.bfs(s, t):
*self.it, = map(iter, self.G)
f = INF
while f:
f = self.dfs(s, t, INF)
flow += f
return flow
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.buffer.readline()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
def mex(*args):
tmp = [0 for j in range(4)]
for a in args:
tmp[a] += 1
for i in range(4):
if not tmp[i]:
return i
ans = []
for _ in range(int(input())):
N,x,y,z = mi()
A = li()
X = [0 for i in range(50+1)] + [0 for j in range(10)]
Y = [0 for i in range(50+1)] + [0 for j in range(10)]
Z = [0 for i in range(50+1)] + [0 for j in range(10)]
memo = [[] for i in range(64)]
start,D = -1,-1
for i in range(1,50+1):
a = X[i-x]
b = Y[i-y]
c = Z[i-z]
X[i] = mex(a,b,c)
Y[i] = mex(a,c)
Z[i] = mex(a,b)
cond = 16 * X[i] + 4 * Y[i] + Z[i]
for idx in memo[cond]:
L = i - idx
if idx<L or L<max(x,y,z):
continue
check_1 = [(X[j],Y[j],Z[j]) for j in range(idx-L+1,idx+1)]
check_2 = [(X[j],Y[j],Z[j]) for j in range(idx+1,i+1)]
if check_1==check_2:
D = L
start = idx-L+1
break
memo[cond].append(i)
def grundy(t,n):
if n<=0:
return 0
if t==1:
if n<start:
return X[n]
else:
n %= D
while n<start:
n += D
return X[n]
elif t==2:
if n<start:
return Y[n]
else:
n %= D
while n<start:
n += D
return Y[n]
else:
if n<start:
return Z[n]
else:
n %= D
while n<start:
n += D
return Z[n]
G = [grundy(1,a) for a in A]
LG = [G[i] for i in range(N)] + [0]
RG = [G[i] for i in range(N)] + [0]
for i in range(1,N):
LG[i] ^= LG[i-1]
for i in range(N-2,-1,-1):
RG[i] ^= RG[i+1]
#print(G)
res = 0
for i in range(N):
tmp_g = LG[i-1] ^ RG[i+1]
if grundy(1,A[i]-x)==tmp_g:
res += 1
if grundy(2,A[i]-y)==tmp_g:
res += 1
if grundy(3,A[i]-z)==tmp_g:
res += 1
ans.append(res)
print(*ans,sep="\n")
``` | output | 1 | 54,071 | 2 | 108,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Red Kingdom is attacked by the White King and the Black King!
The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.
Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.
Each attack must target a castle with at least one alive defender in it. There are three types of attacks:
* a mixed attack decreases the number of defenders in the targeted castle by x (or sets it to 0 if there are already less than x defenders);
* an infantry attack decreases the number of defenders in the targeted castle by y (or sets it to 0 if there are already less than y defenders);
* a cavalry attack decreases the number of defenders in the targeted castle by z (or sets it to 0 if there are already less than z defenders).
The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.
The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
Then, the test cases follow. Each test case is represented by two lines.
The first line contains four integers n, x, y and z (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y, z ≤ 5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}).
It is guaranteed that the sum of values of n over all test cases in the input does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer to it: the number of possible options for the first attack of the White King (or 0, if the Black King can launch the last attack no matter how the White King acts).
Examples
Input
3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
Output
2
3
0
Input
10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
Output
0
2
1
2
5
12
5
0
0
2 | instruction | 0 | 54,072 | 2 | 108,144 |
Tags: games, two pointers
Correct Solution:
```
T = int(input())
def findPeriod(DP):
for offset in range(0, len(DP)):
for period in range(1, 500):
is_period = True
for j in range(offset, len(DP) - period):
if (DP[j][0] == DP[j + period][0] and DP[j][1] == DP[j + period][1] and DP[j][2] == DP[j + period][2]):
is_period = True
else:
is_period = False
break
if is_period and period < len(DP) - offset + 1:
return period, offset
return 0, 0
WHERE = ''
import random
try:
for _ in range(T):
memo = {}
n, x, y, z = list(map(int, input().split()))
PILES = list(map(int, input().split()))
# PILES = [random.randint(0, 1500) for _ in range(500)]
DP = [[0 for _ in range(3)] for _ in range(1000)]
# Compute DP
for i in range(1,1000):
for j in range(3):
children = []
for ind, attack in enumerate([x, y, z]):
if ind != j or ind == 0:
children.append((max(0, i - attack), ind))
if len(children) == 0:
DP[i][j] = 0
else:
s = set()
for child in children:
s.add(DP[child[0]][child[1]])
grundy = 0
while grundy in s:
grundy += 1
DP[i][j] = grundy
WHERE = 'a'
# Compute Period
period, offset = findPeriod(DP)
#print("Period " + str(period))
# print(offset)
grundy = 0
convert = lambda pile: (pile - offset) % period + offset if pile - offset >= 0 else pile
# PILES_MOD = [str(convert(pile)) for pile in PILES]
#print(len([x for x in PILES if x == 16]))
#L = [str(x) for x in PILES if x != 16]
#print(len([x for x in L if x == '15']))
#L = [str(x) for x in L if x != '15']
#print(len([x for x in L if x == '14']))
#L = [str(x) for x in L if x != '14']
#print(len([x for x in L if x == '13']))
#L = [str(x) for x in L if x != '13']
#print(" ".join(L))
# print(PILES)
# print(PILES_MOD)
# print(" ".join(PILES_MOD))
for pile in PILES:
grundy ^= DP[convert(pile)][0]
if grundy == 0:
print(0)
else:
count = 0
WHERE = 'b'
for pile in PILES:
grundy ^= DP[convert(pile)][0]
# You must apply the modulo %period after having changed your state
# Otherwise too easy to get error with the max function
# Example : currentState = 10 ,attack = 5 period=10
# If you apply modulo before you get currentState = 0
# If you apply modulo after you get currentState = 5
if (grundy ^ DP[convert(max(0, (pile - x)))][0] == 0): count += 1
if (grundy ^ DP[convert(max(0, (pile - y)))][1] == 0): count += 1
if (grundy ^ DP[convert(max(0, (pile - z)))][2] == 0): count += 1
grundy ^= DP[convert(pile)][0]
print(count)
except Exception as e:
print(e)
print(WHERE)
``` | output | 1 | 54,072 | 2 | 108,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Red Kingdom is attacked by the White King and the Black King!
The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.
Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.
Each attack must target a castle with at least one alive defender in it. There are three types of attacks:
* a mixed attack decreases the number of defenders in the targeted castle by x (or sets it to 0 if there are already less than x defenders);
* an infantry attack decreases the number of defenders in the targeted castle by y (or sets it to 0 if there are already less than y defenders);
* a cavalry attack decreases the number of defenders in the targeted castle by z (or sets it to 0 if there are already less than z defenders).
The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.
The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
Then, the test cases follow. Each test case is represented by two lines.
The first line contains four integers n, x, y and z (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y, z ≤ 5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}).
It is guaranteed that the sum of values of n over all test cases in the input does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer to it: the number of possible options for the first attack of the White King (or 0, if the Black King can launch the last attack no matter how the White King acts).
Examples
Input
3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
Output
2
3
0
Input
10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
Output
0
2
1
2
5
12
5
0
0
2
Submitted Solution:
```
T = int(input())
def findPeriod(DP):
for period in range(1, len(DP)):
is_period = True
for j in range(1, len(DP) - period):
if (DP[j][0] == DP[j + period][0] and DP[j][1] == DP[j + period][1] and DP[j][2] == DP[j + period][2]):
is_period = True
else:
is_period = False
break
if is_period:
return period
WHERE = ''
try:
for _ in range(T):
memo = {}
n, x, y, z = list(map(int, input().split()))
PILES = list(map(int, input().split()))
DP = [[0 for _ in range(3)] for _ in range(int(30000/T))]
# Compute DP
for i in range(1, int(30000/T)):
for j in range(3):
children = []
for ind, attack in enumerate([x, y, z]):
if ind != j or ind == 0:
children.append((max(0, i - attack), ind))
if len(children) == 0:
DP[i][j] = 0
else:
s = set()
for child in children:
s.add(DP[child[0]][child[1]])
grundy = 0
while grundy in s:
grundy += 1
DP[i][j] = grundy
WHERE = 'a'
# Compute Period
period = findPeriod(DP)
#print(period)
grundy = 0
WHERE = 'c'
for pile in PILES:
grundy ^= DP[pile%period][0]
if grundy == 0:
print(0)
else:
count = 0
WHERE = 'b'
for pile in PILES:
grundy ^= DP[pile%period][0]
#You must apply the modulo %period after having changed your state
#Otherwise too easy to get error with the max function
#Example : currentState = 10 ,attack = 5 period=10
#If you apply modulo before you get currentState = 0
#If you apply modulo after you get currentState = 5
if (grundy ^ DP[max(0, (pile - x))%period][0] == 0): count += 1
if (grundy ^ DP[max(0, (pile - y))%period][1] == 0): count += 1
if (grundy ^ DP[max(0, (pile - z))%period][2] == 0): count += 1
grundy ^= DP[pile%period][0]
print(count)
except Exception as e:
print(e)
print(period)
print(WHERE)
``` | instruction | 0 | 54,073 | 2 | 108,146 |
No | output | 1 | 54,073 | 2 | 108,147 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Red Kingdom is attacked by the White King and the Black King!
The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.
Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.
Each attack must target a castle with at least one alive defender in it. There are three types of attacks:
* a mixed attack decreases the number of defenders in the targeted castle by x (or sets it to 0 if there are already less than x defenders);
* an infantry attack decreases the number of defenders in the targeted castle by y (or sets it to 0 if there are already less than y defenders);
* a cavalry attack decreases the number of defenders in the targeted castle by z (or sets it to 0 if there are already less than z defenders).
The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.
The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
Then, the test cases follow. Each test case is represented by two lines.
The first line contains four integers n, x, y and z (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y, z ≤ 5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}).
It is guaranteed that the sum of values of n over all test cases in the input does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer to it: the number of possible options for the first attack of the White King (or 0, if the Black King can launch the last attack no matter how the White King acts).
Examples
Input
3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
Output
2
3
0
Input
10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
Output
0
2
1
2
5
12
5
0
0
2
Submitted Solution:
```
T = int(input())
def findPeriod(DP):
for offset in range(0, len(DP)):
for period in range(1, 500):
is_period = True
for j in range(offset, len(DP) - period):
if (DP[j][0] == DP[j + period][0] and DP[j][1] == DP[j + period][1] and DP[j][2] == DP[j + period][2]):
is_period = True
else:
is_period = False
break
if is_period and period < len(DP) - offset + 1:
return period, offset
return 0, 0
WHERE = ''
import random
try:
for _ in range(T):
memo = {}
n, x, y, z = list(map(int, input().split()))
PILES = list(map(int, input().split()))
# PILES = [random.randint(0, 1500) for _ in range(500)]
DP = [[0 for _ in range(3)] for _ in range(int(1000 / T))]
# Compute DP
for i in range(1, int(1000 / T)):
for j in range(3):
children = []
for ind, attack in enumerate([x, y, z]):
if ind != j or ind == 0:
children.append((max(0, i - attack), ind))
if len(children) == 0:
DP[i][j] = 0
else:
s = set()
for child in children:
s.add(DP[child[0]][child[1]])
grundy = 0
while grundy in s:
grundy += 1
DP[i][j] = grundy
WHERE = 'a'
# Compute Period
period, offset = findPeriod(DP)
#print("Period " + str(period))
# print(offset)
grundy = 0
convert = lambda pile: (pile - offset) % period + offset if pile - offset >= 0 else pile
# PILES_MOD = [str(convert(pile)) for pile in PILES]
#print(len([x for x in PILES if x == 16]))
#L = [str(x) for x in PILES if x != 16]
#print(len([x for x in L if x == '15']))
#L = [str(x) for x in L if x != '15']
#print(len([x for x in L if x == '14']))
#L = [str(x) for x in L if x != '14']
#print(len([x for x in L if x == '13']))
#L = [str(x) for x in L if x != '13']
#print(" ".join(L))
# print(PILES)
# print(PILES_MOD)
# print(" ".join(PILES_MOD))
for pile in PILES:
grundy ^= DP[convert(pile)][0]
if grundy == 0:
print(0)
else:
count = 0
WHERE = 'b'
for pile in PILES:
grundy ^= DP[convert(pile)][0]
# You must apply the modulo %period after having changed your state
# Otherwise too easy to get error with the max function
# Example : currentState = 10 ,attack = 5 period=10
# If you apply modulo before you get currentState = 0
# If you apply modulo after you get currentState = 5
if (grundy ^ DP[convert(max(0, (pile - x)))][0] == 0): count += 1
if (grundy ^ DP[convert(max(0, (pile - y)))][1] == 0): count += 1
if (grundy ^ DP[convert(max(0, (pile - z)))][2] == 0): count += 1
grundy ^= DP[convert(pile)][0]
print(count)
except Exception as e:
print(e)
print(WHERE)
``` | instruction | 0 | 54,074 | 2 | 108,148 |
No | output | 1 | 54,074 | 2 | 108,149 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Red Kingdom is attacked by the White King and the Black King!
The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.
Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.
Each attack must target a castle with at least one alive defender in it. There are three types of attacks:
* a mixed attack decreases the number of defenders in the targeted castle by x (or sets it to 0 if there are already less than x defenders);
* an infantry attack decreases the number of defenders in the targeted castle by y (or sets it to 0 if there are already less than y defenders);
* a cavalry attack decreases the number of defenders in the targeted castle by z (or sets it to 0 if there are already less than z defenders).
The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.
The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
Then, the test cases follow. Each test case is represented by two lines.
The first line contains four integers n, x, y and z (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y, z ≤ 5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}).
It is guaranteed that the sum of values of n over all test cases in the input does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer to it: the number of possible options for the first attack of the White King (or 0, if the Black King can launch the last attack no matter how the White King acts).
Examples
Input
3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
Output
2
3
0
Input
10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
Output
0
2
1
2
5
12
5
0
0
2
Submitted Solution:
```
import sys
input = sys.stdin.readline
G0=[[[[0]*200 for i in range(6)] for j in range(6)] for k in range(6)]
G1=[[[[0]*200 for i in range(6)] for j in range(6)] for k in range(6)]
G2=[[[[0]*200 for i in range(6)] for j in range(6)] for k in range(6)]
for x in range(1,6):
for y in range(1,6):
for z in range(1,6):
for i in range(1,200):
s=G0[x][y][z][max(0,i-x)]
t=G1[x][y][z][max(0,i-y)]
u=G2[x][y][z][max(0,i-z)]
for j in range(5):
if j==s or j==t or j==u:
continue
else:
G0[x][y][z][i]=j
break
for j in range(5):
if j==s or j==u:
continue
else:
G1[x][y][z][i]=j
break
for j in range(5):
if j==s or j==t:
continue
else:
G2[x][y][z][i]=j
break
t=int(input())
for tests in range(t):
n,x,y,z=map(int,input().split())
B=list(map(int,input().split()))
A=[]
for a in B:
if a<=180:
A.append(a)
else:
A.append(a%60+120)
XOR=0
for a in A:
XOR^=G0[x][y][z][a]
ANS=0
for a in A:
k=XOR^G0[x][y][z][a]
if G0[x][y][z][max(0,a-x)]==k:
ANS+=1
if G1[x][y][z][max(0,a-y)]==k:
ANS+=1
if G2[x][y][z][max(0,a-z)]==k:
ANS+=1
print(ANS)
``` | instruction | 0 | 54,075 | 2 | 108,150 |
No | output | 1 | 54,075 | 2 | 108,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Red Kingdom is attacked by the White King and the Black King!
The Kingdom is guarded by n castles, the i-th castle is defended by a_i soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders.
Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.
Each attack must target a castle with at least one alive defender in it. There are three types of attacks:
* a mixed attack decreases the number of defenders in the targeted castle by x (or sets it to 0 if there are already less than x defenders);
* an infantry attack decreases the number of defenders in the targeted castle by y (or sets it to 0 if there are already less than y defenders);
* a cavalry attack decreases the number of defenders in the targeted castle by z (or sets it to 0 if there are already less than z defenders).
The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.
The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.
Input
The first line contains one integer t (1 ≤ t ≤ 1000) — the number of test cases.
Then, the test cases follow. Each test case is represented by two lines.
The first line contains four integers n, x, y and z (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y, z ≤ 5).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{18}).
It is guaranteed that the sum of values of n over all test cases in the input does not exceed 3 ⋅ 10^5.
Output
For each test case, print the answer to it: the number of possible options for the first attack of the White King (or 0, if the Black King can launch the last attack no matter how the White King acts).
Examples
Input
3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
Output
2
3
0
Input
10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
Output
0
2
1
2
5
12
5
0
0
2
Submitted Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
if n==1:
return 0
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):#排他的論理和の階乗
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[digit[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[digit[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=0):
self.BIT = [0]*(n+1)
self.num = n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class Matrix():
mod=10**9+7
def set_mod(m):
Matrix.mod=m
def __init__(self,L):
self.row=len(L)
self.column=len(L[0])
self._matrix=L
for i in range(self.row):
for j in range(self.column):
self._matridigit[i][j]%=Matrix.mod
def __getitem__(self,item):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
return self._matridigit[i][j]
def __setitem__(self,item,val):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
self._matridigit[i][j]=val
def __add__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matridigit[i][j]+other._matridigit[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __sub__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matridigit[i][j]-other._matridigit[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __mul__(self,other):
if type(other)!=int:
if self.column!=other.row:
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(other.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(other.column):
temp=0
for k in range(self.column):
temp+=self._matridigit[i][k]*other._matrix[k][j]
res[i][j]=temp%Matrix.mod
return Matrix(res)
else:
n=other
res=[[(n*self._matridigit[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)]
return Matrix(res)
def __pow__(self,m):
if self.column!=self.row:
raise MatrixPowError("the size of row must be the same as that of column")
n=self.row
res=Matrix([[int(i==j) for i in range(n)] for j in range(n)])
while m:
if m%2==1:
res=res*self
self=self*self
m//=2
return res
def __str__(self):
res=[]
for i in range(self.row):
for j in range(self.column):
res.append(str(self._matridigit[i][j]))
res.append(" ")
res.append("\n")
res=res[:len(res)-1]
return "".join(res)
from collections import deque
class Dinic:
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap):
forward = [to, cap, None]
forward[2] = backward = [fr, 0, forward]
self.G[fr].append(forward)
self.G[to].append(backward)
def add_multi_edge(self, v1, v2, cap1, cap2):
edge1 = [v2, cap1, None]
edge1[2] = edge2 = [v1, cap2, edge1]
self.G[v1].append(edge1)
self.G[v2].append(edge2)
def bfs(self, s, t):
self.level = level = [None]*self.N
deq = deque([s])
level[s] = 0
G = self.G
while deq:
v = deq.popleft()
lv = level[v] + 1
for w, cap, _ in G[v]:
if cap and level[w] is None:
level[w] = lv
deq.append(w)
return level[t] is not None
def dfs(self, v, t, f):
if v == t:
return f
level = self.level
for e in self.it[v]:
w, cap, rev = e
if cap and level[v] < level[w]:
d = self.dfs(w, t, min(f, cap))
if d:
e[1] -= d
rev[1] += d
return d
return 0
def flow(self, s, t):
flow = 0
INF = 10**9 + 7
G = self.G
while self.bfs(s, t):
*self.it, = map(iter, self.G)
f = INF
while f:
f = self.dfs(s, t, INF)
flow += f
return flow
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.buffer.readline()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
def mex(*args):
tmp = [0 for j in range(4)]
for a in args:
tmp[a] += 1
for i in range(4):
if not tmp[i]:
return i
ans = []
for _ in range(int(input())):
N,x,y,z = mi()
A = li()
X = [0 for i in range(50+1)] + [0 for j in range(10)]
Y = [0 for i in range(50+1)] + [0 for j in range(10)]
Z = [0 for i in range(50+1)] + [0 for j in range(10)]
memo = [[] for i in range(64)]
start,D = -1,-1
for i in range(1,50+1):
a = X[i-x]
b = Y[i-y]
c = Z[i-z]
X[i] = mex(a,b,c)
Y[i] = mex(a,c)
Z[i] = mex(a,b)
cond = 16 * X[i] + 4 * Y[i] + Z[i]
for idx in memo[cond]:
L = i - idx
if idx<L or L<max(x,y,z):
continue
check_1 = [(X[j],Y[j],Z[j]) for j in range(idx-L+1,idx+1)]
check_2 = [(X[j],Y[j],Z[j]) for j in range(idx+1,i+1)]
if check_1==check_2:
D = L
start = idx-L
break
memo[cond].append(i)
def grundy(t,n):
if n<=0:
return 0
if t==1:
if n<start:
return X[n]
else:
n %= D
while n<start:
n += D
return X[n]
elif t==2:
if n<start:
return Y[n]
else:
n %= D
while n<start:
n += D
return Y[n]
else:
if n<start:
return Z[n]
else:
n %= D
while n<start:
n += D
return Z[n]
G = [grundy(1,a) for a in A]
LG = [G[i] for i in range(N)] + [0]
RG = [G[i] for i in range(N)] + [0]
for i in range(1,N):
LG[i] ^= LG[i-1]
for i in range(N-2,-1,-1):
RG[i] ^= RG[i+1]
#print(G)
res = 0
for i in range(N):
tmp_g = LG[i-1] ^ RG[i+1]
if grundy(1,A[i]-x)==tmp_g:
res += 1
if grundy(2,A[i]-y)==tmp_g:
res += 1
if grundy(3,A[i]-z)==tmp_g:
res += 1
ans.append(res)
print(*ans,sep="\n")
``` | instruction | 0 | 54,076 | 2 | 108,152 |
No | output | 1 | 54,076 | 2 | 108,153 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 54,296 | 2 | 108,592 |
Tags: data structures, dsu
Correct Solution:
```
import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
def build_segment(a, tree, i_tree, right, left):
if right == left:
tree[i_tree] = a[right]
else:
mid = (right + left) // 2
build_segment(a, tree, 2 * i_tree, right, mid)
build_segment(a, tree, 2 * i_tree + 1, mid + 1, left)
return
def querry(a, tree, i_tree, left, right, ql, qr, x):
if right == left and a[right] == 0:
if not (ql <= right <= qr) or x == right + 1:
return tree[i_tree]
else:
a[right] = x
tree[i_tree] = 1
return 1
if qr < left or ql > right:
return tree[i_tree]
if ql <= left and right <= qr:
if tree[i_tree]:
return 1
else:
mid = (right + left) // 2
querry(a, tree, 2 * i_tree, left, mid, ql, qr, x)
querry(a, tree, 2 * i_tree + 1, mid + 1, right, ql, qr, x)
tree[i_tree] = min(tree[2 * i_tree], tree[i_tree * 2 + 1])
return tree[i_tree]
else:
mid = (right + left) // 2
querry(a, tree, 2 * i_tree, left, mid, ql, qr, x)
querry(a, tree, 2 * i_tree + 1, mid + 1, right, ql, qr, x)
tree[i_tree] = min(tree[2 * i_tree], tree[i_tree * 2 + 1])
return tree[i_tree]
n, m = map(int, input().split())
a = [0] * n
t = [0] * (4 * n + 1)
ck=[]
for _ in range(m):
l, r, x = map(int, input().split())
l -= 1
r -= 1
if ck:
l1,r1,x1=ck[-1]
if x1==x:
l1=min(l1,l)
r1=max(r1,r)
ck[-1]=[l1,r1,x]
else:
ck.append([l,r,x])
else:
ck.append([l,r,x])
#print(ck)
for i in ck:
l,r,x=i
querry(a, t, 1, 0, n - 1, l, r, x)
print(*a)
``` | output | 1 | 54,296 | 2 | 108,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 54,297 | 2 | 108,594 |
Tags: data structures, dsu
Correct Solution:
```
def main():
n, m = map(int, input().split())
alive, winner = list(range(1, n + 3)), [0] * (n + 2)
for _ in range(m):
l, r, x = map(int, input().split())
while l < x:
if winner[l]:
alive[l], l = x, alive[l]
else:
alive[l] = winner[l] = x
l += 1
l += 1
r += 1
while winner[r]:
r = alive[r]
while l < r:
if winner[l]:
alive[l], l = r, alive[l]
else:
alive[l], winner[l] = r, x
l += 1
print(' '.join(map(str, winner[1: -1])))
if __name__ == '__main__':
main()
``` | output | 1 | 54,297 | 2 | 108,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 54,298 | 2 | 108,596 |
Tags: data structures, dsu
Correct Solution:
```
import sys
from collections import defaultdict
class llnode:
p = None
n = None
val = None
class llist:
root = None
def __init__(self, totalNodes):
self.ans = [0 for _ in range(totalNodes + 1)]
self.makell(totalNodes)
def makell(self, total):
root = llnode()
curVal = 1
root.val = curVal
self.root = root
curNode = self.root
while curVal < total:
curVal += 1
nextNode = llnode()
nextNode.val = curVal
nextNode.p = curNode
curNode.n = nextNode
curNode = nextNode
def printll(self):
curNode = self.root
while curNode:
print(curNode.val)
curNode = curNode.n
def remove(self, node, vanqVal):
self.ans[node.val] = vanqVal
if node == self.root:
self.root = node.n
self.root.p = None
node.p = None
del node
else:
node.p.n = node.n
if node.n:
node.n.p = node.p
del node
def removeNodes(self, startVal, endVal, exception):
curNode = self.root
while curNode and curNode.val < startVal:
curNode = curNode.n
while curNode and curNode.val <= endVal:
if curNode.val != exception:
remNode = curNode
curNode = curNode.n
self.remove(remNode, exception)
else:
curNode = curNode.n
def getAns(self):
return self.ans
def results(knights, tList):
ans = [0 for _ in range(knights + 1)] # remember not to print 0
for l, r, winner in tList:
for i in range(l, r + 1):
if i != winner and ans[i] == 0:
ans[i] = winner
return ans[1:]
def results2(knights, tList):
k = llist(knights)
for l, r, winner in tList:
k.removeNodes(l, r, winner)
return k.getAns()[1:]
def results3(knights, tList):
jumpList = [[0, 0] for _ in range(knights + 1)] # prev / next
ans = [0 for _ in range(knights + 1)]
for l, r, winner in tList:
left = l
right = r
while left < winner:
if ans[left] == 0:
ans[left] = winner
jumpList[left] = [l - 1, winner] # 0 points left, 1 points right
left += 1
else: # ans already filled, update the jumplist with bigger vals if possible
curLeft = left
left = jumpList[left][1] # move right
jumpList[curLeft][0] = min(l - 1, jumpList[curLeft][0]) # update left
jumpList[curLeft][1] = max(winner, jumpList[curLeft][1]) # update right
while right > winner:
if ans[right] == 0:
ans[right] = winner
jumpList[right] = [winner, r + 1]
right -= 1
else:
curRight = right
right = jumpList[right][0] # move left
jumpList[curRight][0] = min(
winner, jumpList[curRight][0]
) # update left
jumpList[curRight][1] = max(
r + 1, jumpList[curRight][1]
) # update right
return ans[1:]
def readinput():
n, m = map(int, sys.stdin.readline().rstrip().split(" "))
tList = []
for _ in range(m):
l, r, win = map(int, sys.stdin.readline().rstrip().split(" "))
tList.append((l, r, win))
for i in results3(n, tList):
print(i, end=" ")
readinput()
``` | output | 1 | 54,298 | 2 | 108,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 54,299 | 2 | 108,598 |
Tags: data structures, dsu
Correct Solution:
```
n, m = map(int, input().split())
ans = [0] * n
a = [i for i in range(2, n + 5)]
for _ in range(m) :
l, r, w = map(int, input().split())
b = l
while (b <= r):
if ans[b - 1] == 0 and b != w:
ans[b - 1] = w
nxt = a[b - 1]
if b < w:
a[b - 1] = w
else:
a[b - 1] = r + 1
b = nxt
print(*ans)
``` | output | 1 | 54,299 | 2 | 108,599 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 54,300 | 2 | 108,600 |
Tags: data structures, dsu
Correct Solution:
```
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
n,m=map(int,input().split())
ans=[0 for i in range(n)]
nextl=[i+1 for i in range(n+2)]
for j in range(m):
l,r,x=map(int,input().split())
i=l
while i<=r:
if ans[i-1]==0 and i!=x:
ans[i-1]=x
a=nextl[i]
if i<x:
nextl[i]=x
else:
nextl[i]=r+1
i=a
print(*ans)
``` | output | 1 | 54,300 | 2 | 108,601 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 54,301 | 2 | 108,602 |
Tags: data structures, dsu
Correct Solution:
```
# submission 42135285
def solve(n, fights):
ans = [0] * (n + 2)
nxt = list(range(1, n + 3))
for l, r, x in fights:
while l < x:
if ans[l]:
k = nxt[l]
nxt[l] = x
l = k
else:
nxt[l] = ans[l] = x
l += 1
l += 1
r += 1
while ans[r]:
r = nxt[r]
while l < r:
if ans[l]:
k = nxt[l]
nxt[l] = r
l = k
else:
nxt[l] = r
ans[l] = x
l += 1
return ans[1:-1]
def read():
return list(map(int, input().split()))
def main():
n, m = read()
fights = [read() for _ in range(m)]
ans = solve(n, fights)
print(*ans)
if __name__ == "__main__":
main()
``` | output | 1 | 54,301 | 2 | 108,603 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 54,302 | 2 | 108,604 |
Tags: data structures, dsu
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
from collections import Counter
import math
#n,m=map(int,input().split())
from collections import Counter
#for i in range(n):
import math
#for _ in range(int(input())):
#n = int(input())
#for _ in range(int(input())):
#n = int(input())
import bisect
'''for _ in range(int(input())):
n=int(input())
n,k=map(int, input().split())
arr = list(map(int, input().split()))'''
#n = int(input())
m=0
n,k=map(int, input().split())
ans=[0]*n
jump=[i+1 for i in range(n+2)]
for _ in range(k):
l,r,x= map(int, input().split())
i=l
while i<=r:
if ans[i-1]==0 and i!=x:
ans[i-1]=x
var=jump[i]
if i<x:
jump[i]=x
else:
jump[i]=r+1
i=var
#print(ans)
print(*ans)
``` | output | 1 | 54,302 | 2 | 108,605 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 54,303 | 2 | 108,606 |
Tags: data structures, dsu
Correct Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
from io import BytesIO, IOBase
import sys
class SortedList:
def __init__(self, iterable=None, _load=200):
"""Initialize sorted list instance."""
if iterable is None:
iterable = []
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def main():
n,m=map(int,input().split())
arr=range(1,n+1)
arr=SortedList(arr)
# print(arr)
ans=[0]*(n+1)
for _ in range(m):
l,r,k=map(int,input().split())
z=arr.bisect_left(l)
# print(z,l,r,arr)
while z<len(arr):
if arr[z]==k:
z+=1
elif arr[z]>r:
break
else:
ans[arr[z]]=k
arr.remove(arr[z])
print(*(ans)[1:])
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 54,303 | 2 | 108,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")
class SegmentTree:
def __init__(self, n):
self.tree = [0] * (2 * n)
self.n = n
# get interval[l,r)
def query(self, l, r, val):
l += self.n
r += self.n
while l < r:
if l % 2 == 1:
self.tree[l] = val
l += 1
if r % 2 == 1:
r -= 1
self.tree[r] = val
l //= 2
r //= 2
def search(self, idx):
idx += self.n
res = [0, 0]
while idx > 1:
if self.tree[idx] and self.tree[idx][1] >= res[1]:
res = self.tree[idx].copy()
idx //= 2
return res
# submission 72248479
def solve1(n, fights):
ans = [0] * (n + 1)
tree = SegmentTree(n)
c = 0
for l, r, x in (fights[::-1]):
tree.query(l - 1, x - 1, [x, c])
tree.query(x, r, [x, c])
c += 1
for i in range(n):
if fights[-1][2] != i + 1:
ans[i + 1] = tree.search(i)[0]
return ans[1:]
# submission 42135285
def solve2(n, fights):
ans = [0] * (n + 2)
# if knight v is alive, then next[v] = v
# if knight v is out of tournament, next[v] points
# to some knight u (next[v] = u), such that there
# are no alive knights between v and u;
nxt = list(range(1, n + 3))
for l, r, x in fights:
while l < x: # knights in the interval with idx below the winner
if ans[l]: # it is already beaten
k = nxt[l] # store who did beat him
nxt[l] = x # the next alive from l is current winner
l = k # next iteration start from k since l+1..k-1 are beaten
else: # he's alive
nxt[l] = x # next alive from l is the current winner
ans[l] = x
l += 1
l += 1 # l = x + 1
# find out after the interval who is the next alive
# last elm of ans handles the case when the current knight is the last
# knight and is out of tournament
r += 1
while ans[r]:
r = nxt[r]
while l < r: # knights from x + 1 to the end
if ans[l]: # it is already beaten
k = nxt[l] # store who did beat him
nxt[l] = r # the next alive from l is r
l = k # next iteration start from k since l+1..k-1 are beaten
else: # he is alive
nxt[l] = r # next alive is r
ans[l] = x # he's beaten by x
l += 1
return ans[1:-1]
def read():
return list(map(int, input().split()))
def main():
n, m = read()
fights = [read() for _ in range(m)]
ans = solve1(n, fights)
print(*ans)
if __name__ == "__main__":
main()
``` | instruction | 0 | 54,304 | 2 | 108,608 |
Yes | output | 1 | 54,304 | 2 | 108,609 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
def ans():
n,m = map(int,input().split())
res,alive = [0]*n,[(i+1) for i in range(n+2)]
from sys import stdin
for _ in range(m):
l,r,x = map(int,stdin.readline().split())
i=l
while i<=r:
if res[i-1]==0 and i!=x:
res[i-1] = x
temp = alive[i]
if i < x:
alive[i] = x
else:
alive[i] = r+1
i = temp
print(*res)
ans()
``` | instruction | 0 | 54,305 | 2 | 108,610 |
Yes | output | 1 | 54,305 | 2 | 108,611 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
from collections import *
from sys import stdin
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return list(stdin.readline()[:-1])
class segmenttree:
def __init__(self, arr, n):
self.tree, self.n = [0] * (2 * n), n
# build tree
if arr:
for i in range(2 * n - 1, 0, -1):
if i >= n:
self.tree[i] = arr[i - n]
else:
self.tree[i] = self.tree[i << 1] + self.tree[(i << 1) + 1]
# get interval[l,r)
def query(self, l, r, val):
res = 0
l += self.n
r += self.n
while l < r:
if l & 1:
self.tree[l] = val
l += 1
if r & 1:
r -= 1
self.tree[r] = val
l >>= 1
r >>= 1
return res
def search(self, ix):
ix += self.n
# move up
ret = [0, 0]
while ix > 1:
if self.tree[ix] and self.tree[ix][1] >= ret[1]:
ret = self.tree[ix].copy()
ix >>= 1
return ret
n, m = map(int, input().split())
ans, tree = [0] * (n + 1), segmenttree([], n)
quaries, c = [arr_inp(1) for i in range(m)], 0
for l, r, x in (quaries[::-1]):
tree.query(l - 1, x - 1, [x, c])
tree.query(x, r, [x, c])
c += 1
for i in range(n):
if quaries[-1][2] != i + 1:
ans[i + 1] = tree.search(i)[0]
print(*ans[1:])
``` | instruction | 0 | 54,306 | 2 | 108,612 |
Yes | output | 1 | 54,306 | 2 | 108,613 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
from sys import stdout, stdin
#------------------ USER DEFINED PROGRAMMING FUNCTIONS ------------------#
st=lambda:list(stdin.readline().strip())
li=lambda:list(map(int,stdin.readline().split()))
mp=lambda:map(int,stdin.readline().split())
inp=lambda:int(stdin.readline())
pr=lambda n: stdout.write(str(n)+"\n")
import bisect
case = li()
ans=[0 for i in range(case[0])]
nextl=[i+1 for i in range(case[0]+2)]
for j in range(case[1]):
f = li()
i=f[0]
while i<=f[1]:
if ans[i-1]==0 and i!=f[2]:
ans[i-1]=f[2]
a=nextl[i]
if i<f[2]:
nextl[i]=f[2]
else:
nextl[i]=f[1]+1
i=a
print(*ans)
``` | instruction | 0 | 54,307 | 2 | 108,614 |
Yes | output | 1 | 54,307 | 2 | 108,615 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ######### #
###### ######### # # # # # # ######### #
# # # # # # # # # # #### # # #
# # # # # # # ## # # # # #
###### # # ####### ####### # # ##### # # # #
from __future__ import print_function # for PyPy2
from collections import Counter, OrderedDict
from itertools import permutations as perm
from fractions import Fraction
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")
n, m = gil()
ans = [[] for _ in range(n+1)]
h = []
rem = [0]*(n+1)
winner = [0]*(n+1)
for _ in range(m):
l, r, w = gil()
if l == w:
l += 1
ans[l].append((_, w))
if r == w:
ans[r].append(w)
else:
if r+1 <= n:ans[r+1].append(w)
for i in range(1, n+1):
while ans[i]:
if type(ans[i][-1]) == int:
rem[ans[i].pop()] = 1
else:
# print(ans)
heappush(h, ans[i].pop())
while h and rem[h[0][1]]:
heappop(h)
if h:
winner[i] = h[0][1]
print(*winner[1:])
``` | instruction | 0 | 54,308 | 2 | 108,616 |
No | output | 1 | 54,308 | 2 | 108,617 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
#!/usr/bin/env python3
import os
import sys
from atexit import register
from io import StringIO
# Buffered output, at least 2x faster.
sys.stdout = StringIO()
register(lambda: os.write(1, sys.stdout.getvalue().encode()))
###############################################################################
import math
###############################################################################
n,m = [int(k) for k in input().split()]
t = [0] * (4*n)
def update(x, l, r, v, tl, tr):
if r < l: return
if l == tl and r == tr:
t[v] = t[v] or x
else:
tm = int((tl+tr)/2)
update(x, l, min(tm, r), 2*v, tl, tm)
update(x, max(tm+1, l), r, 2*v+1, tm+1, tr)
def query(i):
v = 1
tl = 0
tr = n-1
while tl != tr:
tm = int((tl+tr)/2)
if i <= tm:
v = 2*v
tr = tm
else:
v = 2*v+1
tl = tm+1
k = t[v]
while k == 0 and v != 0:
v = int(v/2)
k = t[v]
return k
for _ in range(m):
l,r,x = [int(k) for k in input().split()]
update(x, l-1, x-2, 1, 0, n-1)
update(x, x, r-1, 1, 0, n-1)
print(' '.join([str(query(k)) for k in range(n)]))
``` | instruction | 0 | 54,309 | 2 | 108,618 |
No | output | 1 | 54,309 | 2 | 108,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
#codeforce 356 problem A
from math import ceil, log2
n, m = map(int, input().split())
x = int(ceil(log2(n)))
max_size = 2*pow(2, n) - 1
a = [i for i in range(0, n+1)]
# def update(a, start, end, i, val, si):
# if start == end:
# a[i] = val
# stree[si] = val
# else:
# mid = start+
# stree = [0 for i in range(0, max_size)]
# construct(a, 0, n)
for i in range(m):
l, r, x = map(int, input().split())
for j in range(l, r+1):
if j == a[j] or a[j] == 0:
a[j] = x
if i == m-1:
a[x] = 0
print(a[1:])
``` | instruction | 0 | 54,310 | 2 | 108,620 |
No | output | 1 | 54,310 | 2 | 108,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
print("4 4 4 0")
``` | instruction | 0 | 54,311 | 2 | 108,622 |
No | output | 1 | 54,311 | 2 | 108,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze and her friends are trying to infiltrate a secret base built by Claris. However, Claris has been aware of that and set a bomb which is going to explode in a minute. Although they try to escape, they have no place to go after they find that the door has been locked.
At this very moment, CJB, Father of Tokitsukaze comes. With his magical power given by Ereshkigal, the goddess of the underworld, CJB is able to set m barriers to protect them from the explosion. Formally, let's build a Cartesian coordinate system on the plane and assume the bomb is at O(0, 0). There are n persons in Tokitsukaze's crew, the i-th one of whom is at P_i(X_i, Y_i). Every barrier can be considered as a line with infinity length and they can intersect each other. For every person from Tokitsukaze's crew, there must be at least one barrier separating the bomb and him, which means the line between the bomb and him intersects with at least one barrier. In this definition, if there exists a person standing at the position of the bomb, any line through O(0, 0) will satisfy the requirement.
Although CJB is very powerful, he still wants his barriers to be as far from the bomb as possible, in order to conserve his energy. Please help him calculate the maximum distance between the bomb and the closest barrier while all of Tokitsukaze's crew are safe.
Input
The first line contains two integers n, m (1 ≤ n, m ≤ 10^5), indicating the number of people and the number of barriers respectively.
The i-th line of the next n lines contains two integers X_i, Y_i (-10^5 ≤ X_i, Y_i ≤ 10^5), indicating the i-th person's location P_i(X_i, Y_i). Note that P_i may have the same coordinates as P_j (j ≠ i) or even O.
Output
Print a single real number — the maximum distance meeting the requirement. Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if (|a - b|)/(max(1, |b|)) ≤ 10^{-6}.
Examples
Input
3 1
2 0
0 2
-1 0
Output
0.0000000000
Input
1 1
0 0
Output
0.0000000000
Input
2 1
-1 -1
-1 -1
Output
1.4142135617
Input
3 100000
3 2
-1 -3
2 -5
Output
3.1622776602
Note
In the first two examples, CJB must set the barrier crossing O(0, 0).
In the last two examples, CJB can set each barrier crossing some P_i such that the barrier is perpendicular to the line between P_i and O.
Submitted Solution:
```
import math
def find_m(x, y):
if x == 0:
m = 'u'
else:
m = y / x
if m == -0.0:
return abs(m)
return m
def find_dis(x, y):
return math.sqrt(x * x + y * y)
max_db = 0.0000000000
pb = [int(x) for x in input().split(' ')]
if pb[1] < pb[0]:
temp1 = [int(s) for s in input().split(' ')]
m1 = find_m(temp1[0], temp1[1])
for x in range(1, pb[0]):
temp2 = [int(s) for s in input().split(' ')]
m2 = find_m(temp2[0], temp2[1])
if m1 == m2:
max_db = find_dis(temp2[0], temp2[1])
else:
max_db = 0.0000000000
break
else:
dist = []
for x in range(0, pb[0]):
coor = [int(s) for s in input().split(' ')]
dist.append(find_dis(coor[0], coor[1]))
max_db = min(dist)
print(round(max_db, 10))
``` | instruction | 0 | 54,876 | 2 | 109,752 |
No | output | 1 | 54,876 | 2 | 109,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 55,119 | 2 | 110,238 |
Tags: data structures, dsu
Correct Solution:
```
n, m = map(int, input().split())
p, d = [0] * (n + 2), list(range(1, n + 3))
for i in range(m):
l, r, x = map(int, input().split())
while l < x:
if p[l]:
k = d[l]
d[l] = x
l = k
else:
d[l], p[l] = x, x
l += 1
l += 1
r += 1
while p[r]: r = d[r]
while l < r:
if p[l]:
k = d[l]
d[l] = r
l = k
else:
d[l], p[l] = r, x
l += 1
print(' '.join(map(str, p[1: -1])))
# Made By Mostafa_Khaled
``` | output | 1 | 55,119 | 2 | 110,239 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 55,120 | 2 | 110,240 |
Tags: data structures, dsu
Correct Solution:
```
from collections import *
from sys import stdin
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return list(stdin.readline()[:-1])
class segmenttree:
def __init__(self, arr, n):
self.tree, self.n = [0] * (2 * n), n
# build tree
if arr:
for i in range(2 * n - 1, 0, -1):
if i >= n:
self.tree[i] = arr[i - n]
else:
self.tree[i] = self.tree[i << 1] + self.tree[(i << 1) + 1]
# get interval[l,r)
def query(self, l, r, val):
res = 0
l += self.n
r += self.n
while l < r:
if l & 1:
self.tree[l] = val
l += 1
if r & 1:
r -= 1
self.tree[r] = val
l >>= 1
r >>= 1
return res
def search(self, ix):
ix += self.n
# move up
ret = [0, 0]
while ix > 1:
if self.tree[ix] and self.tree[ix][1] >= ret[1]:
ret = self.tree[ix].copy()
ix >>= 1
return ret
n, m = map(int, input().split())
ans, tree = [0] * (n + 1), segmenttree([], n)
quaries, c = [arr_inp(1) for i in range(m)], 0
for l, r, x in (quaries[::-1]):
tree.query(l - 1, x - 1, [x, c])
tree.query(x, r, [x, c])
c += 1
for i in range(n):
if quaries[-1][2] != i + 1:
ans[i + 1] = tree.search(i)[0]
print(*ans[1:])
``` | output | 1 | 55,120 | 2 | 110,241 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 55,121 | 2 | 110,242 |
Tags: data structures, dsu
Correct Solution:
```
import sys
from collections import defaultdict
class llnode:
p = None
n = None
val = None
class llist:
root = None
def __init__(self, totalNodes):
self.ans = [0 for _ in range(totalNodes + 1)]
self.makell(totalNodes)
def makell(self, total):
root = llnode()
curVal = 1
root.val = curVal
self.root = root
curNode = self.root
while curVal < total:
curVal += 1
nextNode = llnode()
nextNode.val = curVal
nextNode.p = curNode
curNode.n = nextNode
curNode = nextNode
def printll(self):
curNode = self.root
while curNode:
print(curNode.val)
curNode = curNode.n
def remove(self, node, vanqVal):
self.ans[node.val] = vanqVal
if node == self.root:
self.root = node.n
self.root.p = None
node.p = None
del node
else:
node.p.n = node.n
if node.n:
node.n.p = node.p
del node
def removeNodes(self, startVal, endVal, exception):
curNode = self.root
while curNode and curNode.val < startVal:
curNode = curNode.n
while curNode and curNode.val <= endVal:
if curNode.val != exception:
remNode = curNode
curNode = curNode.n
self.remove(remNode, exception)
else:
curNode = curNode.n
def getAns(self):
return self.ans
def results(knights, tList):
ans = [0 for _ in range(knights + 1)] # remember not to print 0
for l, r, winner in tList:
for i in range(l, r + 1):
if i != winner and ans[i] == 0:
ans[i] = winner
return ans[1:]
def results2(knights, tList):
k = llist(knights)
for l, r, winner in tList:
k.removeNodes(l, r, winner)
return k.getAns()[1:]
def results3(knights, tList):
jumpList = [[0, 0] for _ in range(knights + 1)] # prev / next
ans = [0 for _ in range(knights + 1)]
for l, r, winner in tList:
left = l
right = r
while left < winner:
if ans[left] == 0:
ans[left] = winner
jumpList[left] = [l - 1, winner] # 0 points left, 1 points right
left += 1
else: # ans already filled, update the jumplist with bigger vals if possible
curLeft = left
left = jumpList[left][1] # move right
jumpList[curLeft][0] = min(l - 1, jumpList[curLeft][0]) # update left
jumpList[curLeft][1] = max(winner, jumpList[curLeft][1]) # update right
while right > winner:
if ans[right] == 0:
ans[right] = winner
jumpList[right] = [winner, r + 1]
right -= 1
else:
curRight = right
right = jumpList[right][0] # move left
jumpList[curRight][0] = min(
winner, jumpList[curRight][0]
) # update left
jumpList[curRight][1] = max(
r + 1, jumpList[curRight][1]
) # update right
return ans[1:]
def readinput():
n, m = map(int, sys.stdin.readline().rstrip().split(" "))
tList = []
for _ in range(m):
l, r, win = map(int, sys.stdin.readline().rstrip().split(" "))
tList.append((l, r, win))
for i in results3(n, tList):
print(i, end=" ")
readinput()
``` | output | 1 | 55,121 | 2 | 110,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 55,122 | 2 | 110,244 |
Tags: data structures, dsu
Correct Solution:
```
n, m = (int(k) for k in input().split())
list_nxt = [i+1 for i in range(n+1)]
result = [0]*n
for line in range(m):
l, r, x = (int(k) for k in input().split())
pt = l
while pt <= r:
if result[pt-1] == 0 and pt != x:
result[pt-1] = x
nxt = list_nxt[pt]
if pt < x:
list_nxt[pt] = x
else:
list_nxt[pt] = r + 1
pt = nxt
print(*result)
``` | output | 1 | 55,122 | 2 | 110,245 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 55,123 | 2 | 110,246 |
Tags: data structures, dsu
Correct Solution:
```
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
# from sys import stdin
# input = stdin.readline
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
try:
# sys.setrecursionlimit(int(pow(10,6)))
sys.stdin = open("input.txt", "r")
# sys.stdout = open("../output.txt", "w")
except:
pass
def pmat(A):
for ele in A:
print(*ele,end="\n")
def seive():
prime=[1 for i in range(10**6+1)]
prime[0]=0
prime[1]=0
for i in range(10**6+1):
if(prime[i]):
for j in range(2*i,10**6+1,i):
prime[j]=0
return prime
n,m = map(int,input().split())
res,anext = [0]*n,[i+1 for i in range(n+2)]
from sys import stdin
for _ in range(m):
l,r,x = map(int,stdin.readline().split())
i=l
while i<=r:
if res[i-1]==0 and i!=x:
res[i-1]=x
save = anext[i]
if i<x:
anext[i]=x
else:
anext[i]=r+1
i=save
# print(res)
# print(anext)
print(*res)
endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")
``` | output | 1 | 55,123 | 2 | 110,247 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 55,124 | 2 | 110,248 |
Tags: data structures, dsu
Correct Solution:
```
inp = lambda: map(int, input().split())
n, m = inp()
link = [i+1 for i in range(n+3)]
ans = [0] * (n+1)
for _ in range(m):
l, r, x = inp()
pt = l
while pt <= r:
if ans[pt] == 0 and pt != x:
ans[pt] = x
nxt = link[pt]
if pt < x:
link[pt] = x
else:
link[pt] = r+1
pt = nxt
print(*ans[1:])
``` | output | 1 | 55,124 | 2 | 110,249 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won. | instruction | 0 | 55,125 | 2 | 110,250 |
Tags: data structures, dsu
Correct Solution:
```
n, m = (int(x) for x in input().split())
results = [0]*n # n = 3 -> [0, 0, 0] [kn-1]
pointers = [k for k in range(2, n+2)] # n = 3 -> [2, 3, 4] [kn-1]
for i in range(m):
l, r, x = [int(k) for k in input().split()]
while l <= r:
if l != x and results[l-1] == 0: results[l-1] = x
nxt = pointers[l-1]
if l < x: pointers[l-1] = x
else: pointers[l-1] = r+1
l = nxt
print(*results)
``` | output | 1 | 55,125 | 2 | 110,251 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
n, m = (int(k) for k in input().split())
result = [0]*n
old_l = 0
old_r = 0
winner = 0
for line in range(m):
l, r, x = (int(k) for k in input().split())
if old_l == 0 and old_r == 0:
for i in range(l, r+1):
if i != x:
result[i-1] = x
old_l = l
old_r = r
winner = x
else:
if l < old_l:
for i in range(l, old_l):
if i != x:
result[i - 1] = x
old_l = l
if r > old_r:
for i in range(old_r + 1, r + 1):
if i != x:
result[i - 1] = x
old_r = r
if winner != x:
result[winner-1] = x
winner = x
print(*result)
``` | instruction | 0 | 55,126 | 2 | 110,252 |
No | output | 1 | 55,126 | 2 | 110,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
from collections import *
from sys import stdin
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return list(stdin.readline()[:-1])
class segmenttree:
def __init__(self, arr, n):
self.tree, self.n = [0] * (2 * n), n
# build tree
if arr:
for i in range(2 * n - 1, 0, -1):
if i >= n:
self.tree[i] = arr[i - n]
else:
self.tree[i] = self.tree[i << 1] + self.tree[(i << 1) + 1]
# get interval[l,r)
def query(self, l, r, val):
res = 0
l += self.n
r += self.n
while l < r:
if l & 1:
self.tree[l] = val
l += 1
if r & 1:
r -= 1
self.tree[r] = val
l >>= 1
r >>= 1
return res
def search(self, ix):
ix += self.n
# move up
while ix > 1:
if self.tree[ix]:
return self.tree[ix]
ix >>= 1
return self.tree[ix]
n, m = map(int, input().split())
ans, tree = [0] * (n + 1), segmenttree([], n)
quaries = [arr_inp(1) for i in range(m)]
for l, r, x in quaries[::-1]:
tree.query(l - 1, x - 1, x)
tree.query(x, r, x)
for i in range(n):
if quaries[-1][2] != i + 1:
ans[i + 1] = tree.search(i)
print(*ans[1:])
``` | instruction | 0 | 55,127 | 2 | 110,254 |
No | output | 1 | 55,127 | 2 | 110,255 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Submitted Solution:
```
import sys
def results(knights, tList):
ans = [0 for _ in range(knights + 1)] # remember not to print 0
for l, r, winner in tList:
for i in range(l, r + 1):
if i != winner and ans[i] == 0:
ans[i] = winner
return ans[1:]
def readinput():
n, m = map(int, sys.stdin.readline().rstrip().split(" "))
tList = []
for _ in range(m):
l, r, win = map(int, sys.stdin.readline().rstrip().split(" "))
tList.append((l, r, win))
print(results(n, tList))
readinput()
``` | instruction | 0 | 55,128 | 2 | 110,256 |
No | output | 1 | 55,128 | 2 | 110,257 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an n × n grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:
The sound of clashing rocks will awaken the door!
Being a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks:
* '^': this rock moves upwards;
* '<': this rock moves leftwards;
* '>': this rock moves rightwards;
* 'v': this rock moves downwards.
To open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already 107 events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated.
If a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least x. It is okay for the rocks to continue moving after producing x sounds.
The following picture illustrates the four possible scenarios of moving rocks.
* Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated. <image>
* Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end. <image>
* Does not move because a rock is already standing in the path. The blocking rock becomes activated, but no sounds are produced. <image>
* Does not move because the wall is in the way. No sounds are produced and the movements end. <image>
Assume there's an infinite number of rocks of each type in the neighboring room. You know what to do: place the rocks and open the door!
Input
The first line will consists of two integers n and x, denoting the size of the room and the number of sounds required to open the door. There will be exactly three test cases for this problem:
* n = 5, x = 5;
* n = 3, x = 2;
* n = 100, x = 105.
All of these testcases are in pretest.
Output
Output n lines. Each line consists of n characters — the j-th character of the i-th line represents the content of the tile at the i-th row and the j-th column, and should be one of these:
* '^', '<', '>', or 'v': a rock as described in the problem statement.
* '.': an empty tile.
Then, output two integers r and c (1 ≤ r, c ≤ n) on the next line — this means that the rock you activate first is located at the r-th row from above and c-th column from the left. There must be a rock in this cell.
If there are multiple solutions, you may output any of them.
Examples
Input
5 5
Output
>...v
v.<..
..^..
>....
..^.<
1 1
Input
3 2
Output
>vv
^<.
^.<
1 3
Note
Here's a simulation of the first example, accompanied with the number of sounds produced so far.
<image> 0 sound <image> 1 sound <image> 2 sounds <image> 3 sounds <image> 4 sounds <image> still 4 sounds
In the picture above, the activated rock switches between the '^' rock and the '<' rock. However, no sound is produced since the '^' rock didn't move even a single tile. So, still 4 sound.
<image> 5 sounds
At this point, 5 sound are already produced, so this solution is already correct. However, for the sake of example, we will continue simulating what happens.
<image> 6 sounds <image> 7 sounds <image> still 7 sounds <image> 8 sounds
And the movement stops. In total, it produces 8 sounds. Notice that the last move produced sound.
Here's a simulation of the second example:
<image> 0 sound <image> 1 sound <image> 2 sounds
Now, the activated stone will switch continuously from one to another without producing a sound until it reaches the 107 limit, after which the movement will cease.
<image>
In total, it produced exactly 2 sounds, so the solution is correct. | instruction | 0 | 56,662 | 2 | 113,324 |
Tags: constructive algorithms
Correct Solution:
```
n=input()
if n[0]=='5':print(">.>.v\n.v.<.\n>.>^v\n.>.^.\n^.<.<\n1 1")
elif n[0]=='3':print(">.v\n>^.\n^.<\n1 1")
else:print(">"*34+".>"*32+".v\n"+("^."+"<."*32+"<"*33+"v\n"+">"*33+".>"*32+".^v\n")*16+("^."+"<."*32+"<"*33+"v\n"+">"*33+".>"*32+".^.\n")*33+"^."+"<."*32+"<"*34+"\n1 1")
``` | output | 1 | 56,662 | 2 | 113,325 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an n × n grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:
The sound of clashing rocks will awaken the door!
Being a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks:
* '^': this rock moves upwards;
* '<': this rock moves leftwards;
* '>': this rock moves rightwards;
* 'v': this rock moves downwards.
To open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already 107 events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated.
If a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least x. It is okay for the rocks to continue moving after producing x sounds.
The following picture illustrates the four possible scenarios of moving rocks.
* Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated. <image>
* Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end. <image>
* Does not move because a rock is already standing in the path. The blocking rock becomes activated, but no sounds are produced. <image>
* Does not move because the wall is in the way. No sounds are produced and the movements end. <image>
Assume there's an infinite number of rocks of each type in the neighboring room. You know what to do: place the rocks and open the door!
Input
The first line will consists of two integers n and x, denoting the size of the room and the number of sounds required to open the door. There will be exactly three test cases for this problem:
* n = 5, x = 5;
* n = 3, x = 2;
* n = 100, x = 105.
All of these testcases are in pretest.
Output
Output n lines. Each line consists of n characters — the j-th character of the i-th line represents the content of the tile at the i-th row and the j-th column, and should be one of these:
* '^', '<', '>', or 'v': a rock as described in the problem statement.
* '.': an empty tile.
Then, output two integers r and c (1 ≤ r, c ≤ n) on the next line — this means that the rock you activate first is located at the r-th row from above and c-th column from the left. There must be a rock in this cell.
If there are multiple solutions, you may output any of them.
Examples
Input
5 5
Output
>...v
v.<..
..^..
>....
..^.<
1 1
Input
3 2
Output
>vv
^<.
^.<
1 3
Note
Here's a simulation of the first example, accompanied with the number of sounds produced so far.
<image> 0 sound <image> 1 sound <image> 2 sounds <image> 3 sounds <image> 4 sounds <image> still 4 sounds
In the picture above, the activated rock switches between the '^' rock and the '<' rock. However, no sound is produced since the '^' rock didn't move even a single tile. So, still 4 sound.
<image> 5 sounds
At this point, 5 sound are already produced, so this solution is already correct. However, for the sake of example, we will continue simulating what happens.
<image> 6 sounds <image> 7 sounds <image> still 7 sounds <image> 8 sounds
And the movement stops. In total, it produces 8 sounds. Notice that the last move produced sound.
Here's a simulation of the second example:
<image> 0 sound <image> 1 sound <image> 2 sounds
Now, the activated stone will switch continuously from one to another without producing a sound until it reaches the 107 limit, after which the movement will cease.
<image>
In total, it produced exactly 2 sounds, so the solution is correct. | instruction | 0 | 56,663 | 2 | 113,326 |
Tags: constructive algorithms
Correct Solution:
```
r, c = map(int, input().split())
if r == 3:
print('>vv')
print('^<.')
print('^.<')
print('1 3')
elif r == 5:
print('>...v')
print('v.<..')
print('..^..')
print('>....')
print('..^.<')
print('1 1')
elif r == 100:
for i in range(25):
print('>'*50+'.>'*24+'.v')
print('^'+'<.'*25+'<'*49)
print('v.'+'<.'*24+'<'*50)
print('>'*49+'.>'*25+'^')
print('1 1')
else:
d = []
d[1] = 1
``` | output | 1 | 56,663 | 2 | 113,327 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.