message stringlengths 2 43.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 853 107k | cluster float64 24 24 | __index_level_0__ int64 1.71k 214k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | instruction | 0 | 19,689 | 24 | 39,378 |
Tags: implementation, math
Correct Solution:
```
import math
def get_lcm(n1, n2):
# find gcd
gcd = math.gcd(n1, n2)
# formula
result = (n1 * n2) / gcd
return result
class CodeforcesTask173ASolution:
def __init__(self):
self.result = ''
self.rounds = 0
self.n_str = ''
self.p_str = ''
def read_input(self):
self.rounds = int(input())
self.n_str = input()
self.p_str = input()
def process_task(self):
n = int(len(self.n_str))
k = int(len(self.p_str))
ap = 0
bp = 0
np = 0
pp = 0
full_round = int(get_lcm(n, k))
if self.rounds <= full_round:
for x in range(self.rounds):
a = self.n_str[ap]
b = self.p_str[bp]
ap += 1
bp += 1
if ap >= n:
ap = 0
if bp >= k:
bp = 0
if (a == "R" and b == "S") or (a == "S" and b == "P") or (a == "P" and b == "R"):
pp += 1
elif (b == "R" and a == "S") or (b == "S" and a == "P") or (b == "P" and a == "R"):
np += 1
self.result = "{0} {1}".format(np, pp)
else:
for x in range(full_round):
a = self.n_str[ap]
b = self.p_str[bp]
ap += 1
bp += 1
if ap >= n:
ap = 0
if bp >= k:
bp = 0
if (a == "R" and b == "S") or (a == "S" and b == "P") or (a == "P" and b == "R"):
pp += 1
elif (b == "R" and a == "S") or (b == "S" and a == "P") or (b == "P" and a == "R"):
np += 1
np *= self.rounds // full_round
pp *= self.rounds // full_round
for x in range(self.rounds % full_round):
a = self.n_str[ap]
b = self.p_str[bp]
ap += 1
bp += 1
if ap >= n:
ap = 0
if bp >= k:
bp = 0
if (a == "R" and b == "S") or (a == "S" and b == "P") or (a == "P" and b == "R"):
pp += 1
elif (b == "R" and a == "S") or (b == "S" and a == "P") or (b == "P" and a == "R"):
np += 1
self.result = "{0} {1}".format(np, pp)
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask173ASolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
``` | output | 1 | 19,689 | 24 | 39,379 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | instruction | 0 | 19,690 | 24 | 39,380 |
Tags: implementation, math
Correct Solution:
```
Q=lambda x,y:Q(y%x,x)if x else y
I=input
R=range
n=int(I())
s=I()
p=I()
G=len(p)//Q(len(s),len(p))*len(s)
s*=G//len(s)
p*=G//len(p)
a=b=0
for i in R(G):
t=s[i]+p[i]
if t=='RS'or t=='SP'or t=='PR':a+=1
elif t=='SR'or t=='PS' or t=='RP':b+=1
a*=(n//G)
b*=(n//G)
for i in R(n%G):
t=s[i]+p[i]
if t=='RS'or t=='SP'or t=='PR':a+=1
elif t=='SR'or t=='PS' or t=='RP':b+=1
print(b,a)
``` | output | 1 | 19,690 | 24 | 39,381 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | instruction | 0 | 19,691 | 24 | 39,382 |
Tags: implementation, math
Correct Solution:
```
n = int(input())
a = input()
b = input()
ai = 0
alen = len(a)
bi = 0
blen = len(b)
nik = 0
pol = 0
if alen == blen: rnd = alen
else: rnd = alen*blen
numofrounds = 0
for i in range(n):
#print(i,rnd)
if i == rnd:
numofrounds = n//rnd
# print(numofrounds)
nik *= numofrounds
pol *= numofrounds
break
#print(a[ai%alen], b[bi%blen])
if a[ai] == b[bi]: pass
elif (a[ai] == 'R' and b[bi] == 'S') or (a[ai] == 'S'
and b[bi] == 'P') or (a[ai] == 'P' and b[bi] == 'R'):
pol += 1
else: nik += 1
ai = (ai+1)%alen
bi = (bi+1)%blen
if n%rnd != 0 and numofrounds != 0:
n -= rnd*numofrounds
ai = 0
bi = 0
for i in range(n):
if a[ai] == b[bi]: pass
elif (a[ai] == 'R' and b[bi] == 'S') or (a[ai] == 'S'
and b[bi] == 'P') or (a[ai] == 'P' and b[bi] == 'R'):
pol += 1
else: nik += 1
ai = (ai+1)%alen
bi = (bi+1)%blen
print(nik, pol)
``` | output | 1 | 19,691 | 24 | 39,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | instruction | 0 | 19,692 | 24 | 39,384 |
Tags: implementation, math
Correct Solution:
```
def gcd(a, b):
c = a % b
return gcd(b, c) if c else b
def f(k, m, n):
p = {}
for i in range(m * k + 1, 0, -k):
j = m - (i - 1 - n) % m
for d in range(j - n, n, m):
p[d] = i
return p
n, a, b = int(input()), input(), input()
k, m = len(a), len(b)
x, y, g = 0, 0, gcd(k, m)
p, q, r = (k * m) // g, f(k, m, 1000), {'S': 'P', 'P': 'R', 'R': 'S'}
for i in range(k):
for j in range(i % g, m, g):
if a[i] == b[j]: continue
d = (n - q[i - j] - i) // p + 1
if r[a[i]] == b[j]: y += d
else: x += d
print(x, y)
``` | output | 1 | 19,692 | 24 | 39,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | instruction | 0 | 19,693 | 24 | 39,386 |
Tags: implementation, math
Correct Solution:
```
n=int(input())
aa,bb=0,0
a=list(input())
b=list(input())
rp=[]
i=0
while( 1 ):
if a[i%len(a)]=="R":
if b[i%len(b)]=="P":
bb+=1
elif b[i%len(b)]=="S":
aa+=1
elif a[i%len(a)]=="P":
if b[i%len(b)]=="R":
aa+=1
elif b[i%len(b)]=="S":
bb+=1
else:
if b[i%len(b)]=="R":
bb+=1
elif b[i%len(b)]=="P":
aa+=1
i+=1
rp.append( (bb,aa) )
if ( i%len(a)==0 and i%len(b)==0 ) or i>n:
break
if len(rp)==n:
print(bb,aa)
else:
w = n//len(rp)
ww = n%len(rp)
if ww==0:
print( bb*w, aa*w )
else:
print( bb*w+rp[ww-1][0], aa*w+rp[ww-1][1] )
``` | output | 1 | 19,693 | 24 | 39,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | instruction | 0 | 19,694 | 24 | 39,388 |
Tags: implementation, math
Correct Solution:
```
import sys
rounds=int(sys.stdin.readline().strip('\n'))
def Solution():
global rounds
s_A=list(map(str, sys.stdin.readline().rstrip('\n')))
s_B=list(map(str, sys.stdin.readline().rstrip('\n')))
if rounds<=len(s_A):
s_A=s_A[0:rounds]
if rounds<len(s_B):
s_B=s_B[0:rounds]
return Prepare(s_A, s_B)
return Prepare(s_A, s_B)
elif rounds<len(s_B):
s_B=s_B[0:rounds]
if rounds<len(s_B):
s_A=s_A[0:rounds]
return Prepare(s_A, s_B)
return Prepare(s_A, s_B)
else:
return Prepare(s_A, s_B)
def Prepare(s_A, s_B):
if len(s_A)==len(s_B):
return Compare(s_A, s_B)
else:
if len(s_A)>len(s_B):
greater = len(s_A)
else:
greater = len(s_B)
while(True):
if((greater % len(s_A) == 0) and (greater % len(s_B) == 0)):
lcm = greater
break
greater += 1
Alcm=lcm//len(s_A)
Blcm=lcm//len(s_B)
return Compare(s_A*Alcm, s_B*Blcm)
def Compare(s_A, s_B):
global rounds
zipped=list(zip(s_A, s_B))
Nikephoros=0
Polycarpus=0
mult=1
for i in range (0, len(zipped)):
if rounds==i:
return print (Polycarpus*mult, Nikephoros*mult)
elif zipped[i][0]==zipped[i][1]:
pass
elif (zipped[i][0]=="S" and zipped[i][1]=="P") or \
(zipped[i][0]=="R" and zipped[i][1]=="S") or \
(zipped[i][0]=="P" and zipped[i][1]=="R"):
Nikephoros+=1
else:
Polycarpus+=1
if rounds%len(zipped)==0:
mult=rounds//len(zipped)
print (Polycarpus*mult, Nikephoros*mult)
else:
mult=rounds//len(zipped)
Nikephoros_add=0
Polycarpus_add=0
fraction=rounds - (len(zipped)*mult)
iter=0
for i in range (0, len(zipped)):
if iter==fraction:
return print(Polycarpus*mult + Polycarpus_add, Nikephoros*mult+ Nikephoros_add)
elif zipped[i][0]==zipped[i][1]:
iter+=1
pass
elif (zipped[i][0]=="S" and zipped[i][1]=="P") or \
(zipped[i][0]=="R" and zipped[i][1]=="S") or \
(zipped[i][0]=="P" and zipped[i][1]=="R"):
Nikephoros_add+=1
iter+=1
else:
Polycarpus_add+=1
iter+=1
Solution()
``` | output | 1 | 19,694 | 24 | 39,389 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | instruction | 0 | 19,695 | 24 | 39,390 |
Tags: implementation, math
Correct Solution:
```
import math
import itertools as it
n = int(input())
a, b = input(), input()
lcm = len(a) // math.gcd(len(a), len(b)) * len(b)
a, b = it.cycle(a), it.cycle(b)
res = {'RR': 0, 'SS': 0, 'PP': 0, 'RS': 'P', 'SP': 'P', 'PR': 'P', 'RP': 'N', 'SR': 'N', 'PS': 'N'}
v = []
for i in range(min(lcm, n)):
v.append(res[next(a) + next(b)])
ans = [v.count('N'), v.count('P')]
if n > lcm:
ans[0] *= n // lcm
ans[0] += v[: n % lcm].count('N')
ans[1] *= n // lcm
ans[1] += v[: n % lcm].count('P')
print(*ans)
``` | output | 1 | 19,695 | 24 | 39,391 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2. | instruction | 0 | 19,696 | 24 | 39,392 |
Tags: implementation, math
Correct Solution:
```
n=int(input())
finale=[]
co=0;fco=0;
s=input()
s1=input()
ssize=len(s)
s1size=len(s1)
s=s1size*s
s1=ssize*s1
for i in range(0,len(s)):
if (s[i]=='R' and s1[i]=='P'):
fco+=1
if (s[i]=='R' and s1[i]=='S'):
co+=1
if (s[i]=='S' and s1[i]=='P'):
co+=1
if (s[i]=='S' and s1[i]=='R'):
fco+=1
if (s[i]=='P' and s1[i]=='S'):
fco+=1
if (s[i]=='P' and s1[i]=='R'):
co+=1
finale.append((co,fco))
if(len(s)>=n):
co1=finale[n-1][0]
fco1=finale[n-1][1]
else:
co1=n//len(s);
co1*=finale[len(s)-1][0]
if n%len(s)!=0:
co1+=finale[((n)%(len(s)))-1][0]
fco1=n//len(s);
fco1*=finale[len(s)-1][1]
if n%len(s)!=0:
fco1+=finale[((n)%(len(s)))-1][1]
print(fco1," ",co1)
``` | output | 1 | 19,696 | 24 | 39,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Submitted Solution:
```
def gcd(a, b):
c = a % b
return gcd(b, c) if c else b
F = {}
def f(k, m, i, j):
global F
d = i - j
if d in F: return F[d] + i
u, v = i, d
while d:
if d < 0:
d += k
i += k
else: d -= m
i += 1
F[v] = i - u
return i
n, a, b = int(input()), input(), input()
k, m = len(a), len(b)
r = gcd(k, m)
p = (k * m) // r
x, y = 0, 0
for i in range(k):
for j in range(i % r, m, r):
if a[i] == b[j]: continue
d = (n - f(k, m, i, j)) // p + 1
if a[i] + b[j] in ['SP', 'PR', 'RS']: y += d
else: x += d
print(x, y)
``` | instruction | 0 | 19,697 | 24 | 39,394 |
Yes | output | 1 | 19,697 | 24 | 39,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Submitted Solution:
```
#------------------------------warmup----------------------------
import os
import sys
import math
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")
#-------------------game starts now----------------------------------------------------
def rps(x,y):
res=0
if x==y:
res=0
elif x=='R' and y=='S':
res=1
elif x=='S' and y=='P':
res=1
elif x=='P' and y=='R':
res=1
elif x=='R' and y=='P':
res=2
elif x=='S' and y=='R':
res=2
elif x=='P' and y=='S':
res=2
return res
n=int(input())
a=input()
b=input()
l1=len(a)
l2=len(b)
#print(a,b)
lcm=l1*l2//math.gcd(l1,l2)
c1=0
c2=0
for i in range (min(n,lcm)):
x=a[i%l1]
y=b[i%l2]
r=0
r=rps(x, y)
#print(r)
if r==1:
c1+=1
elif r==2:
c2+=1
#print(c2,c1)
if lcm<n:
t=n//lcm
c1*=t
c2*=t
t=n%lcm
#print(c2,c1)
for i in range (t):
x=a[i%l1]
y=b[i%l2]
r=0
r=rps(x, y)
if r==1:
c1+=1
elif r==2:
c2+=1
print(c2,c1)
``` | instruction | 0 | 19,698 | 24 | 39,396 |
Yes | output | 1 | 19,698 | 24 | 39,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Submitted Solution:
```
def co(x,y,s):
if x==y:return 0
z=(x=="P" and y=="R") or (x=="S" and y=="P") or (x=="R" and y=="S")
if s:return int(z)
return int(not z)
from math import gcd as gh
a=int(input());b=input();c=input()
b1=len(b);c1=len(c)
z=((b1*c1)//gh(b1,c1))
w=[0]*(z+1);w1=[0]*(z+1)
for i in range(1,z+1):
w[i]=co(b[(i-1)%b1],c[(i-1)%c1],0)+w[i-1]
w1[i]=co(b[(i-1)%b1],c[(i-1)%c1],1)+w1[i-1]
print(w[-1]*(a//z)+w[a%z],w1[-1]*(a//z)+w1[a%z])
``` | instruction | 0 | 19,699 | 24 | 39,398 |
Yes | output | 1 | 19,699 | 24 | 39,399 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Submitted Solution:
```
n=int(input())
a=input()
b=input()
l,r=0,0
nike=0
poly=0
if len(a)*len(b)>n:
for i in range(n):
x=a[l%(len(a))]
y=b[r%(len(b))]
if x==y:
l+=1
r+=1
continue
else:
#print(0)
if x=="R":
if y=="P":
nike+=1
else:
poly+=1
elif x=="P":
if y=="S":
nike+=1
else:
poly+=1
else:
if y=="R":
nike+=1
else:
poly+=1
l+=1
r+=1
else:
for i in range(len(a)*len(b)):
x=a[l%(len(a))]
y=b[r%(len(b))]
if x==y:
l+=1
r+=1
continue
else:
if x=="R":
if y=="P":
nike+=1
else:
poly+=1
elif x=="P":
if y=="S":
nike+=1
else:
poly+=1
else:
if y=="R":
nike+=1
else:
poly+=1
l+=1
r+=1
#print(nike,poly)
nike=nike*(n//(len(a)*len(b)))
poly=poly*(n//(len(a)*len(b)))
rem=n%(len(a)*len(b))
l,r=0,0
for i in range(rem):
x=a[l%(len(a))]
y=b[r%(len(b))]
if x==y:
l+=1
r+=1
continue
else:
if x=="R":
if y=="P":
nike+=1
else:
poly+=1
elif x=="P":
if y=="S":
nike+=1
else:
poly+=1
else:
if y=="R":
nike+=1
else:
poly+=1
l+=1
r+=1
print(nike,poly)
``` | instruction | 0 | 19,700 | 24 | 39,400 |
Yes | output | 1 | 19,700 | 24 | 39,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Submitted Solution:
```
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def counter(s, t, r):
p, q = 0, 0
for i in range(r):
if s[i % k] == 'P':
if t[i % m] == 'S':
q += 1
elif t[i % m] == 'R':
p += 1
elif s[i % k] == 'R':
if t[i % m] == 'S':
p += 1
elif t[i % m] == 'P':
q += 1
else:
if t[i % m] == 'P':
p += 1
elif t[i % m] == 'R':
q += 1
return p, q
n = int(input())
s = input()
t = input()
k, m = len(s), len(t)
r = k * m // gcd(k, m)
p, q = counter(s, t, n // r)
p1, q1 = counter(s, t, n % r)
print(q + q1, p + p1)
``` | instruction | 0 | 19,701 | 24 | 39,402 |
No | output | 1 | 19,701 | 24 | 39,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Submitted Solution:
```
n=int(input())
aa,bb=0,0
a=list(input())
b=list(input())
rp=[]
i=0
while( 1 ):
if a[i%len(a)]=="R":
if b[i%len(b)]=="P":
bb+=1
elif b[i%len(b)]=="S":
aa+=1
elif a[i%len(a)]=="P":
if b[i%len(b)]=="R":
aa+=1
elif b[i%len(b)]=="S":
bb+=1
else:
if b[i%len(b)]=="R":
bb+=1
elif b[i%len(b)]=="P":
aa+=1
i+=1
if ( i%len(a)==0 and i%len(b)==0 ) or i>n:
break
else:
rp.append( (bb,aa) )
if len(rp)==n:
print(bb,aa)
else:
w = n//len(rp)
ww = n%len(rp)
print( bb*w+rp[ww-1][0], aa*w+rp[ww-1][1] )
``` | instruction | 0 | 19,702 | 24 | 39,404 |
No | output | 1 | 19,702 | 24 | 39,405 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Submitted Solution:
```
import sys
def Solution():
s_A=list(map(str, sys.stdin.readline()))
s_B=list(map(str, sys.stdin.readline()))
zipped=list(zip(s_A, s_B))
Nikephoros=0
Polycarpus=0
for i in range (0, len(zipped)):
if zipped[i][0]==zipped[i][1]:
pass
elif (zipped[i][0]=="S" and zipped[i][1]=="P") or \
(zipped[i][0]=="R" and zipped[i][1]=="S") or \
(zipped[i][0]=="P" and zipped[i][1]=="R"):
Nikephoros+=1
else:
Polycarpus+=1
print (Polycarpus, Nikephoros)
Solution()
``` | instruction | 0 | 19,703 | 24 | 39,406 |
No | output | 1 | 19,703 | 24 | 39,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).
Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.
Input
The first line contains integer n (1 β€ n β€ 2Β·109) β the number of the game's rounds.
The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 β€ m, k β€ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.
Output
Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.
Examples
Input
7
RPS
RSPP
Output
3 2
Input
5
RRRRRRRR
R
Output
0 0
Note
In the first sample the game went like this:
* R - R. Draw.
* P - S. Nikephoros loses.
* S - P. Polycarpus loses.
* R - P. Nikephoros loses.
* P - R. Polycarpus loses.
* S - S. Draw.
* R - P. Nikephoros loses.
Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Submitted Solution:
```
n = int(input())
*N, = input()
*P, = input()
print(N,P)
def is_greater(a, b):
if (a == 'R' and b == 'S') or (a == 'P' and b == 'R') or (a == 'S' and b == 'P'):
print('a>b')
return 0
elif a == b:
print('a=b')
return 1
elif (b == 'R' and a == 'S') or (b == 'P' and a == 'R') or (b == 'S' and a == 'P'):
print('a<b')
return 2
return 'hurrah'
loseN, loseP, lenN, lenP = 0, 0, len(N), len(P)
for i in range(n):
if is_greater( N[i%lenN], P[i%lenP] ) == 0:
loseP += 1
elif is_greater( N[i%lenN], P[i%lenP] ) == 2:
loseN += 1
print(loseN, loseP)
``` | instruction | 0 | 19,704 | 24 | 39,408 |
No | output | 1 | 19,704 | 24 | 39,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO"). | instruction | 0 | 20,318 | 24 | 40,636 |
Tags: implementation
Correct Solution:
```
q=int(input())
o,x,y=input().split()
x=int(x)
y=int(y)
arz=min(x,y)
tool=max(x,y)
ans=""
for i in range(1,q):
o,x,y=input().split()
x=int(x)
y=int(y)
if x>y:
x,y=y,x
if o=="+":
if x>arz:
arz=x
if y>tool:
tool=y
else:
if x<arz or y<tool:
ans+="NO\n"
else:
ans+="YES\n"
print(ans)
``` | output | 1 | 20,318 | 24 | 40,637 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO"). | instruction | 0 | 20,319 | 24 | 40,638 |
Tags: implementation
Correct Solution:
```
import sys
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import *
from time import time
from io import StringIO as stream
from atexit import register
def sync_with_stdio(sync=True):
global input, flush
if sync:
flush = sys.stdout.flush
else:
sys.stdin = stream(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip('\r\n')
#sys.stdout = stream()
#register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
sync_with_stdio(False)
#input = sys.stdin.readline
#print = sys.stdout.write
n, = I()
w = 0
h = 0
while n:
n -= 1
c, x, y = input().split()
x = int(x)
y = int(y)
if c == '+':
if y > x: x, y = y , x
w = max(w, x)
h = max(h, y)
else:
if (x >= w and y >= h) or (y >= w and x >= h):
print('YES')
else:
print('NO')
``` | output | 1 | 20,319 | 24 | 40,639 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO"). | instruction | 0 | 20,320 | 24 | 40,640 |
Tags: implementation
Correct Solution:
```
def sync_with_stdio():
import sys
from io import StringIO as stream
from atexit import register
global input
sys.stdin = stream(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip('\r\n')
sys.stdout = stream()
register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
sync_with_stdio()
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
n, = I()
w = 0
h = 0
while n:
n -= 1
c, x, y = input().split()
x = int(x)
y = int(y)
if c == '+':
if y > x: x, y = y , x
w = max(w, x)
h = max(h, y)
else:
if (x >= w and y >= h) or (y >= w and x >= h):
print('YES')
else:
print('NO')
``` | output | 1 | 20,320 | 24 | 40,641 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO"). | instruction | 0 | 20,321 | 24 | 40,642 |
Tags: implementation
Correct Solution:
```
import sys
lax = -10**9;lay = -10**9
for _ in range(int(input())) :
sign,x,y = map(str,sys.stdin.readline().split())
x=int(x)
y=int(y)
if sign=="+" :
if y > x :
t=x
x=y
y=t
lax = max(x,lax)
lay = max(y,lay)
else :
if y > x :
t=x
x=y
y=t
#print(lax,lay)
if lax<=x and lay<=y :
print("YES")
else :
print("NO")
``` | output | 1 | 20,321 | 24 | 40,643 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO"). | instruction | 0 | 20,322 | 24 | 40,644 |
Tags: implementation
Correct Solution:
```
n = input()
max_x = None
max_y = None
arr = []
inputs = []
for i in range(int(n)):
_input = input()
inputs.append(_input)
for _input in inputs:
_input = _input.split(' ')
if _input[0] == '+':
x = int(_input[1])
y = int(_input[2])
if x < y:
temp = x
x = y
y = temp
if max_x is None or max_x < x:
max_x = x
if max_y is None or max_y < y:
max_y = y
if _input[0] == '?':
w = int(_input[1])
h = int(_input[2])
if w < h:
temp = w
w = h
h = temp
if max_x <= w and max_y <= h:
arr.append(f'YES')
else:
arr.append(f'NO')
for i in arr:
print(i)
``` | output | 1 | 20,322 | 24 | 40,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO"). | instruction | 0 | 20,323 | 24 | 40,646 |
Tags: implementation
Correct Solution:
```
x,y = 0,0
res = ''
n = int(input())
for _ in range(n):
q = [i for i in input().split()]
q[1] = int(q[1])
q[2] = int(q[2])
if q[0] == '+':
x = max(x, min(q[1], q[2]))
y = max(y, max(q[1], q[2]))
elif x <= min(q[1], q[2]) and y <= max(q[1], q[2]):
res += 'YES\n'
else:
res += 'NO\n'
print(res)
``` | output | 1 | 20,323 | 24 | 40,647 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO"). | instruction | 0 | 20,324 | 24 | 40,648 |
Tags: implementation
Correct Solution:
```
import io, os
input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline
maxw, maxh = 0,0
for _ in range(int(input())):
x = input().split()
w, h = map(int, x[1:])
if h > w: w,h = h,w
if x[0] == '+':
if w > maxw: maxw = w
if h > maxh: maxh = h
else:
print("YES" if maxw <= w and maxh <= h else "NO")
``` | output | 1 | 20,324 | 24 | 40,649 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO"). | instruction | 0 | 20,325 | 24 | 40,650 |
Tags: implementation
Correct Solution:
```
a=b=0
s=''
for f in range(int(input())):
i=input().split()
x=min(int(i[1]),int(i[2]))
y=max(int(i[1]),int(i[2]))
if i[0]=='?':
if x<a or y<b:s+='NO\n'
else:s+='YES\n'
else:
a,b=max(a,x),max(b,y)
print(s[:-1])
``` | output | 1 | 20,325 | 24 | 40,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO").
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
a = [list(map(str,input().split())) for _ in range(n)]
tate = 0
yoko = 0
for i in range(n):
if a[i][0] == "+":
b = [int(a[i][1]),int(a[i][2])]
b.sort()
if tate < b[0]:
tate = b[0]
if yoko < b[1]:
yoko = b[1]
elif a[i][0] == "?":
b = [int(a[i][1]),int(a[i][2])]
b.sort()
if tate <= b[0] and yoko <= b[1]:
print("YES")
else:
print("NO")
``` | instruction | 0 | 20,326 | 24 | 40,652 |
Yes | output | 1 | 20,326 | 24 | 40,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO").
Submitted Solution:
```
num = int(input())
log = []
for x in range(num):
log.append(input().split())
a = 0
b = min(int(log[0][2]),int(log[0][1]))
for y in log:
first = int(y[1])
second = int(y[2])
if y[0] == '+':
a = max(first,second,a)
temp = min(first,second)
b = max(temp,b)
continue
else:
if (first < a or second < b) and (first < b or second < a):
print('NO')
else:
print('Yes')
``` | instruction | 0 | 20,327 | 24 | 40,654 |
Yes | output | 1 | 20,327 | 24 | 40,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO").
Submitted Solution:
```
n=int(input())
s=''
maxx=0
maxy=0
for item in range(n):
flag=input().split()
a=int(flag[1])
b=int(flag[2])
if a>b:
a,b=b,a
if flag[0]=='+':
if a>maxx:
maxx=a
if b>maxy:
maxy=b
else:
if maxx<=a and maxy<=b:
s+='YES\n'
else:
s+='NO\n'
print(s)
``` | instruction | 0 | 20,328 | 24 | 40,656 |
Yes | output | 1 | 20,328 | 24 | 40,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO").
Submitted Solution:
```
import sys
import bisect
input=sys.stdin.readline
#t=int(input())
t=1
mod=10**9+7
for _ in range(t):
n=int(input())
#l,r,d=map(int,input().split())
#s=input()
#l=list(map(int,input().split()))
l=[]
for i in range(n):
x=input()
if x[0]=='+':
x=list(map(int,x[2:].split()))
if len(l)==0:
l.append([[x[0],x[1]],[x[1],x[0]]])
else:
l1=[]
maxi=max(l[-1][0][0],l[-1][1][0],max(x[0],x[1]))
mini=min(x[0],x[1])
mini=max(min(l[-1][0][0],l[-1][1][0]),mini)
l.append([[maxi,mini],[mini,maxi]])
else:
#print(l[-1])
x=list(map(int,x[2:].split()))
if (l[-1][0][0]<=x[0] and l[-1][0][1]<=x[1]) :
print("YES")
elif l[-1][1][0]<=x[0] and l[-1][1][1]<=x[1] :
print("YES")
else:
print("NO")
``` | instruction | 0 | 20,329 | 24 | 40,658 |
Yes | output | 1 | 20,329 | 24 | 40,659 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO").
Submitted Solution:
```
n = int(input())
a = []
prov = []
prov_const = -1
def check(ci , cj , m):
result = True
for i in range(m):
if ((ci >= a[i][0]) and (cj >= a[i][1] )) or ((ci >= a[i][1]) and (cj >= a[i][0])):
continue
else:
result = False
break
return result
for i in range(n):
s = [i for i in input().split()]
if s[0] == '+':
a.append([int(s[1]) , int(s[2])])
if s[0] == '?':
if prov_const >=0:
if (int(s[1])>=prov[prov_const][0] and int(s[2]) >= prov[prov_const][1]) or (int(s[2])>=prov[prov_const][0] and int(s[1]) >= prov[prov_const][1]) and prov[prov_const][2] == True:
print('YES')
l = True
elif (int(s[1])<=prov[prov_const][0] and int(s[2]) <= prov[prov_const][1]) and prov[prov_const][2] == False:
print('NO')
l = False
else:
l = check(int(s[1]) , int(s[2]) , len(a))
if l:
print('YES')
else:
print('NO')
else:
l = check(int(s[1]), int(s[2]), len(a))
if l:
print('YES')
else:
print('NO')
prov.append([int(s[1]) , int(s[2]) , l])
prov_const +=1
``` | instruction | 0 | 20,330 | 24 | 40,660 |
No | output | 1 | 20,330 | 24 | 40,661 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO").
Submitted Solution:
```
from sys import stdin , stdout
n = int(stdin.readline())
maxix , maxiy = 0 , 0
for _ in range(n):
s = [x for x in stdin.readline().split()]
s[1] , s[2] = max(s[1], s[2]) , min(s[1], s[2])
if s[0]=="+":
maxix = max(maxix, int(s[1]))
maxiy = max(maxiy, int(s[2]))
else:
ans='NO'
h , w = int(s[1]) , int(s[2])
if (maxix <= h and maxiy <=w):
ans='YES'
stdout.write(ans + "\n")
``` | instruction | 0 | 20,331 | 24 | 40,662 |
No | output | 1 | 20,331 | 24 | 40,663 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO").
Submitted Solution:
```
n = int(input())
stx = 0
sty = 0
for i in range(n):
t, x, y = input().split()
x = int(x)
y = int(y)
if x > y:
x,y=y,x
if t == '+':
stx = max(stx, x)
sty = max(sty, y)
else:
print('YNeos'[x >= stx and y >= sty::2])
``` | instruction | 0 | 20,332 | 24 | 40,664 |
No | output | 1 | 20,332 | 24 | 40,665 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.
Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).
A bill x Γ y fits into some wallet h Γ w if either x β€ h and y β€ w or y β€ h and x β€ w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.
Now you are asked to perform the queries of two types:
1. +~x~y β Polycarp earns a bill of size x Γ y;
2. ?~h~w β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Input
The first line contains a single integer n (2 β€ n β€ 5 β
10^5) β the number of queries.
Each of the next n lines contains a query of one of these two types:
1. +~x~y (1 β€ x, y β€ 10^9) β Polycarp earns a bill of size x Γ y;
2. ?~h~w (1 β€ h, w β€ 10^9) β Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h Γ w.
It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.
Output
For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.
Example
Input
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
Note
The queries of type 2 of the example:
1. Neither bill fits;
2. Both bills fit (just checking that you got that bills can overlap);
3. Both bills fit (both bills are actually the same);
4. All bills fit (too much of free space in a wallet is not a problem);
5. Only bill 1 Γ 5 fit (all the others don't, thus it's "NO").
Submitted Solution:
```
def f():
x = int(input()) ;final = list(); one = list(); two = list()
for a in range(x):
string = list(map(str,input().split()))
ch = string[0]; a = int(string[1]); b= int(string[2])
if ch == "+":
one += [a]
two += [b]
final += [a,b]
if ch == "?":
if a in one and b in two:
one.remove(a)
two.remove(b)
min_one = max(one)
min_two = max(two)
if a >= min_one and b >= min_two:
print("YES")
elif b>= min_one and a >= min_two:
print("YES")
else:
print("NO")
one += [a]
two += [b]
f()
``` | instruction | 0 | 20,333 | 24 | 40,666 |
No | output | 1 | 20,333 | 24 | 40,667 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21 | instruction | 0 | 20,452 | 24 | 40,904 |
Tags: binary search, data structures, greedy, implementation, math, sortings
Correct Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
#from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.buffer.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#sys.setrecursionlimit(100000)
#INF = float('inf')
mod = int(1e9)+7
#from decimal import Decimal
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
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 fix():
global sumL, cntL, sumDouble
while len(Double)<cntL:
temp=LF[-1]
Double.add(temp)
LF.remove(temp)
sumDouble+=temp
while len(Double)>cntL:
temp=Double[0]
Double.remove(temp)
LF.add(temp)
sumDouble-=temp
while Double and LF and Double[0]<LF[-1]:
temp1,temp2=Double[0],LF[-1]
LF.remove(temp2)
Double.remove(temp1)
LF.add(temp1)
Double.add(temp2)
sumDouble+=temp2-temp1
if sumDouble==sumL and cntL:
temp1=Double[0]
Double.remove(temp1)
if LF:
temp2=LF[-1]
LF.remove(temp2)
Double.add(temp2)
sumDouble+=temp2
LF.add(temp1)
sumDouble-=temp1
def add(tp,d):
global sumF,sumL, sumDouble, cntL
if not tp:
sumF+=d
else:
sumL+=d
cntL+=1
LF.add(d)
def remove(tp,d):
global sumF, sumL, sumDouble, cntL
if not tp:
sumF-=d
else:
sumL-=d
cntL-=1
if d in LF:
LF.remove(d)
else:
Double.remove(d)
sumDouble-=d
n=int(data())
sumL,sumF,sumDouble,cntL=0,0,0,0
LF=SortedList()
Double=SortedList()
for _ in range(n):
tp,d=mdata()
if d<0:
remove(tp,-d)
else:
add(tp,d)
fix()
print(sumDouble+sumL+sumF)
``` | output | 1 | 20,452 | 24 | 40,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21 | instruction | 0 | 20,453 | 24 | 40,906 |
Tags: binary search, data structures, greedy, implementation, math, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# 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()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
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))
# import heapq as hq
# import bisect as bs
# from collections import deque as dq
# from collections import defaultdict as dc
# from math import ceil,floor,sqrt
# from collections import Counter
spell = SortedList([0])
lightning = SortedList()
s,k = 0,-1
for _ in range(N()):
t,power = RL()
s+=power
if t==1:
if lightning:
spell.add(lightning[0])
if lightning[0]>spell[k]: s+=lightning[0]-spell[k]
if power>0:
lightning.add(power)
spell.add(power)
if power>spell[k]: s+=power-spell[k]
else:
lightning.discard(-power)
if -power>spell[k]: s-=-power-spell[k]
spell.discard(-power)
if lightning:
if lightning[0]>spell[k]: s-=lightning[0]-spell[k]
spell.discard(lightning[0])
else:
if power>0:
spell.add(power)
if power>spell[k]: s+=power-spell[k]
else:
if -power>spell[k]: s-=-power-spell[k]
spell.discard(-power)
k = max(k,-len(spell))
if -k>len(lightning)+1:
k+=1
s-=spell[k]
elif -k<len(lightning)+1 and spell[k]>0:
s+=spell[k]
k-=1
# print(spell,lightning,k,s)
print(s)
``` | output | 1 | 20,453 | 24 | 40,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21 | instruction | 0 | 20,454 | 24 | 40,908 |
Tags: binary search, data structures, greedy, implementation, math, sortings
Correct Solution:
```
from sys import stdin, stdout
# 1 5
# 0 10
# 1 -5
# 0 5
# 1 11
# 0 -10
#
# (5) => 5
# (5) 10 => 5 + 2*10
# 10 => 10
# 10 5 => 15
# 10 5 (11) => 11 + 2*10 + 5 = 36
# 5 (11) => 11 + 2*5 = 21
# 1-11 (sum, cnt)
# 1-5 6-11
# 1-2 2-5 6-8 9-11
#
class seg_node:
def __init__(self, l, r, c, v):
self.l = l
self.r = r
self.c = c
self.v = v
self.ln = None
self.rn = None
def seg_update(self, i, c, v):
if self.l == self.r:
self.c += c
self.v += v
return
m = (self.l + self.r) // 2
if i <= m:
if not self.ln:
self.ln = seg_node(self.l, m, 0, 0)
self.ln.seg_update(i, c, v)
else:
if not self.rn:
self.rn = seg_node(m+1, self.r, 0, 0)
self.rn.seg_update(i, c, v)
self.c += c
self.v += v
def seg_query_r(self, cnt):
if self.l == self.r:
if cnt >= self.c:
return [self.c, self.v]
else:
return [cnt, self.v * cnt // self.c]
if self.c <= cnt:
return [self.c, self.v]
r_a = [0, 0]
if self.rn:
r_a = self.rn.seg_query_r(cnt)
#print('cnt ' + str(cnt))
#print('l ' + str(self.l))
#print('r ' + str(self.r))
#print(r_a)
#print('~~~~~~~~~~')
if r_a[0] >= cnt:
return r_a
l_a = [0, 0]
if self.ln:
l_a = self.ln.seg_query_r(cnt - r_a[0])
res = [r_a[0] + l_a[0], r_a[1] + l_a[1]]
#print(r_a)
#print(l_a)
#print(res)
return res
class seg_minnode:
def __init__(self, l, r):
self.l = l
self.r = r
self.c = 0
self.v = 10**10
self.ln = None
self.rn = None
def seg_update(self, i, c, v):
if self.l == self.r:
self.c += c
self.v = v if self.c > 0 else 10**10
return self.v
m = (self.l + self.r) // 2
lv = 10**10 if not self.ln else self.ln.v
rv = 10**10 if not self.rn else self.rn.v
if i <= m:
if not self.ln:
self.ln = seg_minnode(self.l, m)
lv = self.ln.seg_update(i, c, v)
else:
if not self.rn:
self.rn = seg_minnode(m + 1, self.r)
rv = self.rn.seg_update(i, c, v)
self.v = min(lv, rv)
return self.v
def seg_query(self):
return self.v
def two_types_of_spells(n, s, tpd_a):
# 5, 10, 15 => 0, 1, 2
dic = {}
ls = list(s)
ls.sort()
for i in range(len(ls)):
dic[ls[i]] = i
#print(dic)
seg_root = seg_node(0, len(ls)-1, 0, 0)
seg_minroot = seg_minnode(0, len(ls)-1)
rsum = 0
lcnt = 0
ans = []
for tpd in tpd_a:
i = dic[abs(tpd[1])]
c = 1 if tpd[1] > 0 else -1
v = tpd[1]
#print(i)
#print(c)
#print(v)
rsum += tpd[1]
#print(rsum)
if tpd[0] == 1:
if tpd[1] > 0:
lcnt += 1
else:
lcnt -= 1
i = dic[abs(tpd[1])]
c = 1 if tpd[1] > 0 else -1
seg_minroot.seg_update(i, c, abs(v))
#print(c)
#print(seg_minroot.v)
seg_root.seg_update(i, c, v)
#print(seg_root.l)
#print(seg_root.r)
#print(seg_root.c)
#print(seg_root.v)
if lcnt < 1:
ans.append(rsum)
continue
# remove minimum lighting
minV = seg_minroot.seg_query()
#print(minV)
seg_root.seg_update(dic[minV], -1, -minV)
#print(seg_root.c)
#print(seg_root.v)
cnt, v = seg_root.seg_query_r(lcnt)
# add minimum lighting
seg_root.seg_update(dic[minV], 1, minV)
ans.append(rsum + v)
#print(v)
#print('-----------')
return ans
n = int(stdin.readline())
tpd_a = []
s = set()
for _ in range(n):
tp, d = map(int, stdin.readline().split())
tpd_a.append([tp, d])
s.add(abs(d))
ans = two_types_of_spells(n, s, tpd_a)
for a in ans:
stdout.write(str(a) + '\n')
``` | output | 1 | 20,454 | 24 | 40,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21 | instruction | 0 | 20,455 | 24 | 40,910 |
Tags: binary search, data structures, greedy, implementation, math, sortings
Correct Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
# Based on https://raw.githubusercontent.com/cheran-senthil/PyRival/master/pyrival/data_structures/SortedList.py
# Modified to do range sum queries
class SortedListWithSum:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._sum = sum(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._mins = [_list[0] for _list in _lists]
self._list_lens = [len(_list) for _list in _lists]
self._fen_tree = []
self._list_sums = [sum(_list) for _list in _lists]
self._fen_tree_sum = []
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._fen_tree_sum[:] = self._list_sums
_fen_tree_sum = self._fen_tree_sum
for i in range(len(_fen_tree_sum)):
if i | i + 1 < len(_fen_tree_sum):
_fen_tree_sum[i | i + 1] += _fen_tree_sum[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_update_sum(self, index, value):
"""Update `fen_tree2[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree_sum
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_query_sum(self, end):
"""Return `sum(_fen_tree_sum[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree_sum
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
_list_sums = self._list_sums
value = _lists[pos][idx]
self._len -= 1
self._sum -= value
self._fen_update(pos, -1)
self._fen_update_sum(pos, -value)
del _lists[pos][idx]
_list_lens[pos] -= 1
_list_sums[pos] -= value
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _list_sums[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
_list_sums = self._list_sums
self._len += 1
self._sum += value
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
self._fen_update_sum(pos, value)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_list_sums[pos] += value
_mins[pos] = _list[0]
if _load + _load < len(_list):
back = _list[_load:]
old_len = _list_lens[pos]
old_sum = _list_sums[pos]
new_len_front = _load
new_len_back = old_len - new_len_front
new_sum_back = sum(back)
new_sum_front = old_sum - new_sum_back
_lists.insert(pos + 1, back)
_list_lens.insert(pos + 1, new_len_back)
_list_sums.insert(pos + 1, new_sum_back)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = new_len_front
_list_sums[pos] = new_sum_front
del _list[_load:]
# assert len(_lists[pos]) == _list_lens[pos]
# assert len(_lists[pos + 1]) == _list_lens[pos + 1]
# assert sum(_lists[pos]) == _list_sums[pos]
# assert sum(_lists[pos + 1]) == _list_sums[pos + 1]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
_list_sums.append(value)
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 query(self, i, j):
if i == j:
return 0
pos1, idx1 = self._fen_findkth(self._len + i if i < 0 else i)
pos2, idx2 = self._fen_findkth(self._len + j if j < 0 else j)
return (
sum(self._lists[pos1][idx1:])
+ (self._fen_query_sum(pos2) - self._fen_query_sum(pos1 + 1))
+ sum(self._lists[pos2][:idx2])
)
def sum(self):
return self._sum
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
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 solve(N, queries):
L = SortedList()
F = SortedList()
sumL = 0
sumF = 0
# Stores best candidates for doubling which is everything except for the smallest lightning
# Can only double at most len(L) spells
cand = SortedListWithSum()
# Store smallest lightning separately
smallestL = None
def add(d, tp):
nonlocal sumL, sumF, smallestL
toAdd = d
if tp == 0:
F.add(d)
sumF += d
else:
if not L or L[0] > d:
# adding new smallest lightning, bump old smallestL into candidate list
toAdd = smallestL
smallestL = d
L.add(d)
sumL += d
if toAdd is not None:
cand.add(toAdd)
def remove(d, tp):
nonlocal sumL, sumF, smallestL
toRemove = d
if tp == 0:
F.remove(d)
sumF -= d
else:
L.remove(d)
sumL -= d
smallestL = None if not L else L[0]
if not L or smallestL > d:
# removed old smallest lightning, pull new smallestL from candidate list
toRemove = smallestL
if toRemove is not None:
cand.remove(toRemove)
ans = []
for tp, d in queries:
if d > 0:
# learn
add(d, tp)
else:
# unlearn
remove(-d, tp)
ans.append(
cand.query(max(0, len(cand) - len(L)), len(cand)) + sumL + sumF
)
return "\n".join(map(str, ans))
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = [int(x) for x in input().split()]
queries = ((int(x) for x in input().split()) for i in range(N))
ans = solve(N, queries)
print(ans)
``` | output | 1 | 20,455 | 24 | 40,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21 | instruction | 0 | 20,456 | 24 | 40,912 |
Tags: binary search, data structures, greedy, implementation, math, sortings
Correct Solution:
```
class BalancingTree:
def __init__(self, n):
self.N = n
self.root = self.node(1<<n, 1<<n)
def debug(self):
def debug_info(nd_):
return (nd_.value - 1, nd_.pivot , nd_.left.value - 1 if nd_.left else -1, nd_.right.value - 1 if nd_.right else -1,nd_.cnt)
def debug_node(nd):
re = []
if nd.left:
re += debug_node(nd.left)
if nd.value: re.append(debug_info(nd))
if nd.right:
re += debug_node(nd.right)
return re
print("Debug - root =", self.root.value - 1, debug_node(self.root)[:50])
def append(self, v):
v += 1
nd = self.root
while True:
if v == nd.value:
return 0
else:
nd.cnt+=1
nd.sum+=v-1
mi, ma = min(v, nd.value), max(v, nd.value)
if mi < nd.pivot:
nd.value = ma
if nd.left:
nd = nd.left
v = mi
else:
p = nd.pivot
nd.left = self.node(mi, p - (p&-p)//2)
break
else:
nd.value = mi
if nd.right:
nd = nd.right
v = ma
else:
p = nd.pivot
nd.right = self.node(ma, p + (p&-p)//2)
break
def kth(self,k):
cnt=k
nd=self.root
while True:
if nd.left:
if nd.left.cnt<k:
k-=nd.left.cnt+1
if nd.right:
nd=nd.right
else:
raise IndexError("BalancingTree doesn't hold kth number")
elif nd.left.cnt==k:
return nd.value-1
else:
nd=nd.left
else:
if k==0:
return nd.value-1
if nd.right:
k-=1
nd=nd.right
else:
raise IndexError("BalancingTree doesn't hold kth number")
def kth_sum(self,k):
if k==-1:
return 0
cnt=k
res_sum=0
nd=self.root
while True:
if nd.left:
if nd.left.cnt<k:
k-=nd.left.cnt+1
res_sum+=nd.left.sum+nd.value-1
if nd.right:
nd=nd.right
else:
raise IndexError("BalancingTree doesn't hold kth number")
elif nd.left.cnt==k:
res_sum+=nd.left.sum+nd.value-1
return res_sum
else:
nd=nd.left
else:
if k==0:
return res_sum+nd.value-1
if nd.right:
k-=1
res_sum+=nd.value-1
nd=nd.right
else:
print(cnt,self.size,nd.value-1,nd.right)
self.debug()
raise IndexError("BalancingTree doesn't hold kth number")
def kth_sum_big(self,k):
res_sum=self.sum
if self.size>k:
res_sum-=self.kth_sum(self.size-k-2)
return res_sum
else:
raise IndexError("BalancingTree doesn't hold kth number")
def leftmost(self, nd):
if nd.left: return self.leftmost(nd.left)
return nd
def rightmost(self, nd):
if nd.right: return self.rightmost(nd.right)
return nd
def find_l(self, v):
v += 1
nd = self.root
prev = 0
if nd.value < v: prev = nd.value
while True:
if v <= nd.value:
if nd.left:
nd = nd.left
else:
return prev - 1
else:
prev = nd.value
if nd.right:
nd = nd.right
else:
return prev - 1
def find_r(self, v):
v += 1
nd = self.root
prev = 0
if nd.value > v: prev = nd.value
while True:
if v < nd.value:
prev = nd.value
if nd.left:
nd = nd.left
else:
return prev - 1
else:
if nd.right:
nd = nd.right
else:
return prev - 1
@property
def max(self):
if self.size:
return self.find_l((1<<self.N)-1)
return 0
@property
def min(self):
if self.size:
return self.find_r(-1)
return 0
@property
def sum(self):
return self.root.sum-self.root.value+1
@property
def size(self):
return self.root.cnt-1
def delete(self, v, nd = None, prev = None):
v += 1
if not nd: nd = self.root
if not prev: prev = nd
while v != nd.value:
prev = nd
nd.cnt-=1
nd.sum-=v-1
if v <= nd.value:
if nd.left:
nd = nd.left
else:
return
else:
if nd.right:
nd = nd.right
else:
return
nd.cnt-=1
nd.sum-=v-1
if (not nd.left) and (not nd.right):
if not prev.left:
prev.right=None
elif not prev.right:
prev.left=None
else:
if nd.pivot==prev.left.pivot:
prev.left=None
else:
prev.right=None
elif nd.right:
nd.value = self.leftmost(nd.right).value
self.delete(nd.value - 1, nd.right, nd)
else:
nd.value = self.rightmost(nd.left).value
self.delete(nd.value - 1, nd.left, nd)
def __contains__(self, v: int) -> bool:
return self.find_r(v - 1) == v
def __len__(self):
return self.size
class node:
def __init__(self, v, p):
self.value = v
self.pivot = p
self.left = None
self.right = None
self.cnt=1
self.sum=v-1
import sys
input=sys.stdin.readline
n=int(input())
xybst=BalancingTree(30)
S=0
split_bst=[BalancingTree(30),BalancingTree(30)]
for _ in range(n):
t,d=map(int,input().split())
if d<0:
split_bst[t].delete(abs(d))
xybst.delete(abs(d))
else:
split_bst[t].append(abs(d))
xybst.append(abs(d))
S+=d
x,y=len(split_bst[0]),len(split_bst[1])
tmp,tmpy=xybst.kth_sum_big(y-1),split_bst[1].kth_sum_big(y-1)
if tmp==tmpy and y:
print(S+tmp-split_bst[1].min+split_bst[0].max)
else:
print(S+tmp)
``` | output | 1 | 20,456 | 24 | 40,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21 | instruction | 0 | 20,457 | 24 | 40,914 |
Tags: binary search, data structures, greedy, implementation, math, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# 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()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
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))
# import heapq as hq
# import bisect as bs
# from collections import deque as dq
# from collections import defaultdict as dc
# from math import ceil,floor,sqrt
# from collections import Counter
spell = SortedList([0])
lightning = SortedList()
data = [map(int,line.split()) for line in sys.stdin.readlines()]
n = data[0].__next__()
s,k = 0,-1
for i in range(1,n+1):
t,power = data[i]
s+=power
if t==1:
if lightning:
spell.add(lightning[0])
if lightning[0]>spell[k]: s+=lightning[0]-spell[k]
if power>0:
lightning.add(power)
spell.add(power)
if power>spell[k]: s+=power-spell[k]
else:
lightning.discard(-power)
if -power>spell[k]: s-=-power-spell[k]
spell.discard(-power)
if lightning:
if lightning[0]>spell[k]: s-=lightning[0]-spell[k]
spell.discard(lightning[0])
else:
if power>0:
spell.add(power)
if power>spell[k]: s+=power-spell[k]
else:
if -power>spell[k]: s-=-power-spell[k]
spell.discard(-power)
k = max(k,-len(spell))
if -k>len(lightning)+1:
k+=1
s-=spell[k]
elif -k<len(lightning)+1 and spell[k]>0:
s+=spell[k]
k-=1
# print(spell,lightning,k,s)
print(s)
``` | output | 1 | 20,457 | 24 | 40,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21 | instruction | 0 | 20,458 | 24 | 40,916 |
Tags: binary search, data structures, greedy, implementation, math, sortings
Correct Solution:
```
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
class SegmentTree:
def __init__(self, a):
# Operator
self.op = lambda a, b : a + b
# Identity element
self.e = 0
self.n = len(a)
self.lv = (self.n - 1).bit_length()
self.size = 2**self.lv
self.data = [self.e] * (2*self.size - 1)
# Bisect checking function
self._check = lambda x, acc : acc >= x
self._acc = self.e
self.initialize(a)
# Initialize data
def initialize(self, a):
for i in range(self.n):
self.data[self.size + i - 1] = a[i]
for i in range(self.size-2, -1, -1):
self.data[i] = self.op(self.data[i*2 + 1], self.data[i*2 + 2])
# Update ak as x (0-indexed)
def update(self, k, x):
k += self.size - 1
self.data[k] = x
while k > 0:
k = (k - 1) // 2
self.data[k] = self.op(self.data[2*k+1], self.data[2*k+2])
# Min value in [l, r) (0-indexed)
def fold(self, l, r):
L = l + self.size; R = r + self.size
s = self.e
while L < R:
if R & 1:
R -= 1
s = self.op(s, self.data[R-1])
if L & 1:
s = self.op(s, self.data[L-1])
L += 1
L >>= 1; R >>= 1
return s
def _bisect_forward(self, x, start, k):
# When segment-k is at the bottom, accumulate and return.
if k >= self.size - 1:
self._acc = self.op(self._acc, self.data[k])
if self._check(x, self._acc):
return k - (self.size - 1)
else:
return -1
width = 2**(self.lv - (k+1).bit_length() + 1)
mid = (k+1) * width + width // 2 - self.size
# When left-child isn't in range, just look at right-child.
if mid <= start:
return self._bisect_forward(x, start, 2*k + 2)
# When segment-k is in range and has no answer in it, accumulate and return -1
tmp_acc = self.op(self._acc, self.data[k])
if start <= mid - width // 2 and not self._check(x, tmp_acc):
self._acc = tmp_acc
return -1
# Check left-child then right-child
vl = self._bisect_forward(x, start, 2*k + 1)
if vl != -1:
return vl
return self._bisect_forward(x, start, 2*k + 2)
# Returns min index s.t. start <= index and satisfy check(data[start:idx)) = True
def bisect_forward(self, x, start=None):
if start:
ret = self._bisect_forward(x, start, 0)
else:
ret = self._bisect_forward(x, 0, 0)
self._acc = self.e
return ret
def _bisect_backward(self, x, start, k):
# When segment-k is at the bottom, accumulate and return.
if k >= self.size - 1:
self._acc = self.op(self._acc, self.data[k])
if self._check(x, self._acc):
return k - (self.size - 1)
else:
return -1
width = 2**(self.lv - (k+1).bit_length() + 1)
mid = (k+1) * width + width // 2 - self.size
# When right-child isn't in range, just look at right-child.
if mid >= start:
return self._bisect_backward(x, start, 2*k + 1)
# When segment-k is in range and has no answer in it, accumulate and return -1
tmp_acc = self.op(self._acc, self.data[k])
if start > mid + width // 2 and not self._check(x, tmp_acc):
self._acc = tmp_acc
return -1
# Check right-child then left-child
vl = self._bisect_backward(x, start, 2*k + 2)
if vl != -1:
return vl
return self._bisect_backward(x, start, 2*k + 1)
# Returns max index s.t. index < start and satisfy check(data[idx:start)) = True
def bisect_backward(self, x, start=None):
if start:
ret = self._bisect_backward(x, start, 0)
else:
ret = self._bisect_backward(x, self.n, 0)
self._acc = self.e
return ret
n = int(input())
query = []
seen = set([0])
for _ in range(n):
kind, val = map(int, input().split())
query.append((kind, val))
if val > 0:
seen.add(val)
unique = list(seen)
unique.sort()
comp = {val: i for i, val in enumerate(unique)}
decomp = {i: val for i, val in enumerate(unique)}
decopm = {}
nn = len(comp)
base = [0] * nn
STfire = SegmentTree(base)
STnum = SegmentTree(base)
STval = SegmentTree(base)
tnum = 0
fnum = 0
spell = 0
total = 0
for kind, val in query:
cd = comp[abs(val)]
if val > 0:
STval.update(cd, val)
STnum.update(cd, 1)
total += val
if kind == 1:
tnum += 1
else:
STfire.update(cd, 1)
fnum += 1
else:
total += val
STval.update(cd, 0)
STnum.update(cd, 0)
if kind == 1:
tnum -= 1
else:
STfire.update(cd, 0)
fnum -= 1
spell = tnum + fnum
if fnum == 0:
fid = -1
else:
fid = STfire.bisect_forward(fnum)
l = STnum.bisect_forward(spell - tnum)
if tnum == 0:
print(total)
continue
if fid >= l + 1:
double_total = STval.fold(l + 1, nn)
print(total + double_total)
else:
l = STnum.bisect_forward(spell - tnum + 1)
double_total = STval.fold(l + 1, nn)
if fnum > 0:
print(total + double_total + decomp[fid])
else:
print(total + double_total)
``` | output | 1 | 20,458 | 24 | 40,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21 | instruction | 0 | 20,459 | 24 | 40,918 |
Tags: binary search, data structures, greedy, implementation, math, sortings
Correct Solution:
```
from math import inf, log2
class SegmentTree:
def __init__(self, array, func=max):
self.n = len(array)
self.size = 2**(int(log2(self.n-1))+1) if self.n != 1 else 1
self.func = func
self.default = 0 if self.func != min else inf
self.data = [self.default] * (2 * self.size)
self.process(array)
def process(self, array):
self.data[self.size : self.size+self.n] = array
for i in range(self.size-1, -1, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i+1])
def query(self, alpha, omega):
"""Returns the result of function over the range (inclusive)!"""
if alpha == omega:
return self.data[alpha + self.size]
res = self.default
alpha += self.size
omega += self.size + 1
while alpha < omega:
if alpha & 1:
res = self.func(res, self.data[alpha])
alpha += 1
if omega & 1:
omega -= 1
res = self.func(res, self.data[omega])
alpha >>= 1
omega >>= 1
return res
def update(self, index, value):
"""Updates the element at index to given value!"""
index += self.size
self.data[index] = value
index >>= 1
while index:
self.data[index] = self.func(self.data[2*index], self.data[2*index+1])
index >>= 1
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
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))
# ------------------- fast io --------------------
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")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if not True else 1):
n = int(input())
lightning, fire = 0, 0
slf = SortedList([])
sll = SortedList([])
sl = SortedList([])
queries = []
oof = []
for i in range(n):
tp, d = map(int, input().split())
queries += [[tp, d]]
oof += [abs(d)]
oof = sorted(list(set(oof)))
high = len(oof) + 10
st = SegmentTree([0]*high, func=lambda a,b:a+b)
di = {}
for i in range(len(oof)):
di[oof[i]] = i
for tp, d in queries:
if not tp:
# fire
fire += d
if d > 0:
slf.add(d)
sl.add(d)
st.update(di[d], d)
else:
slf.remove(-d)
sl.remove(-d)
st.update(di[-d], 0)
else:
# lightning
lightning += d
if d > 0:
sll.add(d)
sl.add(d)
st.update(di[d], d)
else:
sll.remove(-d)
sl.remove(-d)
st.update(di[-d], 0)
if sll.__len__() == 0:
print(fire + lightning)
continue
least = sl.__getitem__(sl.__len__() - sll.__len__())
if fire and slf.__getitem__(slf.__len__()-1) >= least:
print(least + st.query(di[least]+1, high-1)*2 + st.query(0, di[least]))
else:
if fire:
firemax = slf.__getitem__(slf.__len__()-1)
print(least + st.query(di[least]+1, high-1)*2 + firemax*2 + st.query(0, di[firemax]-1))
else:
print(least + st.query(di[least] + 1, high - 1) * 2)
``` | output | 1 | 20,459 | 24 | 40,919 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21
Submitted Solution:
```
import bisect
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
class TreeSet(object):
"""
Binary-tree set like java Treeset.
Duplicate elements will not be added.
When added new element, TreeSet will be sorted automatically.
"""
def __init__(self, elements):
self._treeset = []
self.addAll(elements)
def addAll(self, elements):
for element in elements:
if element in self: continue
self.add(element)
def add(self, element):
if element not in self:
bisect.insort(self._treeset, element)
def ceiling(self, e):
index = bisect.bisect_right(self._treeset, e)
if self[index - 1] == e:
return e
return self._treeset[bisect.bisect_right(self._treeset, e)]
def floor(self, e):
index = bisect.bisect_left(self._treeset, e)
if self[index] == e:
return e
else:
return self._treeset[bisect.bisect_left(self._treeset, e) - 1]
def __getitem__(self, num):
return self._treeset[num]
def __len__(self):
return len(self._treeset)
def clear(self):
"""
Delete all elements in TreeSet.
"""
self._treeset = []
def clone(self):
"""
Return shallow copy of self.
"""
return TreeSet(self._treeset)
def remove(self, element):
"""
Remove element if element in TreeSet.
"""
try:
self._treeset.remove(element)
except ValueError:
return False
return True
def __iter__(self):
"""
Do ascending iteration for TreeSet
"""
for element in self._treeset:
yield element
def pop(self, index):
return self._treeset.pop(index)
def __str__(self):
return str(self._treeset)
def __eq__(self, target):
if isinstance(target, TreeSet):
return self._treeset == target.treeset
elif isinstance(target, list):
return self._treeset == target
def __contains__(self, e):
"""
Fast attribution judgment by bisect
"""
try:
return e == self._treeset[bisect.bisect_left(self._treeset, e)]
except:
return False
n = int(input())
MAX_VALUE = int(1e9+1)
ts = TreeSet([-MAX_VALUE, MAX_VALUE])
info = {}
cntL = 0
cntL2 = 0
min2 = MAX_VALUE
sum1 = 0
sum2 = 0
for _ in range(n):
type, power = list(map(int, input().split()))
if power>0:
ts.add(power)
info[power] = type
if min2 == ts[len(ts) - cntL-1]:
sum1 += power
if type == 1:
cntL += 1
min2 = ts[len(ts) - cntL - 1]
sum2 += min2
sum1 -= min2
cntL2 += info[min2]
else:
sum2 += power
cntL2 += info[power]
if type == 0:
sum2 -= min2
sum1 += min2
cntL2 -= info.get(min2, 0)
# min2 = ts[len(ts) - cntL - 1]
else:
cntL += 1
else:
power = abs(power)
ts.remove(power)
if min2 == ts[len(ts) - cntL - 1]:
sum1 -= power
if type == 1:
sum2 -= min2
sum1 += min2
cntL2 -= info.get(min2, 0)
cntL -= 1
# min2 = ts[len(ts) - cntL - 1]
else:
sum2 -= power
cntL2 -= info[power]
if type == 0:
min2 = ts[len(ts) - cntL - 1]
sum2 += min2
sum1 -= min2
cntL2 += info[min2]
else:
cntL -= 1
min2 = ts[len(ts) - cntL - 1]
if cntL2 < cntL or cntL == 0:
ans = 2*sum2 + sum1
else:
if len(ts) - cntL - 2 > 0:
max1 = ts[len(ts) - cntL - 2]
else:
max1 = 0
ans = 2*sum2 - min2 + sum1 + max1
print(ans)
``` | instruction | 0 | 20,460 | 24 | 40,920 |
Yes | output | 1 | 20,460 | 24 | 40,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21
Submitted Solution:
```
class BalancingTree:
def __init__(self, n):
self.N = n
self.root = self.node(1<<n, 1<<n)
def debug(self):
def debug_info(nd_):
return (nd_.value - 1, nd_.pivot , nd_.left.value - 1 if nd_.left else -1, nd_.right.value - 1 if nd_.right else -1,nd_.cnt)
def debug_node(nd):
re = []
if nd.left:
re += debug_node(nd.left)
if nd.value: re.append(debug_info(nd))
if nd.right:
re += debug_node(nd.right)
return re
print("Debug - root =", self.root.value - 1, debug_node(self.root)[:50])
def append(self, v):
v += 1
nd = self.root
while True:
if v == nd.value:
return 0
else:
nd.cnt+=1
nd.sum+=v-1
mi, ma = min(v, nd.value), max(v, nd.value)
if mi < nd.pivot:
nd.value = ma
if nd.left:
nd = nd.left
v = mi
else:
p = nd.pivot
nd.left = self.node(mi, p - (p&-p)//2)
break
else:
nd.value = mi
if nd.right:
nd = nd.right
v = ma
else:
p = nd.pivot
nd.right = self.node(ma, p + (p&-p)//2)
break
def kth(self,k):
cnt=k
nd=self.root
while True:
if nd.left:
if nd.left.cnt<k:
k-=nd.left.cnt+1
if nd.right:
nd=nd.right
else:
raise IndexError("BalancingTree doesn't hold kth number")
elif nd.left.cnt==k:
return nd.value-1
else:
nd=nd.left
else:
if k==0:
return nd.value-1
if nd.right:
k-=1
nd=nd.right
else:
raise IndexError("BalancingTree doesn't hold kth number")
def kth_sum(self,k):
if k==-1:
return 0
cnt=k
res_sum=0
nd=self.root
while True:
if nd.left:
if nd.left.cnt<k:
k-=nd.left.cnt+1
res_sum+=nd.left.sum+nd.value-1
if nd.right:
nd=nd.right
else:
raise IndexError("BalancingTree doesn't hold kth number")
elif nd.left.cnt==k:
res_sum+=nd.left.sum+nd.value-1
return res_sum
else:
nd=nd.left
else:
if k==0:
return res_sum+nd.value-1
if nd.right:
k-=1
res_sum+=nd.value-1
nd=nd.right
else:
print(cnt,self.size,nd.value-1,nd.right)
self.debug()
raise IndexError("BalancingTree doesn't hold kth number")
def kth_sum_big(self,k):
res_sum=self.sum
if self.size>k:
res_sum-=self.kth_sum(self.size-k-2)
return res_sum
else:
raise IndexError("BalancingTree doesn't hold kth number")
def leftmost(self, nd):
if nd.left: return self.leftmost(nd.left)
return nd
def rightmost(self, nd):
if nd.right: return self.rightmost(nd.right)
return nd
def find_l(self, v):
v += 1
nd = self.root
prev = 0
if nd.value < v: prev = nd.value
while True:
if v <= nd.value:
if nd.left:
nd = nd.left
else:
return prev - 1
else:
prev = nd.value
if nd.right:
nd = nd.right
else:
return prev - 1
def find_r(self, v):
v += 1
nd = self.root
prev = 0
if nd.value > v: prev = nd.value
while True:
if v < nd.value:
prev = nd.value
if nd.left:
nd = nd.left
else:
return prev - 1
else:
if nd.right:
nd = nd.right
else:
return prev - 1
@property
def max(self):
return self.find_l((1<<self.N)-1)
@property
def min(self):
return self.find_r(-1)
@property
def sum(self):
return self.root.sum-self.root.value+1
@property
def size(self):
return self.root.cnt-1
def delete(self, v, nd = None, prev = None):
v += 1
if not nd: nd = self.root
if not prev: prev = nd
while v != nd.value:
prev = nd
nd.cnt-=1
nd.sum-=v-1
if v <= nd.value:
if nd.left:
nd = nd.left
else:
return
else:
if nd.right:
nd = nd.right
else:
return
nd.cnt-=1
nd.sum-=v-1
if (not nd.left) and (not nd.right):
if not prev.left:
prev.right=None
elif not prev.right:
prev.left=None
else:
if nd.pivot==prev.left.pivot:
prev.left=None
else:
prev.right=None
elif nd.right:
nd.value = self.leftmost(nd.right).value
self.delete(nd.value - 1, nd.right, nd)
else:
nd.value = self.rightmost(nd.left).value
self.delete(nd.value - 1, nd.left, nd)
def __contains__(self, v: int) -> bool:
return self.find_r(v - 1) == v
class node:
def __init__(self, v, p):
self.value = v
self.pivot = p
self.left = None
self.right = None
self.cnt=1
self.sum=v-1
import sys
input=sys.stdin.readline
n=int(input())
xybst=BalancingTree(30)
xbst=BalancingTree(30)
ybst=BalancingTree(30)
x,y=0,0
S=0
for _ in range(n):
t,d=map(int,input().split())
if d<0:
if t==0:
xbst.delete(abs(d))
x-=1
else:
ybst.delete(abs(d))
y-=1
xybst.delete(abs(d))
else:
if t==0:
xbst.append(d)
x+=1
else:
ybst.append(d)
y+=1
xybst.append(abs(d))
S+=d
if x==0:
if y==0:
print(0)
else:
print(2*S-ybst.min)
else:
if y==0:
print(S)
else:
tmp,tmpy=xybst.kth_sum_big(y-1),ybst.kth_sum_big(y-1)
if tmp==tmpy:
print(S+tmp-ybst.min+xbst.max)
else:
print(S+tmp)
``` | instruction | 0 | 20,461 | 24 | 40,922 |
Yes | output | 1 | 20,461 | 24 | 40,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21
Submitted Solution:
```
import sys, math
import io, os
data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
#from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
#def data(): return sys.stdin.buffer.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#sys.setrecursionlimit(100000)
#INF = float('inf')
mod = int(1e9)+7
#from decimal import Decimal
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
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 fix():
global sumL, cntL, sumDouble
while len(Double)<cntL:
temp=LF[-1]
Double.add(temp)
LF.remove(temp)
sumDouble+=temp
while len(Double)>cntL:
temp=Double[0]
Double.remove(temp)
LF.add(temp)
sumDouble-=temp
while Double and LF and Double[0]<LF[-1]:
temp1,temp2=Double[0],LF[-1]
LF.remove(temp2)
Double.remove(temp1)
LF.add(temp1)
Double.add(temp2)
sumDouble+=temp2-temp1
if sumDouble==sumL and cntL:
temp1=Double[0]
Double.remove(temp1)
if LF:
temp2=LF[-1]
LF.remove(temp2)
Double.add(temp2)
sumDouble+=temp2
LF.add(temp1)
sumDouble-=temp1
def add(tp,d):
global sumF,sumL, sumDouble, cntL
if not tp:
sumF+=d
else:
sumL+=d
cntL+=1
LF.add(d)
def remove(tp,d):
global sumF, sumL, sumDouble, cntL
if not tp:
sumF-=d
else:
sumL-=d
cntL-=1
if d in LF:
LF.remove(d)
else:
Double.remove(d)
sumDouble-=d
n=int(data())
sumL,sumF,sumDouble,cntL=0,0,0,0
LF=SortedList()
Double=SortedList()
for _ in range(n):
tp,d=mdata()
if d<0:
remove(tp,-d)
else:
add(tp,d)
fix()
out(sumDouble+sumL+sumF)
``` | instruction | 0 | 20,462 | 24 | 40,924 |
Yes | output | 1 | 20,462 | 24 | 40,925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
class fenwick:
def __init__(self, n):
self.mem = [0]*(n+1)
def get(self, u):
return self.psum(u) - self.psum(u-1)
def add(self, u, val):
while u <= n:
self.mem[u] += val
u += (u & -u)
def psum(self, u):
sm = 0
while u > 0:
sm += self.mem[u]
u -= (u & -u)
return sm
def pos(self, val):
l, r = 0, n+1
while l < r:
m = (l+r)//2
if self.psum(m) < val: l = m+1
else: r = m
return l
n, q = int(input()), []
for _ in range(n):
ligt, power = map(int, input().split())
q.append((power, ligt))
p2o = {}
for i, (power, _) in enumerate(sorted(q, reverse=True)):
if power > 0: p2o[power] = i+1
res, nspell, nfire = [], 0, 0
frcc, spcc, pwcc = fenwick(n), fenwick(n), fenwick(n)
for power, ligt in q:
nspell += 1 if power > 0 else -1
if not ligt: nfire += 1 if power > 0 else -1
nligt = nspell-nfire
order = p2o[abs(power)]
if not ligt: frcc.add(order, 1 if power > 0 else -1)
spcc.add(order, 1 if power > 0 else -1)
pwcc.add(order, power)
sm = 0
if nfire == 0:
sm = pwcc.psum(n) + pwcc.psum(spcc.pos(nligt-1))
elif nligt == 0:
sm = pwcc.psum(n)
else:
p = spcc.pos(nligt)
if frcc.psum(p):
sm = pwcc.psum(n) + pwcc.psum(p)
else:
sm = pwcc.psum(n) + pwcc.psum(p-1) + pwcc.get(frcc.pos(1))
res.append(sm)
print('\n'.join(map(str, res)))
``` | instruction | 0 | 20,463 | 24 | 40,926 |
Yes | output | 1 | 20,463 | 24 | 40,927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21
Submitted Solution:
```
x = {1:[],0:[]}
for _ in range(int(input())):
tp, d = map(int,input().split())
if d<0:
x[tp] = list(filter(lambda a: a!=(-1*d), x[tp]))
else:
x[tp].append(d)
if len(x[1]) == 0:
print(sum(x[0]))
elif len(x[1]) == 1:
if len(x[0])==0:
print(x[1][0])
elif len(x[0])==1:
print(x[1][0] + 2*x[0][0])
else:
x[0].sort(reverse=True)
print(x[1][0] + 2*x[0][0] + sum(x[0][1:len(x[0])]))
else:
x[0].sort(reverse = True)
x[1].sort()
if len(x[0])==0:
print(x[1][0]+ 2*sum(x[1][1:len(x[1])]))
elif len(x[0])==1:
print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0])
else:
x[0].sort(reverse = True)
print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0] + sum(x[0][1:len(x[0])]))
``` | instruction | 0 | 20,464 | 24 | 40,928 |
No | output | 1 | 20,464 | 24 | 40,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21
Submitted Solution:
```
x = {1:[],0:[]}
for _ in range(int(input())):
tp, d = map(int,input().split())
if d<0:
x[tp] = list(filter(lambda a: a!=(-1*d), x[tp]))
if len(x[1]) == 0:
print(sum(x[0]))
elif len(x[1]) == 1:
if len(x[0])==0:
print(x[1][0])
elif len(x[0])==1:
print(x[1][0] + 2*x[0][0])
else:
x[0].sort(reverse=True)
print(x[1][0] + 2*x[0][0] + sum(x[0][1:len(x[0])]))
else:
if len(x[0])==0:
print(x[1][0]+ 2*sum(x[1][1:len(x[1])]))
elif len(x[0])==1:
print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0])
else:
x[0].sort(reverse = True)
x[1].sort()
print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0] + sum(x[0][1:len(x[0])]))
else:
x[tp].append(d)
if len(x[1]) == 0:
print(sum(x[0]))
elif len(x[1]) == 1:
if len(x[0])==0:
print(x[1][0])
elif len(x[0])==1:
print(x[1][0] + 2*x[0][0])
else:
x[0].sort(reverse=True)
print(x[1][0] + 2*x[0][0] + sum(x[0][1:len(x[0])]))
else:
if len(x[0])==0:
print(x[1][0]+ 2*sum(x[1][1:len(x[1])]))
elif len(x[0])==1:
print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0])
else:
x[0].sort(reverse = True)
x[1].sort()
print(x[1][0]+ 2*sum(x[1][1:len(x[1])]) + 2*x[0][0] + sum(x[0][1:len(x[0])]))
``` | instruction | 0 | 20,465 | 24 | 40,930 |
No | output | 1 | 20,465 | 24 | 40,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21
Submitted Solution:
```
class BalancingTree:
def __init__(self, n):
self.N = n
self.root = self.node(1<<n, 1<<n)
def debug(self):
def debug_info(nd_):
return (nd_.value - 1, nd_.pivot , nd_.left.value - 1 if nd_.left else -1, nd_.right.value - 1 if nd_.right else -1,nd_.cnt)
def debug_node(nd):
re = []
if nd.left:
re += debug_node(nd.left)
if nd.value: re.append(debug_info(nd))
if nd.right:
re += debug_node(nd.right)
return re
print("Debug - root =", self.root.value - 1, debug_node(self.root)[:50])
def append(self, v):
v += 1
nd = self.root
while True:
if v == nd.value:
return 0
else:
nd.cnt+=1
nd.sum+=v-1
mi, ma = min(v, nd.value), max(v, nd.value)
if mi < nd.pivot:
nd.value = ma
if nd.left:
nd = nd.left
v = mi
else:
p = nd.pivot
nd.left = self.node(mi, p - (p&-p)//2)
break
else:
nd.value = mi
if nd.right:
nd = nd.right
v = ma
else:
p = nd.pivot
nd.right = self.node(ma, p + (p&-p)//2)
break
def kth(self,k):
cnt=k
nd=self.root
while True:
if nd.left:
if nd.left.cnt<k:
k-=nd.left.cnt+1
if nd.right:
nd=nd.right
else:
raise IndexError("BalancingTree doesn't hold kth number")
elif nd.left.cnt==k:
return nd.value-1
else:
nd=nd.left
else:
if k==0:
return nd.value-1
if nd.right:
k-=1
nd=nd.right
else:
raise IndexError("BalancingTree doesn't hold kth number")
def kth_sum(self,k):
if k==-1:
return 0
cnt=k
res_sum=0
nd=self.root
while True:
if nd.left:
if nd.left.cnt<k:
k-=nd.left.cnt+1
res_sum+=nd.left.sum+nd.value-1
if nd.right:
nd=nd.right
else:
raise IndexError("BalancingTree doesn't hold kth number")
elif nd.left.cnt==k:
res_sum+=nd.left.sum+nd.value-1
return res_sum
else:
nd=nd.left
else:
if k==0:
return res_sum+nd.value-1
if nd.right:
k-=1
res_sum+=nd.value-1
nd=nd.right
else:
print(cnt,self.size,nd.value-1,nd.right)
self.debug()
raise IndexError("BalancingTree doesn't hold kth number")
def kth_sum_big(self,k):
res_sum=self.sum
if self.size>k:
res_sum-=self.kth_sum(self.size-k-2)
print(self.size-k-2,self.kth_sum(self.size-k-2))
return res_sum
else:
raise IndexError("BalancingTree doesn't hold kth number")
def leftmost(self, nd):
if nd.left: return self.leftmost(nd.left)
return nd
def rightmost(self, nd):
if nd.right: return self.rightmost(nd.right)
return nd
def find_l(self, v):
v += 1
nd = self.root
prev = 0
if nd.value < v: prev = nd.value
while True:
if v <= nd.value:
if nd.left:
nd = nd.left
else:
return prev - 1
else:
prev = nd.value
if nd.right:
nd = nd.right
else:
return prev - 1
def find_r(self, v):
v += 1
nd = self.root
prev = 0
if nd.value > v: prev = nd.value
while True:
if v < nd.value:
prev = nd.value
if nd.left:
nd = nd.left
else:
return prev - 1
else:
if nd.right:
nd = nd.right
else:
return prev - 1
@property
def max(self):
return self.find_l((1<<self.N)-1)
@property
def min(self):
return self.find_r(-1)
@property
def sum(self):
return self.root.sum-self.root.value+1
@property
def size(self):
return self.root.cnt-1
def delete(self, v, nd = None, prev = None):
v += 1
if not nd: nd = self.root
if not prev: prev = nd
while v != nd.value:
prev = nd
nd.cnt-=1
nd.sum-=v-1
if v <= nd.value:
if nd.left:
nd = nd.left
else:
return
else:
if nd.right:
nd = nd.right
else:
return
nd.cnt-=1
nd.sum-=v-1
if (not nd.left) and (not nd.right):
if not prev.left:
prev.right=None
elif not prev.right:
prev.left=None
else:
if nd.pivot==prev.left.pivot:
prev.left=None
else:
prev.right=None
elif nd.right:
nd.value = self.leftmost(nd.right).value
self.delete(nd.value - 1, nd.right, nd)
else:
nd.value = self.rightmost(nd.left).value
self.delete(nd.value - 1, nd.left, nd)
def __contains__(self, v: int) -> bool:
return self.find_r(v - 1) == v
class node:
def __init__(self, v, p):
self.value = v
self.pivot = p
self.left = None
self.right = None
self.cnt=1
self.sum=v-1
import sys
input=sys.stdin.readline
n=int(input())
xybst=BalancingTree(30)
xbst=BalancingTree(30)
ybst=BalancingTree(30)
x,y=0,0
S=0
for _ in range(n):
t,d=map(int,input().split())
if d<0:
if t==0:
xbst.delete(abs(d))
x-=1
else:
ybst.delete(abs(d))
y-=1
xybst.delete(abs(d))
else:
if t==0:
xbst.append(d)
x+=1
else:
ybst.append(d)
y+=1
xybst.append(abs(d))
S+=d
if x==0:
if y==0:
print(0)
else:
print(2*S-ybst.min)
else:
if y==0:
print(S)
else:
tmp,tmpy=xybst.kth_sum_big(y-1),ybst.kth_sum_big(y-1)
if tmp==tmpy:
print(S+tmp-ybst.min+xbst.max)
else:
print(S+tmp)
``` | instruction | 0 | 20,466 | 24 | 40,932 |
No | output | 1 | 20,466 | 24 | 40,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power x deals x damage to the monster, and lightning spell of power y deals y damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power 5, a lightning spell of power 1, and a lightning spell of power 8. There are 6 ways to choose the order in which he casts the spells:
* first, second, third. This order deals 5 + 1 + 2 β
8 = 22 damage;
* first, third, second. This order deals 5 + 8 + 2 β
1 = 15 damage;
* second, first, third. This order deals 1 + 2 β
5 + 8 = 19 damage;
* second, third, first. This order deals 1 + 2 β
8 + 2 β
5 = 27 damage;
* third, first, second. This order deals 8 + 2 β
5 + 1 = 19 damage;
* third, second, first. This order deals 8 + 2 β
1 + 2 β
5 = 20 damage.
Initially, Polycarp knows 0 spells. His spell set changes n times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the number of changes to the spell set.
Each of the next n lines contains two integers tp and d (0 β€ tp_i β€ 1; -10^9 β€ d β€ 10^9; d_i β 0) β the description of the change. If tp_i if equal to 0, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If d_i > 0, then Polycarp learns a spell of power d_i. Otherwise, Polycarp forgets a spell with power -d_i, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
Output
After each change, print the maximum damage Polycarp can deal with his current set of spells.
Example
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21
Submitted Solution:
```
i = int(input())
spell_book = []
def spell_damage(spells):
damage = 0
lightning_mult = 0
sspells = sorted(spells, key=lambda x: x[0], reverse=True)
if len(spells) > 1:
if spells[0][0] == spells[1][0]:
spells[0][1], spells[1][1] = spells[1][1], spells[0][1]
for spell in sspells:
if lightning_mult == 1:
damage += spell[1] * 2
lightning_mult = 0
elif lightning_mult == 0:
damage += spell[1]
if spell[0] == 1:
lightning_mult = 1
print(damage)
for x in range(i):
tp, d = [int(x) for x in input().split()]
if d > 0:
spell_book.append([tp, d])
elif d < 0:
spell_book.remove([tp, abs(d)])
spell_damage(spell_book)
``` | instruction | 0 | 20,467 | 24 | 40,934 |
No | output | 1 | 20,467 | 24 | 40,935 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"Hey, it's homework time" β thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
Input
The first line of the input data contains an integer n (1 β€ n β€ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 β€ ai β€ 5000, 1 β€ i β€ n).
Output
Print the only number β the minimum number of changes needed to get the permutation.
Examples
Input
3
3 1 2
Output
0
Input
2
2 2
Output
1
Input
5
5 3 3 3 1
Output
2
Note
The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2. | instruction | 0 | 21,363 | 24 | 42,726 |
Tags: greedy
Correct Solution:
```
n = int(input())
ns = [int(x) for x in input().split()]
ok = [False]*n
for ni in ns:
ni-=1
if ni<n:
ok[ni]=True
print(sum([1 for isOK in ok if not isOK]))
``` | output | 1 | 21,363 | 24 | 42,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"Hey, it's homework time" β thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
Input
The first line of the input data contains an integer n (1 β€ n β€ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 β€ ai β€ 5000, 1 β€ i β€ n).
Output
Print the only number β the minimum number of changes needed to get the permutation.
Examples
Input
3
3 1 2
Output
0
Input
2
2 2
Output
1
Input
5
5 3 3 3 1
Output
2
Note
The first sample contains the permutation, which is why no replacements are required.
In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.
In the third sample we can replace the second element with number 4 and the fourth element with number 2. | instruction | 0 | 21,364 | 24 | 42,728 |
Tags: greedy
Correct Solution:
```
n = int(input())
nums = set(map(int, input().split()))
count = 0
for i in range(1, n + 1):
if i not in nums:
count += 1
print(count)
``` | output | 1 | 21,364 | 24 | 42,729 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.