text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Tags: strings
Correct Solution:
```
import string
def main():
flags = input()
s1 = input()
s2 = input()
# flags = "aaabbaa"
# s1 = "aab"
# s2 = "aaa"
revFlags = flags[::-1]
foundF = canSee(flags, s1, s2)
foundRevF = canSee(revFlags, s1, s2)
if foundF == True:
if foundRevF == True:
print("both")
else:
print("forward")
else:
if foundRevF == True:
print("backward")
else:
print("fantasy")
def canSee(flags, s1, s2):
foundS1 = flags.find(s1)
if foundS1 != -1:
rem = flags[foundS1+len(s1):]
if rem.find(s2) != -1:
return True
return False
main()
#print(canSee("abacabb", "aca", "aa"))
```
| 10,500 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Tags: strings
Correct Solution:
```
m1 = input()
a = input()
b = input()
length = len(m1)
m2 = ""
r1 = False
r2 = False
for i in range(length):
m2 = m2 + m1[length-i-1]
for i in range(length):
if m1[i:i+len(a)] == a :
r1 = True
if r1 == True and m1[i+len(a):i+len(a)+len(b)] == b :
r2 = True
break
r3 = False
r4 = False
for i in range(length):
if m2[i:i + len(a)] == a:
r3 = True
if r3 == True and m2[i+len(a):i+len(b)+len(a)] == b:
r4 = True
break
if r2 == True and r4 == True : print("both")
if r2 == True and r4 == False : print("forward")
if r2 == False and r4 == True : print("backward")
if r2 == False and r4 == False : print("fantasy")
```
| 10,501 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Tags: strings
Correct Solution:
```
def train_and_peter():
flags = input()
a = input()
b = input()
i = flags.find(a)
if i == -1:
forward = False
else:
forward = flags.find(b, i + len(a)) != -1
reversed_flags = flags[::-1]
j = reversed_flags.find(a)
if j == -1:
backward = False
else:
backward = reversed_flags.find(b, j + len(a)) != -1
if forward and backward:
print('both')
elif forward:
print('forward')
elif backward:
print('backward')
else:
print('fantasy')
train_and_peter()
```
| 10,502 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Submitted Solution:
```
allflags = input() #input list of flags
flags1 = input()
flags2 = input()
searchresult = [0]*2 #array of search results
#check if Petya has written flags forward
res1 = allflags.find(flags1)
if res1 != -1: #if first string is in general list of flags
res2 = allflags.find(flags2, res1+len(flags1))
if res2 != -1: #if second string is in general list of flags
searchresult[0] = 1 #if two conditions are carried out
flags = list(allflags) #reverse list of flags
flags.reverse()
flagsrev = ''.join(flags)
#check if Petya has written flags backward
res1 = flagsrev.find(flags1)
if res1 != -1: #if first string is in general list of flags
res2 = flagsrev.find(flags2, res1+len(flags1))
if res2 != -1: #if second string is in general list of flags
searchresult[1] = 1 #if two conditions are carried out
#print the solution
if searchresult[0] == 1 and searchresult[1] == 1:
print('both')
elif searchresult[0] == 1:
print('forward')
elif searchresult[1] == 1:
print('backward')
else:
print('fantasy')
```
Yes
| 10,503 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Submitted Solution:
```
i,ii,iii = [input() for i in range(3)]
def check(a):
try:
c = a.index(ii)
cc = a.index(iii,c+len(ii))
except:
return 0,0
return c,cc
c = check(i)
cc = check(i[::-1])
if c[0] < c[1] and cc[0] < cc[1]: print("both")
elif c[0] < c[1]: print("forward")
elif cc[0] < cc[1]: print("backward")
else: print("fantasy")
```
Yes
| 10,504 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Submitted Solution:
```
def CF_8A():
flag=input()
one=input()
two=input()
rev_flag=flag[::-1]
forward=0
a=flag.find(one)
b=flag.rfind(two)
if a!=-1 and b!=-1 and a+len(one)<=b:
forward=1
backward=0
a=rev_flag.find(one)
b=rev_flag.rfind(two)
if a!=-1 and b!=-1 and a+len(one)<=b:
backward=1
if forward and backward:
print('both')
elif forward:
print('forward')
elif backward:
print('backward')
else:
print('fantasy')
return
CF_8A()
```
Yes
| 10,505 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Submitted Solution:
```
s=input()
s1=input()
s2=input()
index1=s.find(s1)
i=0
temp=index1
forward=0
backward=0
if(index1!=-1):
for x in range(temp,len(s)):
# print(s1[i],s[x],i)
if(i<len(s1)):
if(s1[i]==s[x]):
index1=index1+1
i=i+1
else:
break
else:
break
# print(s1[i],s[x],i)
# print(index1)
index2=s.find(s2,index1)
# print(index1,index2)
if(index2!=-1):
forward=1
s=s[::-1]
# s1,s2=s2,s1
index1=s.find(s1)
i=0
temp=index1
if(index1!=-1):
for x in range(temp,len(s)):
if(i<len(s1)):
if(s1[i]==s[x]):
index1=index1+1
i=i+1
else:
break
else:
break
index2=s.find(s2,index1)
# print(s,index1,index2)
if(index2!=-1):
backward=1
if(forward==1) and (backward==1):
print("both")
elif(forward==0) and (backward==0):
print("fantasy")
elif(forward==1):
print("forward")
else:
print("backward")
```
Yes
| 10,506 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Submitted Solution:
```
Way = input()
L1 = input()
L2 = input()
WayB = Way[::-1]
forw = True
back = True
if Way.find(L1) == Way.rfind(L2) == -1:
print('fantasy')
else:
if Way.find(L1) + len(L1) > Way.rfind(L2):
forw = False
if WayB.find(L1) + len(L2) > WayB.rfind(L2):
back = False
if forw and back:
print('both')
if (not forw) and back:
print('backward')
if forw and (not back):
print('forward')
if (not forw) and (not back):
print('fantasy')
```
No
| 10,507 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Submitted Solution:
```
r = input()
r2 = r[::-1]
a = input()
b = input()
if (a in r) * (b in r):
ai = []; ai2 = []
bi = []; bi2 = []
a = list(a); b = list(b)
forward = 0; backward = 0
for i in range(len(r)):
if forward == 0:
ai.append(r[i])
if len(ai) > len(a): del ai[0]
if ai == a: forward = 1
elif forward == 1:
bi.append(r[i])
if len(bi) > len(b): del bi[0]
if bi == b: forward = 2
if backward == 0:
ai2.append(r2[i])
if len(ai2) > len(a): del ai2[0]
if ai2 == a: backward = 1
elif backward == 1:
bi2.append(r2[i])
if len(bi2) > len(b): del bi2[0]
if bi2 == b: backward = 2
if forward == 2 and backward == 2: print("both")
elif forward == 2: print("forward")
elif backward == 2: print("backward")
else: print("fantasy")
else: print("fantasy")
```
No
| 10,508 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Submitted Solution:
```
s = input()
a = input()
b = input()
l = list(reversed(s))
s1 = "".join(l)
try:
a1 = s.index(a)
b1 = s.index(b)
if a == b :
print("fantasy")
elif s1 == s:
print("both")
elif a1 < b1:
print("forward")
elif b1<a1:
print("backward")
except ValueError:
print("fantasy")
```
No
| 10,509 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.
At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.
Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.
Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.
Input
The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.
The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.
Output
Output one of the four words without inverted commas:
* «forward» — if Peter could see such sequences only on the way from A to B;
* «backward» — if Peter could see such sequences on the way from B to A;
* «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;
* «fantasy» — if Peter could not see such sequences.
Examples
Input
atob
a
b
Output
forward
Input
aaacaaa
aca
aa
Output
both
Note
It is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.
Submitted Solution:
```
s = input()
a, b = input(), input()
ind = s.find(a)
first, second = 0, 0
if ind != -1:
ind = s[ind:].find(b)
if ind != -1:
first = 1
s = s[::-1]
ind = s.find(a)
if ind != -1:
ind = s[ind:].find(b)
if ind != -1:
second = 1
if first and second:
print('both')
elif first:
print('forward')
elif second:
print('backward')
else:
print('fantasy')
```
No
| 10,510 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Tags: implementation, strings
Correct Solution:
```
c=[input() for i in range(11)]
x=[ c[0][i:i+10] for i in range(0,80,10)]
for i in x:
print(c.index(i)-1,end='')
```
| 10,511 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Tags: implementation, strings
Correct Solution:
```
msg = input()
password = [msg[i:i+10] for i in range(0,80, 10)]
for i in range(10):
digit = input()
while digit in password:
password[password.index(digit)] = str(i)
print("".join(password))
```
| 10,512 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Tags: implementation, strings
Correct Solution:
```
string = str(input())
number0 = str(input())
number1 = str(input())
number2 = str(input())
number3 = str(input())
number4 = str(input())
number5 = str(input())
number6 = str(input())
number7 = str(input())
number8 = str(input())
number9 = str(input())
number = ""
i = 0
while i <= 80:
try:
if string[i:i + 10] == number0:
number += "0"
elif string[i:i + 10] == number1:
number += "1"
elif string[i:i + 10] == number2:
number += "2"
elif string[i:i + 10] == number3:
number += "3"
elif string[i:i + 10] == number4:
number += "4"
elif string[i:i + 10] == number5:
number += "5"
elif string[i:i + 10] == number6:
number += "6"
elif string[i:i + 10] == number7:
number += "7"
elif string[i:i + 10] == number8:
number += "8"
elif string[i:i + 10] == number9:
number += "9"
i += 10
except IndexError:
pass
print(number)
```
| 10,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Tags: implementation, strings
Correct Solution:
```
from __future__ import print_function
import sys
if __name__ == "__main__":
# '''input
# 01001100100101100000010110001001011001000101100110010110100001011010100101101100
# 0100110000
# 0100110010
# 0101100000
# 0101100010
# 0101100100
# 0101100110
# 0101101000
# 0101101010
# 0101101100
# 0101101110
# '''
encryted_password = input()
n = 10
split_password = [encryted_password[i:i+n]
for i in range(0, len(encryted_password), n)]
num_code_list = []
for i in range(10):
num_code_list.append(input())
decryted_password = ""
for i in range(len(split_password)):
for j in range(len(num_code_list)):
if split_password[i] == num_code_list[j]:
decryted_password += str(j)
print(decryted_password)
```
| 10,514 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Tags: implementation, strings
Correct Solution:
```
a=input()
c=[]
for i in range(0,10):
b=input()
c.append(b)
k=0
for i in range(0,8):
x=a[k:k+10]
j=0
while(x!=c[j]):
j=j+1
print(j,end="")
k=k+10
```
| 10,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Tags: implementation, strings
Correct Solution:
```
n = input()
numbers = {}
for i in range(10):
x = input()
numbers[x] = i
res = []
for i in range(8):
p = n[i*10 : (i*10)+10 ]
#print(p)
if p in numbers:
res.append(numbers[p])
for i in res:
print(i,end="")
```
| 10,516 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Tags: implementation, strings
Correct Solution:
```
def pars(_str):
pars_list = []
for i in range(0,80,10):
pars_list.append(_str[i:i+10])
return pars_list
def recover(_str,_list):
password = ''
for i in _str:
if i in _list:
password += str(_list.index(i))
return password
_str = input()
_list = []
for i in range(10):
_list.append(input())
_str = pars(_str)
print(recover(_str,_list))
```
| 10,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Tags: implementation, strings
Correct Solution:
```
s=input()
x={}
for i in range(10):
w=input()
x[w]=str(i)
ans=''
for i in range(0,80,10):
ans+=x[s[i:i+10]]
print(ans)
```
| 10,518 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Submitted Solution:
```
inp = input("")
ls = []
binaries = []
for i in range(0, 8):
binaries.append(inp[i * 10:(i + 1) * 10])
el = []
result = ''
for i in range(10):
el.append(input(""))
for i in range(8):
if binaries[i] in el:
result += str(el.index(binaries[i]))
print(result)
```
Yes
| 10,519 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Submitted Solution:
```
password = input()
str_to_dec = {}
for dec in range(10):
str_to_dec[input()] = dec
dec_pass = ""
for i in range(8):
dec_pass += str(str_to_dec[password[10*i:10*(i+1)]])
print(dec_pass)
```
Yes
| 10,520 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Submitted Solution:
```
def main():
encrypted = input()
decrypted = [''] * 8
numbers = {}
for i in range(10):
numbers[input()] = i
start = 0
end = start + 10
for i in range(8):
decrypted[i] = str(numbers[encrypted[start:end]])
start = end
end += 10
print(''.join(decrypted))
if __name__ == '__main__':
main()
```
Yes
| 10,521 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Submitted Solution:
```
pwd = str(input())
seq = [str(input()),str(input()),str(input()),str(input()),str(input())
,str(input()),str(input()),str(input()),str(input()),str(input())]
for n in range(0 , 8):
for i in range(0 ,len(seq)) :
if pwd[n*10:n*10+10] ==seq[i] :
print(i , end= '')
```
Yes
| 10,522 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Submitted Solution:
```
c = input()
a = []
for x in range(10):
a.append(input())
qwerty = ""
for x in range(8):
for z in range(10):
#print(c[x:x+10])
if a[z]==c[x:x+10]:
qwerty+=str(z)
print(qwerty)
```
No
| 10,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Submitted Solution:
```
cod = input()
ind = ["" for loop in range(10)]
for i in range(10):
ind[i] = input()
ch =cod[i]
for i in range(1,len(cod)):
j = 0
bol = False
if i%10 == 0:
while bol == False and j<10:
if ind[j] == ch:
bol = True
print (j,end='')
else:
j+=1
ch = cod[i]
else:
ch += cod[i]
j = 0
bol = False
while bol == False and j<10:
if ind[j] == ch:
bol = True
print (j)
else:
j+=1
```
No
| 10,524 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Submitted Solution:
```
encoded_string = input()
digits = []
for _ in range(10):
digits.append(input())
for idx, digit in enumerate(digits):
encoded_string = encoded_string.replace(digit, str(idx))
print(encoded_string)
```
No
| 10,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".
Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" — thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.
Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.
Help Igor K. restore his ISQ account by the encrypted password and encryption specification.
Input
The input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.
Output
Print one line containing 8 characters — The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.
Examples
Input
01001100100101100000010110001001011001000101100110010110100001011010100101101100
0100110000
0100110010
0101100000
0101100010
0101100100
0101100110
0101101000
0101101010
0101101100
0101101110
Output
12345678
Input
10101101111001000010100100011010101101110010110111011000100011011110010110001000
1001000010
1101111001
1001000110
1010110111
0010110111
1101001101
1011000001
1110010101
1011011000
0110001000
Output
30234919
Submitted Solution:
```
arr=[]
reslt=[]
count=0
rst=''
str_to=''
x=input()
for i in range(10):
arr.append(input())
for i in range(len(x)):
str_to+=x[i]
count+=1
if count==10:
reslt.append(str_to)
str_to=''
count=0
for i in range(len(arr)):
for j in range(len(reslt)):
if arr[i]==reslt[j]:
rst+=str(i)
print(rst)
```
No
| 10,526 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys
from math import sqrt, gcd, ceil, log
from bisect import bisect, bisect_left
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop
inp = sys.stdin.readline
read = lambda: list(map(int, inp().strip().split()))
# sys.setrecursionlimit(10**3)
def main():
n, m = read()
graph = defaultdict(list)
for i in range(m):
u,v = read()
graph[u].append(v)
graph[v].append(u)
visited = [0]*(n+1)
# def dfs(node):
# visited[node] = 1
# f = (len(graph[node]) == 2)
# for i in graph[node]:
# very good probelm
# if not visited[i]:
# f &= dfs(i)
# # else:
# # return(f)
# return(f)
ans = 0
# print("*******")
for i in range(1, n+1):
if not visited[i]:
f = (len(graph[i]) == 2)
stack = [i]
while stack:
elem = stack.pop()
visited[elem] = 1
f &= (len(graph[elem]) == 2)
for j in graph[elem]:
if not visited[j]:
stack.append(j)
ans += f
print(ans)
if __name__ == "__main__":
main()
```
| 10,527 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import bisect
import sys
from collections import deque
input = sys.stdin.readline
def main():
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
g[a-1].append(b-1)
g[b-1].append(a-1)
ans = 0
current = []
used = [False] * n
def bfs(node):
q = deque()
q.append(node)
while q:
node = q.popleft()
if not used[node]:
used[node] = True
current.append(node)
for child in g[node]:
q.append(child)
for v in range(n):
current.clear()
if not used[v]:
bfs(v)
cycle = True
for u in current:
if len(g[u]) != 2:
cycle = False
break
if cycle:
ans += 1
print(ans)
if __name__ == '__main__':
main()
```
| 10,528 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
n, m = map(int, input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
to_check = set(i for i in range(n+1) if len(graph[i]) == 2)
cnt = 0
while to_check:
node = to_check.pop()
right, left = graph[node]
while left in to_check:
to_check.remove(left)
v1, v2 = graph[left]
if v1 in to_check:
left = v1
elif v2 in to_check:
left = v2
else:
break
if left == right:
cnt += 1
print(cnt)
```
| 10,529 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import setrecursionlimit
setrecursionlimit(100000)
from collections import deque
nV, nE = map(int, input().split())
g = [[] for _ in range(nV)]
for _ in range(nE):
u, v = map(lambda x: int(x) - 1, input().split())
g[u].append(v)
g[v].append(u)
def bfs(v):
visited[v] = True
q = deque([v])
res = True
while q:
cur = q.pop()
res &= len(g[cur]) == 2
for to in g[cur]:
if not visited[to]:
visited[to] = True
q.appendleft(to)
return res
def dfs(v):
visited[v] = True
res = len(g[v]) == 2
for to in g[v]:
if not visited[to]:
res &= dfs(to)
return res
visited = [False] * nV
ret = 0
for v in range(nV):
if not visited[v]:
ret += bfs(v)
print(ret)
```
| 10,530 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin,stdout
from collections import Counter
st=lambda:list(stdin.readline().strip())
li=lambda:list(map(int,stdin.readline().split()))
mp=lambda:map(int,stdin.readline().split())
inp=lambda:int(stdin.readline())
pr=lambda n: stdout.write(str(n)+"\n")
mod=1000000007
INF= float('inf')
def DFS(n):
v[n]=True
stack=[n]
p=set()
while stack:
a=stack.pop()
p.add(len(d[a]))
for i in d[a]:
if i==par[a]:
continue
else:
if not v[i]:
v[i]=True
stack.append(i)
par[i]=a
return p=={2}
n,m=mp()
d={i:[] for i in range(1,n+1)}
for i in range(m):
a,b=mp()
d[a].append(b)
d[b].append(a)
v=[False for i in range(n+1)]
ans=0
par=[-1 for i in range(n+1)]
for i in range(1,n+1):
if not v[i]:
cycle=DFS(i)
if cycle:
ans+=1
pr(ans)
```
| 10,531 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin
from collections import defaultdict, deque
import io
def find_cycle(graph, visited, node):
stack = deque()
stack.append((node, None))
cycle = False
while stack:
(node, parent) = stack.pop()
if node in visited:
cycle = True
else:
stack.extend((child, node) for child in graph[node] if child != parent)
visited.add(node)
return cycle
def cycliccomps(graph):
visited = set()
result = 0
for node in graph:
if node in visited or len(graph[node]) == 2:
continue
find_cycle(graph, visited, node)
for node in graph:
if node in visited:
continue
if find_cycle(graph, visited, node):
result += 1
return result
# input = io.StringIO("""17 15
# 1 8
# 1 12
# 5 11
# 11 9
# 9 15
# 15 5
# 4 13
# 3 13
# 4 3
# 10 16
# 7 10
# 16 7
# 14 3
# 14 4
# 17 6""")
input = stdin
input.readline()
graph = defaultdict(list)
for line in input:
(n1, n2) = line.split()
graph[int(n1)].append(int(n2))
graph[int(n2)].append(int(n1))
print(cycliccomps(graph))
```
| 10,532 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
n,m=R()
v=[[] for i in range(n)]
for i in range(m):
a,b=R()
v[a-1]+=b-1,
v[b-1]+=a-1,
vl=[len(v[i]) for i in range(n)]
vst=[0]*n
ans=0
for i in range(n):
if vst[i]:continue
flg=1
stack=[i]
vst[i]=1
if vl[i]!=2:flg=0
while stack:
p=stack.pop()
for el in v[p]:
if not vst[el]:
vst[el]=1
stack+=el,
if vl[el]!=2:flg=0
if flg:ans+=1
print(ans)
```
| 10,533 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys,math
from collections import Counter,deque,defaultdict
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
n,m = inpl()
uf = UnionFind(n)
g = [[] for _ in range(n)]
for _ in range(m):
a,b = inpl()
a,b = a-1,b-1
uf.union(a,b)
g[a].append(b)
g[b].append(a)
ch = [[] for _ in range(n)]
for i in range(n):
now = uf.find(i)
ch[now].append(i)
res = 0
for i in range(n):
if ch[i] == [] or len(ch) < 3: continue
d = defaultdict(int)
for now in ch[i]:
for x in g[now]:
d[x] += 1
if len(ch[i]) != len(list(d)): continue
for now in ch[i]:
if d[now] != 2:
break
else:
res += 1
print(res)
```
| 10,534 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
n, m = map(int, input().split())
edges = __import__('collections').defaultdict(list); connected = set()
for _ in range(m):
v1, v2 = map(int, input().split())
connected.add((v1, v2) if v1 < v2 else (v2, v1))
edges[v1].append(v2); edges[v2].append(v1)
components = set(i for i in edges.keys() if len(edges[i]) == 2)
count = 0
while components:
current, last = edges[components.pop()]
while current in components:
components.remove(current)
v1, v2 = edges[current]
contains_v1, contains_v2 = v1 in components, v2 in components
if not contains_v1 and not contains_v2: break
else: current = (v1 if contains_v1 else v2)
if current == last: count += 1
print(count)
```
Yes
| 10,535 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
from collections import deque
from sys import stdin
input=stdin.readline
n,m=map(int,input().split())
arr=[[] for i in range(n+1)]
for i in range(m):
u,v=map(int,input().split())
arr[u].append(v)
arr[v].append(u)
vis=[-1]*(n+1)
count=0
for i in range(1,n+1):
if vis[i]==-1:
l=[]
q=deque()
q.append(i)
while len(q)!=0:
x=q.popleft()
l.append(x)
vis[x]=1
for ele in arr[x]:
if vis[ele]==-1:
q.append(ele)
flag=True
for ele in l:
if len(arr[ele])!=2:
flag=False
break
if flag:
count=count+1
print(count)
```
Yes
| 10,536 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
def connected_components(neighbors):
seen = set()
def component(node):
nodes = set([node])
while nodes:
node = nodes.pop()
seen.add(node)
nodes |= neighbors[node] - seen
yield node
for node in neighbors:
if node not in seen:
yield component(node)
from collections import defaultdict
graph = defaultdict(set)
n,m = map(int,input().split())
for _ in range(m):
u,v = map(int,input().split())
graph[u].add(v)
graph[v].add(u)
total = 0
for component in connected_components(graph):
nodes = list(component)
size = len(nodes)
seen = set()
current = nodes[0]
while len(seen) < size:
choice = list(graph[current])
if len(choice) != 2:break
seen.add(current)
possible = [c for c in choice if c not in seen]
if not possible: break
current = possible[0]
if len(seen) == size:
total+=1
print (total)
```
Yes
| 10,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
# the iterative approach to grpah traversal was required
# generate graph using a dictionary
graph = {}
vert,edge = map(int,input().split())
reached = set()
for _ in range(edge):
a,b = map(int,input().split())
if a not in graph.keys():
graph.update({a:[b]})
else: graph[a].append(b)
if b not in graph.keys():
graph.update({b:[a]})
else: graph[b].append(a)
# cycles have 2 edges, i think
cycle = dict(filter(lambda x: len(x[1]) == 2,graph.items()))
cyc= 0
while cycle:
target = next(iter(cycle))
left,right = cycle.pop(target)
while right in cycle.keys():
l1,r1 = cycle.pop(right)
if r1 in cycle.keys():
right = r1
elif l1 in cycle.keys():
right = l1
else: break
if right == left: cyc +=1
print(cyc)
```
Yes
| 10,538 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
from sys import stdin, stdout
count = 0
def find(node):
x = []
while dsu[node] > 0:
x.append(node)
node = dsu[node]
for i in x:
dsu[i] = node
return node
def union(node1, node2):
if node1 != node2:
if dsu[node1] > dsu[node2]:
node1, node2 = node2, node1
dsu[node1] += dsu[node2]
dsu[node2] = node1
else:
if not cycle[node1][0] and cycle[node1][1] == 0:
cycle[node1] = (True, 1)
elif cycle[node1][0] and cycle[node1][1] == 1:
cycle[node1] = (False, 1)
n, m = map(int, stdin.readline().strip().split())
dsu = [-1]*(n+1)
cycle = [(False,0)]*(n+1)
for __ in range(m):
a, b = map(int, stdin.readline().strip().split())
union(find(a), find(b))
for i in range(1, n+1):
if cycle[i][0] and cycle[i][1]==1:
count += 1
stdout.write(f'{count}')
```
No
| 10,539 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
adj[u].append(v)
adj[v].append(u)
out = 0
marks = [None for _ in range(n)]
def dfs(v):
stack = [v]
while stack:
v = stack.pop()
if marks[v] is not None:
continue
marks[v] = True
path.append(v)
for j in adj[v]:
stack.append(j)
def graph_cyclic():
if n < 3:
return False
for j in path:
degree = len(adj[j])
if degree % 2 != 0 or degree < (n/2):
return False
return True
cc_cyclic = 0
for i in range(n):
if marks[i] is None:
path = []
dfs(i)
if graph_cyclic():
cc_cyclic += 1
print(cc_cyclic)
```
No
| 10,540 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
class N:
def __init__(self, i) -> None:
self.i = i
self.st = None
self.ft = None
self.p = None
self.c = []
if __name__ == '__main__':
n, m = map(int, input().split())
arr = [N(i + 1) for i in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
arr[u].c.append(arr[v])
arr[v].c.append(arr[u])
t = 0
cdct = {}
for r in arr:
if r.ft:
continue
st = [r]
while st:
t += 1
r = st.pop()
if r.st:
r.ft = t
continue
r.st = t
st.append(r)
for c in r.c:
if c == r.p:
continue
if not c.ft:
if c.st:
cy = (min(c.i, r.i), max(c.i, r.i))
if c.i in cdct or r.i in cdct:
if c.i in cdct:
(u, v), _ = cdct[c.i]
cdct[u] = (u, v), False
cdct[v] = (u, v), False
if r.i in cdct:
(u, v), _ = cdct[r.i]
cdct[u] = (u, v), False
cdct[v] = (u, v), False
cdct[c.i] = cy, False
cdct[r.i] = cy, False
else:
cdct[c.i] = cy, True
cdct[r.i] = cy, True
else:
t += 1
c.p = r
st.append(c)
print(len(set(cy for cy, tv in cdct.values() if tv)))
```
No
| 10,541 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.
Here are some definitions of graph theory.
An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A connected component is a cycle if and only if its vertices can be reordered in such a way that:
* the first vertex is connected with the second vertex by an edge,
* the second vertex is connected with the third vertex by an edge,
* ...
* the last vertex is connected with the first vertex by an edge,
* all the described edges of a cycle are distinct.
A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices.
<image> There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15].
Input
The first line contains two integer numbers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — number of vertices and edges.
The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.
Output
Print one integer — the number of connected components which are also cycles.
Examples
Input
5 4
1 2
3 4
5 4
3 5
Output
1
Input
17 15
1 8
1 12
5 11
11 9
9 15
15 5
4 13
3 13
4 3
10 16
7 10
16 7
14 3
14 4
17 6
Output
2
Note
In the first example only component [3, 4, 5] is also a cycle.
The illustration above corresponds to the second example.
Submitted Solution:
```
from sys import stdin,stdout
class DFS_General:
def __init__(self, edges, n):
self.n = n
self.pi = [-1 for _ in range(n)]
self.visit = [False for _ in range(n)]
self.Ady = edges
self.compo = [-1 for _ in range(n)]
self.count = -1
def DFS_visit(self, u):
self.visit[u] = True
for v in self.Ady[u]:
if not self.visit[v]:
self.pi[v] = u
self.DFS_visit(v)
self.compo[u] = self.count
def DFS(self):
for i in range(self.n):
if not self.visit[i]:
self.count += 1
self.DFS_visit(i)
def Solution(Ady, n, degree):
DFS_ = DFS_General(Ady, n)
DFS_.DFS()
verif = [True for _ in range(DFS_.count)]
for i in range(n):
if degree[i] != 2:
verif [DFS_.compo[i]] = False
var = 0
for item in verif:
if item:
var += 1
return var
n_m = stdin.readline().split()
n = int(n_m[0])
m = int(n_m[1])
Ady = [[] for _ in range(n)]
degree = [0 for _ in range(n)]
for i in range(m):
stri= stdin.readline().split()
item = (int(stri[0])-1, int(stri[1])-1)
Ady[item[0]].append(item[1])
Ady[item[1]].append(item[0])
degree[item[0]]+=1
degree[item[1]]+=1
stdout.write('ccccccccc')
stdout.write(str(Solution(Ady,n,degree)))
```
No
| 10,542 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On one of the planets of Solar system, in Atmosphere University, many students are fans of bingo game.
It is well known that one month on this planet consists of n^2 days, so calendars, represented as square matrix n by n are extremely popular.
Weather conditions are even more unusual. Due to the unique composition of the atmosphere, when interacting with sunlight, every day sky takes one of three colors: blue, green or red.
To play the bingo, you need to observe the sky for one month — after each day, its cell is painted with the color of the sky in that day, that is, blue, green or red.
At the end of the month, students examine the calendar. If at least one row or column contains only cells of one color, that month is called lucky.
Let's call two colorings of calendar different, if at least one cell has different colors in them. It is easy to see that there are 3^{n ⋅ n} different colorings. How much of them are lucky? Since this number can be quite large, print it modulo 998244353.
Input
The first and only line of input contains a single integer n (1 ≤ n ≤ 1000 000) — the number of rows and columns in the calendar.
Output
Print one number — number of lucky colorings of the calendar modulo 998244353
Examples
Input
1
Output
3
Input
2
Output
63
Input
3
Output
9933
Note
In the first sample any coloring is lucky, since the only column contains cells of only one color.
In the second sample, there are a lot of lucky colorings, in particular, the following colorings are lucky:
<image>
While these colorings are not lucky:
<image>
Submitted Solution:
```
n = int(input())
if n==1: print(3)
elif n==2: print(63)
elif n==3: print(9933)
elif n==4: print(11213343)
elif n==5: print(149702586)
elif n==6: print(977299444)
elif n==7: print(184654847)
elif n==8: print(126441804)
elif n==9: print(858462679)
elif n==10: print(267328409)
elif n==100: print(485774850)
elif n==500: print(559588851)
elif n==1200: print(681471241)
elif n==10001: print(729761820)
elif n==100002: print(990446288)
elif n==1000000: print(733684421)
elif n==11: print(5647520983)
elif n==12: print(771756884)
elif n==13: print(138307135)
elif n==14: print(189544955)
elif n==15: print(695058759)
elif n==16: print(977073017)
elif n==17: print(49721264)
elif n==18: print(743995156)
elif n==19: print(133001100)
elif n==20: print(562961266)
elif n==21: print(476427482)
elif n==22: print(547105672)
elif n==23: print(92989454)
elif n==24: print(278945223)
elif n==25: print(883544047)
elif n==26: print(572019095)
elif n==27: print(39733884)
elif n==28: print(837323055)
elif n==29: print(475382551)
elif n==30: print(89507673)
elif n==1100: print(96619671)
elif n==10228: print(37159602)
elif n==401230: print(522040619)
elif n==591899: print(827652698)
elif n==791899: print(8092157)
elif n==999999: print(756184448)
```
No
| 10,543 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On one of the planets of Solar system, in Atmosphere University, many students are fans of bingo game.
It is well known that one month on this planet consists of n^2 days, so calendars, represented as square matrix n by n are extremely popular.
Weather conditions are even more unusual. Due to the unique composition of the atmosphere, when interacting with sunlight, every day sky takes one of three colors: blue, green or red.
To play the bingo, you need to observe the sky for one month — after each day, its cell is painted with the color of the sky in that day, that is, blue, green or red.
At the end of the month, students examine the calendar. If at least one row or column contains only cells of one color, that month is called lucky.
Let's call two colorings of calendar different, if at least one cell has different colors in them. It is easy to see that there are 3^{n ⋅ n} different colorings. How much of them are lucky? Since this number can be quite large, print it modulo 998244353.
Input
The first and only line of input contains a single integer n (1 ≤ n ≤ 1000 000) — the number of rows and columns in the calendar.
Output
Print one number — number of lucky colorings of the calendar modulo 998244353
Examples
Input
1
Output
3
Input
2
Output
63
Input
3
Output
9933
Note
In the first sample any coloring is lucky, since the only column contains cells of only one color.
In the second sample, there are a lot of lucky colorings, in particular, the following colorings are lucky:
<image>
While these colorings are not lucky:
<image>
Submitted Solution:
```
def search(a):
s = None
flg = False
for i in range(len(a)):
if flg is True:
break
if a[i] == '2':
for j in range(len(a)):
if a[j] == '5':
s = '25'
flg = True
break
elif a[i] == '5':
for j in range(len(a)):
if a[j] == '2':
s = '25'
flg = True
break
elif a[j] == '7':
s = '75'
flg = True
break
elif a[j] == '0':
s = '50'
flg = True
break
elif a[i] == '7':
for j in range(len(a)):
if a[j] == '5':
s = '75'
flg = True
break
elif a[i] == '0':
for j in range(len(a)):
if a[j] == '5':
s = '50'
flg = True
break
elif a[j] == '0':
s = '00'
flg = True
break
if s is None:
print(-1)
exit()
return s
#def swap(a,b):
# a, b = b, a
# return b, a
def czero(a):
ctr = 0
index = None
for i in range(len(a)):
if a[i] != 0:
index = i
break
if index == 0:
return None
else:
cou = index
while a[0] == '0':
a[cou-1], a[cou] = a[cou], a[cou-1]
ctr+=1
cou-=1
return ctr
Counter = 0
a=input()[::-1]
Comb = search(a)
a = list(a)[::-1]
Nxt = a.index(Comb[1])
for i in range(Nxt+1, len(a)):
a[i-1], a[i] = a[i], a[i-1]
Counter+=1
Fst = a.index(Comb[0])
for i in range(Fst+1, len(a)-1):
a[i-1], a[i] = a[i], a[i-1]
Counter+=1
f = czero(a)
if f is None:
print(Counter)
else:
print(Counter+f)
```
No
| 10,544 |
Provide a correct Python 3 solution for this coding contest problem.
We have N boxes numbered 1 to N, and M balls numbered 1 to M. Currently, Ball i is in Box A_i.
You can do the following operation:
* Choose a box containing two or more balls, pick up one of the balls from that box, and put it into another box.
Since the balls are very easy to break, you cannot move Ball i more than C_i times in total. Within this limit, you can do the operation any number of times.
Your objective is to have Ball i in Box B_i for every i (1 \leq i \leq M). Determine whether this objective is achievable. If it is, also find the minimum number of operations required to achieve it.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq A_i,B_i \leq N
* 1 \leq C_i \leq 10^5
* In the situation where the objective is achieved, every box contains one or more balls. That is, for every i (1 \leq i \leq N), there exists j such that B_j=i.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
A_2 B_2 C_2
\vdots
A_M B_M C_M
Output
If the objective is unachievable, print -1; if it is achievable, print the minimum number of operations required to achieve it.
Examples
Input
3 3
1 2 1
2 1 1
1 3 2
Output
3
Input
2 2
1 2 1
2 1 1
Output
-1
Input
5 5
1 2 1
2 1 1
1 3 2
4 5 1
5 4 1
Output
6
Input
1 1
1 1 1
Output
0
"Correct Solution:
```
import sys
from bisect import bisect_left
from collections import defaultdict
from itertools import accumulate
class UnionFind:
def __init__(self, n):
self.table = [-1] * n
def _root(self, x):
stack = []
tbl = self.table
while tbl[x] >= 0:
stack.append(x)
x = tbl[x]
for y in stack:
tbl[y] = x
return x
def find(self, x, y):
return self._root(x) == self._root(y)
def unite(self, x, y):
r1 = self._root(x)
r2 = self._root(y)
if r1 == r2:
return
d1 = self.table[r1]
d2 = self.table[r2]
if d1 <= d2:
self.table[r2] = r1
self.table[r1] += d2
else:
self.table[r1] = r2
self.table[r2] += d1
def get_size(self, x):
return -self.table[self._root(x)]
def solve():
n, m = map(int, sys.stdin.buffer.readline().split())
extra_durabilities = [0] * n
self_loop_durabilities = [[] for _ in range(n)]
outdegrees = [0] * n
base_operation_count = 0
uft = UnionFind(n)
mp = map(int, sys.stdin.buffer.read().split())
for a, b, c in zip(mp, mp, mp):
a -= 1
b -= 1
outdegrees[a] += 1
if a == b:
if c >= 2:
self_loop_durabilities[a].append(c)
continue
uft.unite(a, b)
extra_durabilities[a] += c - 1
base_operation_count += 1
# components[root] = [size, max_outdegree, durability(non-self-loop), self-loop-durability]
components = defaultdict(lambda: [0, 0, 0, []])
for i in range(n):
r = uft._root(i)
item = components[r]
item[0] += 1
item[1] = max(item[1], outdegrees[i])
item[2] += extra_durabilities[i]
item[3].extend(self_loop_durabilities[i])
exists_initial_catalyst_on_moving_path = False
exists_initial_catalyst_at_self_loop = False
supplied_catalyst = 0
demanded_catalyst = 0
self_loop_catalysts_cost1 = []
self_loop_catalysts_cost2 = []
for i, (cnt, deg, dur, sel) in components.items():
if cnt == 1:
if deg == 1:
self_loop_catalysts_cost2.extend(c - 2 for c in sel)
else:
if len(sel) >= 1:
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
exists_initial_catalyst_at_self_loop = True
continue
if deg == 1:
supplied_catalyst += dur
demanded_catalyst += 1
else:
supplied_catalyst += dur
if dur >= 1:
exists_initial_catalyst_on_moving_path = True
elif len(sel) >= 1:
exists_initial_catalyst_at_self_loop = True
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
# print(base_operation_count, supplied_catalyst, demanded_catalyst,
# exists_initial_catalyst_on_moving_path, exists_initial_catalyst_at_self_loop)
if demanded_catalyst == 0:
return base_operation_count
if not exists_initial_catalyst_on_moving_path and not exists_initial_catalyst_at_self_loop:
return -1
if supplied_catalyst >= demanded_catalyst:
if exists_initial_catalyst_on_moving_path:
return base_operation_count + demanded_catalyst
else:
return base_operation_count + demanded_catalyst + 1
self_loop_catalysts_cost1.sort(reverse=True)
self_loop_catalysts_cost2.sort(reverse=True)
# print(self_loop_catalysts_cost1)
# print(self_loop_catalysts_cost2)
acc1 = [0] + list(accumulate(self_loop_catalysts_cost1))
acc2 = [0] + list(accumulate(self_loop_catalysts_cost2))
# print(acc1)
# print(acc2)
shortage = demanded_catalyst - supplied_catalyst
if acc1[-1] + acc2[-1] < shortage:
return -1
cost = 10 ** 18
for use1 in range(0 if exists_initial_catalyst_on_moving_path else 1, len(acc1)):
cat = acc1[use1]
remaining = shortage - cat
if remaining <= 0:
cost = min(cost, use1)
break
if remaining > acc2[-1]:
continue
use2 = bisect_left(acc2, remaining)
cost = min(cost, use1 + 2 * use2)
return base_operation_count + demanded_catalyst + cost
print(solve())
```
| 10,545 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have N boxes numbered 1 to N, and M balls numbered 1 to M. Currently, Ball i is in Box A_i.
You can do the following operation:
* Choose a box containing two or more balls, pick up one of the balls from that box, and put it into another box.
Since the balls are very easy to break, you cannot move Ball i more than C_i times in total. Within this limit, you can do the operation any number of times.
Your objective is to have Ball i in Box B_i for every i (1 \leq i \leq M). Determine whether this objective is achievable. If it is, also find the minimum number of operations required to achieve it.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq A_i,B_i \leq N
* 1 \leq C_i \leq 10^5
* In the situation where the objective is achieved, every box contains one or more balls. That is, for every i (1 \leq i \leq N), there exists j such that B_j=i.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
A_2 B_2 C_2
\vdots
A_M B_M C_M
Output
If the objective is unachievable, print -1; if it is achievable, print the minimum number of operations required to achieve it.
Examples
Input
3 3
1 2 1
2 1 1
1 3 2
Output
3
Input
2 2
1 2 1
2 1 1
Output
-1
Input
5 5
1 2 1
2 1 1
1 3 2
4 5 1
5 4 1
Output
6
Input
1 1
1 1 1
Output
0
Submitted Solution:
```
import sys
from bisect import bisect_left
from collections import defaultdict
from itertools import accumulate
class UnionFind:
def __init__(self, n):
self.table = [-1] * n
def _root(self, x):
stack = []
tbl = self.table
while tbl[x] >= 0:
stack.append(x)
x = tbl[x]
for y in stack:
tbl[y] = x
return x
def find(self, x, y):
return self._root(x) == self._root(y)
def unite(self, x, y):
r1 = self._root(x)
r2 = self._root(y)
if r1 == r2:
return
d1 = self.table[r1]
d2 = self.table[r2]
if d1 <= d2:
self.table[r2] = r1
self.table[r1] += d2
else:
self.table[r1] = r2
self.table[r2] += d1
def get_size(self, x):
return -self.table[self._root(x)]
def solve():
n, m = map(int, sys.stdin.buffer.readline().split())
extra_durabilities = [0] * n
self_loop_durabilities = [[] for _ in range(n)]
outdegrees = [0] * n
base_operation_count = 0
uft = UnionFind(n)
mp = map(int, sys.stdin.buffer.read().split())
for a, b, c in zip(mp, mp, mp):
a -= 1
b -= 1
outdegrees[a] += 1
if a == b:
if c >= 2:
self_loop_durabilities[a].append(c)
continue
uft.unite(a, b)
extra_durabilities[a] += c - 1
base_operation_count += 1
# components[root] = [size, max_outdegree, durability(non-self-loop), self-loop-durability]
components = defaultdict(lambda: [0, 0, 0, []])
for i in range(n):
r = uft._root(i)
item = components[r]
item[0] += 1
item[1] = max(item[1], outdegrees[i])
item[2] += extra_durabilities[i]
item[3].extend(self_loop_durabilities[i])
exists_initial_catalyst = False
supplied_catalyst = 0
demanded_catalyst = 0
self_loop_catalysts_cost1 = []
self_loop_catalysts_cost2 = []
for i, (cnt, deg, dur, sel) in components.items():
if cnt == 1:
if deg == 1:
self_loop_catalysts_cost2.extend(c - 2 for c in sel)
else:
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
exists_initial_catalyst = True
continue
if deg == 1:
supplied_catalyst += dur
demanded_catalyst += 1
else:
supplied_catalyst += dur
if dur >= 1 or sel:
exists_initial_catalyst = True
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
# print(base_operation_count, supplied_catalyst, demanded_catalyst, exists_initial_catalyst)
if demanded_catalyst == 0:
return base_operation_count
if not exists_initial_catalyst:
return -1
if supplied_catalyst >= demanded_catalyst:
return base_operation_count + demanded_catalyst
self_loop_catalysts_cost1.sort(reverse=True)
self_loop_catalysts_cost2.sort(reverse=True)
# print(self_loop_catalysts_cost1)
# print(self_loop_catalysts_cost2)
acc1 = list(accumulate(self_loop_catalysts_cost1))
acc2 = [0] + list(accumulate(self_loop_catalysts_cost2))
# print(acc1)
# print(acc2)
shortage = demanded_catalyst - supplied_catalyst
if acc1[-1] + acc2[-1] < shortage:
return -1
cost = 10 ** 18
for use1, cat in enumerate(acc1, start=1):
remaining = shortage - cat
if remaining <= 0:
cost = min(cost, use1)
break
if remaining > acc2[-1]:
continue
use2 = bisect_left(acc2, remaining)
cost = min(cost, use1 + 2 * use2)
return base_operation_count + demanded_catalyst + cost
print(solve())
```
No
| 10,546 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have N boxes numbered 1 to N, and M balls numbered 1 to M. Currently, Ball i is in Box A_i.
You can do the following operation:
* Choose a box containing two or more balls, pick up one of the balls from that box, and put it into another box.
Since the balls are very easy to break, you cannot move Ball i more than C_i times in total. Within this limit, you can do the operation any number of times.
Your objective is to have Ball i in Box B_i for every i (1 \leq i \leq M). Determine whether this objective is achievable. If it is, also find the minimum number of operations required to achieve it.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq A_i,B_i \leq N
* 1 \leq C_i \leq 10^5
* In the situation where the objective is achieved, every box contains one or more balls. That is, for every i (1 \leq i \leq N), there exists j such that B_j=i.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
A_2 B_2 C_2
\vdots
A_M B_M C_M
Output
If the objective is unachievable, print -1; if it is achievable, print the minimum number of operations required to achieve it.
Examples
Input
3 3
1 2 1
2 1 1
1 3 2
Output
3
Input
2 2
1 2 1
2 1 1
Output
-1
Input
5 5
1 2 1
2 1 1
1 3 2
4 5 1
5 4 1
Output
6
Input
1 1
1 1 1
Output
0
Submitted Solution:
```
import sys
from bisect import bisect_left
from collections import defaultdict
from itertools import accumulate
class UnionFind:
def __init__(self, n):
self.table = [-1] * n
def _root(self, x):
stack = []
tbl = self.table
while tbl[x] >= 0:
stack.append(x)
x = tbl[x]
for y in stack:
tbl[y] = x
return x
def find(self, x, y):
return self._root(x) == self._root(y)
def unite(self, x, y):
r1 = self._root(x)
r2 = self._root(y)
if r1 == r2:
return
d1 = self.table[r1]
d2 = self.table[r2]
if d1 <= d2:
self.table[r2] = r1
self.table[r1] += d2
else:
self.table[r1] = r2
self.table[r2] += d1
def get_size(self, x):
return -self.table[self._root(x)]
def solve():
n, m = map(int, sys.stdin.buffer.readline().split())
extra_durabilities = [0] * n
self_loop_durabilities = [[] for _ in range(n)]
outdegrees = [0] * n
base_operation_count = 0
uft = UnionFind(n)
mp = map(int, sys.stdin.buffer.read().split())
for a, b, c in zip(mp, mp, mp):
a -= 1
b -= 1
outdegrees[a] += 1
if a == b:
if c >= 3:
self_loop_durabilities[a].append(c)
continue
uft.unite(a, b)
extra_durabilities[a] += c - 1
base_operation_count += 1
# components[root] = [size, max_outdegree, durability(non-self-loop), self-loop-durability]
components = defaultdict(lambda: [0, 0, 0, []])
for i in range(n):
r = uft._root(i)
item = components[r]
item[0] += 1
item[1] = max(item[1], outdegrees[i])
item[2] += extra_durabilities[i]
item[3].extend(self_loop_durabilities[i])
exists_initial_catalyst = False
supplied_catalyst = 0
demanded_catalyst = 0
self_loop_catalysts_cost1 = []
self_loop_catalysts_cost2 = []
for i, (cnt, deg, dur, sel) in components.items():
if cnt == 1:
if deg == 1:
self_loop_catalysts_cost2.extend(c - 2 for c in sel)
else:
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
continue
if deg == 1:
supplied_catalyst += dur
demanded_catalyst += 1
else:
supplied_catalyst += dur
exists_initial_catalyst = True
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
if demanded_catalyst == 0:
return base_operation_count
if not exists_initial_catalyst:
return -1
if supplied_catalyst >= demanded_catalyst:
return base_operation_count + demanded_catalyst
self_loop_catalysts_cost1.sort(reverse=True)
self_loop_catalysts_cost2.sort(reverse=True)
acc1 = [0] + list(accumulate(self_loop_catalysts_cost1))
acc2 = [0] + list(accumulate(self_loop_catalysts_cost2))
shortage = demanded_catalyst - supplied_catalyst
if acc1[-1] + acc2[-1] < shortage:
return -1
cost = 10 ** 18
for use1, cat in enumerate(acc1):
remaining = shortage - cat
if remaining <= 0:
cost = min(cost, use1)
break
use2 = bisect_left(acc2, remaining)
cost = min(cost, use1 + 2 * use2)
return base_operation_count + demanded_catalyst + cost
print(solve())
```
No
| 10,547 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have N boxes numbered 1 to N, and M balls numbered 1 to M. Currently, Ball i is in Box A_i.
You can do the following operation:
* Choose a box containing two or more balls, pick up one of the balls from that box, and put it into another box.
Since the balls are very easy to break, you cannot move Ball i more than C_i times in total. Within this limit, you can do the operation any number of times.
Your objective is to have Ball i in Box B_i for every i (1 \leq i \leq M). Determine whether this objective is achievable. If it is, also find the minimum number of operations required to achieve it.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq A_i,B_i \leq N
* 1 \leq C_i \leq 10^5
* In the situation where the objective is achieved, every box contains one or more balls. That is, for every i (1 \leq i \leq N), there exists j such that B_j=i.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
A_2 B_2 C_2
\vdots
A_M B_M C_M
Output
If the objective is unachievable, print -1; if it is achievable, print the minimum number of operations required to achieve it.
Examples
Input
3 3
1 2 1
2 1 1
1 3 2
Output
3
Input
2 2
1 2 1
2 1 1
Output
-1
Input
5 5
1 2 1
2 1 1
1 3 2
4 5 1
5 4 1
Output
6
Input
1 1
1 1 1
Output
0
Submitted Solution:
```
import sys
from bisect import bisect_left
from collections import defaultdict
from itertools import accumulate
class UnionFind:
def __init__(self, n):
self.table = [-1] * n
def _root(self, x):
stack = []
tbl = self.table
while tbl[x] >= 0:
stack.append(x)
x = tbl[x]
for y in stack:
tbl[y] = x
return x
def find(self, x, y):
return self._root(x) == self._root(y)
def unite(self, x, y):
r1 = self._root(x)
r2 = self._root(y)
if r1 == r2:
return
d1 = self.table[r1]
d2 = self.table[r2]
if d1 <= d2:
self.table[r2] = r1
self.table[r1] += d2
else:
self.table[r1] = r2
self.table[r2] += d1
def get_size(self, x):
return -self.table[self._root(x)]
def solve():
n, m = map(int, sys.stdin.buffer.readline().split())
extra_durabilities = [0] * n
self_loop_durabilities = [[] for _ in range(n)]
outdegrees = [0] * n
base_operation_count = 0
uft = UnionFind(n)
mp = map(int, sys.stdin.buffer.read().split())
for a, b, c in zip(mp, mp, mp):
a -= 1
b -= 1
outdegrees[a] += 1
if a == b:
if c >= 2:
self_loop_durabilities[a].append(c)
continue
uft.unite(a, b)
extra_durabilities[a] += c - 1
base_operation_count += 1
# components[root] = [size, max_outdegree, durability(non-self-loop), self-loop-durability]
components = defaultdict(lambda: [0, 0, 0, []])
for i in range(n):
r = uft._root(i)
item = components[r]
item[0] += 1
item[1] = max(item[1], outdegrees[i])
item[2] += extra_durabilities[i]
item[3].extend(self_loop_durabilities[i])
exists_initial_catalyst_on_moving_path = False
exists_initial_catalyst_at_self_loop = False
supplied_catalyst = 0
demanded_catalyst = 0
self_loop_catalysts_cost1 = []
self_loop_catalysts_cost2 = []
for i, (cnt, deg, dur, sel) in components.items():
if cnt == 1:
if deg == 1:
self_loop_catalysts_cost2.extend(c - 2 for c in sel)
else:
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
exists_initial_catalyst_at_self_loop = True
continue
if deg == 1:
supplied_catalyst += dur
demanded_catalyst += 1
else:
supplied_catalyst += dur
if dur >= 1:
exists_initial_catalyst_on_moving_path = True
elif len(sel) >= 1:
exists_initial_catalyst_at_self_loop = True
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
# print(base_operation_count, supplied_catalyst, demanded_catalyst,
# exists_initial_catalyst_on_moving_path, exists_initial_catalyst_at_self_loop)
if demanded_catalyst == 0:
return base_operation_count
if not exists_initial_catalyst_on_moving_path and not exists_initial_catalyst_at_self_loop:
return -1
if supplied_catalyst >= demanded_catalyst:
if exists_initial_catalyst_on_moving_path:
return base_operation_count + demanded_catalyst
else:
return base_operation_count + demanded_catalyst + 1
self_loop_catalysts_cost1.sort(reverse=True)
self_loop_catalysts_cost2.sort(reverse=True)
# print(self_loop_catalysts_cost1)
# print(self_loop_catalysts_cost2)
acc1 = [0] + list(accumulate(self_loop_catalysts_cost1))
acc2 = [0] + list(accumulate(self_loop_catalysts_cost2))
# print(acc1)
# print(acc2)
shortage = demanded_catalyst - supplied_catalyst
if acc1[-1] + acc2[-1] < shortage:
return -1
cost = 10 ** 18
for use1 in range(0 if exists_initial_catalyst_on_moving_path else 1, len(acc1)):
cat = acc1[use1]
remaining = shortage - cat
if remaining <= 0:
cost = min(cost, use1)
break
if remaining > acc2[-1]:
continue
use2 = bisect_left(acc2, remaining)
cost = min(cost, use1 + 2 * use2)
return base_operation_count + demanded_catalyst + cost
print(solve())
```
No
| 10,548 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have N boxes numbered 1 to N, and M balls numbered 1 to M. Currently, Ball i is in Box A_i.
You can do the following operation:
* Choose a box containing two or more balls, pick up one of the balls from that box, and put it into another box.
Since the balls are very easy to break, you cannot move Ball i more than C_i times in total. Within this limit, you can do the operation any number of times.
Your objective is to have Ball i in Box B_i for every i (1 \leq i \leq M). Determine whether this objective is achievable. If it is, also find the minimum number of operations required to achieve it.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq A_i,B_i \leq N
* 1 \leq C_i \leq 10^5
* In the situation where the objective is achieved, every box contains one or more balls. That is, for every i (1 \leq i \leq N), there exists j such that B_j=i.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
A_2 B_2 C_2
\vdots
A_M B_M C_M
Output
If the objective is unachievable, print -1; if it is achievable, print the minimum number of operations required to achieve it.
Examples
Input
3 3
1 2 1
2 1 1
1 3 2
Output
3
Input
2 2
1 2 1
2 1 1
Output
-1
Input
5 5
1 2 1
2 1 1
1 3 2
4 5 1
5 4 1
Output
6
Input
1 1
1 1 1
Output
0
Submitted Solution:
```
import sys
# 箱を頂点とし、A→Bに有向辺を張る
# ①出次数(初期でボールが入っている個数)が全て1以下の、サイズ2以上の連結成分
# ・分岐のないサイクル(入次数1以上が保証されているため)
# ・外部から触媒が来ないと動かせない。来たら全て連鎖的に流れる
# ・流れる途中で Ci>=2 のボールがあればそいつも他の触媒になれる
# ②出次数に2以上のものがある連結成分
# ・強連結成分分解+トポロジカルソートを考える(実際にやる必要は無い)
# ・トポロジカル順で最上位になる組は、必ず下位の組に辺が伸びる頂点が出次数2以上
# ・連鎖的に全てのボールを希望の箱に1回で移せる
# ・Ci>=2 のボールがあれば他の触媒になれる
# ③自己ループボール
# ・動かす必要は無いが、Ci>=2なら触媒数が足りなければ触媒になれる
# ・②に含まれるものは、全体の移動回数を1増やすことでCi-1回触媒を増やせる
# ・完全に浮いているものはそれ自身を起動するのにも触媒が必要なので、
# 全体の移動回数を2と触媒数1を犠牲にCi-1回触媒を増やせる(差し引きCi-2回)
#
# ①が存在し、かつ②が1つもなければ不可能
# ①が存在しなければ、A!=Bであるボール数
# ①が存在し、初期で②が1つでもあれば、
# A!=Bであるボール数 + ①の個数 が下限
# 触媒が足りない場合、全体の移動回数を1 or 2増やすことでCi-2回触媒を増やせる
# →それでも足りなければ不可能
# →足りるならコストと価値でナップサック問題
# A!=Bであるボール数 + ①の個数 + 自己ループを触媒に利用するためのコスト
from bisect import bisect_left
from collections import defaultdict
from itertools import accumulate
class UnionFind:
def __init__(self, n):
self.table = [-1] * n
def _root(self, x):
stack = []
tbl = self.table
while tbl[x] >= 0:
stack.append(x)
x = tbl[x]
for y in stack:
tbl[y] = x
return x
def find(self, x, y):
return self._root(x) == self._root(y)
def unite(self, x, y):
r1 = self._root(x)
r2 = self._root(y)
if r1 == r2:
return
d1 = self.table[r1]
d2 = self.table[r2]
if d1 <= d2:
self.table[r2] = r1
self.table[r1] += d2
else:
self.table[r1] = r2
self.table[r2] += d1
def get_size(self, x):
return -self.table[self._root(x)]
def solve():
n, m = map(int, sys.stdin.buffer.readline().split())
extra_durabilities = [0] * n
self_loop_durabilities = [[] for _ in range(n)]
outdegrees = [0] * n
base_operation_count = 0
uft = UnionFind(n)
mp = map(int, sys.stdin.buffer.read().split())
for a, b, c in zip(mp, mp, mp):
a -= 1
b -= 1
outdegrees[a] += 1
if a == b:
if c >= 3:
self_loop_durabilities[a].append(c)
continue
uft.unite(a, b)
extra_durabilities[a] += c - 1
base_operation_count += 1
# components[root] = [size, max_outdegree, durability(non-self-loop), self-loop-durability]
components = defaultdict(lambda: [0, 0, 0, []])
for i in range(n):
r = uft._root(i)
item = components[r]
item[0] += 1
item[1] = max(item[1], outdegrees[i])
item[2] += extra_durabilities[i]
item[3].extend(self_loop_durabilities[i])
exists_initial_catalyst = False
supplied_catalyst = 0
demanded_catalyst = 0
self_loop_catalysts_cost1 = []
self_loop_catalysts_cost2 = []
for i, (cnt, deg, dur, sel) in components.items():
if cnt == 1:
if deg == 1:
self_loop_catalysts_cost2.extend(c - 2 for c in sel)
else:
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
continue
if deg == 1:
supplied_catalyst += dur
demanded_catalyst += 1
else:
supplied_catalyst += dur
exists_initial_catalyst = True
self_loop_catalysts_cost1.extend(c - 1 for c in sel)
if demanded_catalyst == 0:
return base_operation_count
if not exists_initial_catalyst:
return -1
if supplied_catalyst >= demanded_catalyst:
return base_operation_count + demanded_catalyst
self_loop_catalysts_cost1.sort(reverse=True)
self_loop_catalysts_cost2.sort(reverse=True)
acc1 = [0] + list(accumulate(self_loop_catalysts_cost1))
acc2 = [0] + list(accumulate(self_loop_catalysts_cost2))
shortage = demanded_catalyst - supplied_catalyst
if acc1[-1] + acc2[-1] < shortage:
return -1
cost = 10 ** 18
for use1, cat in enumerate(acc1):
remaining = shortage - cat
if remaining <= 0:
cost = min(cost, use1)
break
if remaining > acc2[-1]:
continue
use2 = bisect_left(acc2, remaining)
cost = min(cost, use1 + 2 * use2)
return base_operation_count + demanded_catalyst + cost
print(solve())
```
No
| 10,549 |
Provide a correct Python 3 solution for this coding contest problem.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
"Correct Solution:
```
H, N = map(int, input().split())
l = list(map(int, input().split()))
print('Yes' if H <= sum(l) else 'No')
```
| 10,550 |
Provide a correct Python 3 solution for this coding contest problem.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
"Correct Solution:
```
H, N = map(int, input().split())
PP = list(map(int, input().split()))
print("Yes" if sum(PP) >= H else "No")
```
| 10,551 |
Provide a correct Python 3 solution for this coding contest problem.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
"Correct Solution:
```
H, N = map(int, input().split())
a = sum(map(int, input().split()))
print("Yes" if a >= H else "No")
```
| 10,552 |
Provide a correct Python 3 solution for this coding contest problem.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
"Correct Solution:
```
h, n, *a = map(int, open(0).read().split())
if sum(a) >= h:
print("Yes")
else:
print("No")
```
| 10,553 |
Provide a correct Python 3 solution for this coding contest problem.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
"Correct Solution:
```
h,n=map(int,input().split())
A=list(map(int,input().split()))
print("Yes" if h<=sum(A) else "No")
```
| 10,554 |
Provide a correct Python 3 solution for this coding contest problem.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
"Correct Solution:
```
h,n = map(int,input().split())
a =[int(i) for i in input().split()]
print("Yes" if sum(a) >= h else "No")
```
| 10,555 |
Provide a correct Python 3 solution for this coding contest problem.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
"Correct Solution:
```
H,N=map(int,input().split())
A=[int(i) for i in input().split()]
print('Yes' if H<=sum(A) else "No")
```
| 10,556 |
Provide a correct Python 3 solution for this coding contest problem.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
"Correct Solution:
```
h,n = map(int,input().split())
a = list(map(int,input().split()))
print(["No","Yes"][sum(a) >= h])
```
| 10,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
Submitted Solution:
```
h,a=map(int,input().split())
l=list(map(int,input().split()))
print("Yes" if h<=sum(l) else "No")
```
Yes
| 10,558 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
Submitted Solution:
```
h,n=map(int,input().split())
A=tuple(map(int,input().split()))
print('Yes' if sum(A)>=h else 'No')
```
Yes
| 10,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
Submitted Solution:
```
h, _, *a = map(int, open(0).read().split())
print("Yes" if sum(a) >= h else "No")
```
Yes
| 10,560 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
Submitted Solution:
```
H, N = map(int, input().split())
A = [int(i) for i in input().split()]
print("Yes" if H<=sum(A) else "No")
```
Yes
| 10,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
Submitted Solution:
```
A, B = map(int, input().split())
input_list = input().split( )
input_sum = sum(input_list)
if(A <= input_sum):
print("Yes")
else:
print("No")
```
No
| 10,562 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
Submitted Solution:
```
N,H = map(int,input().split())
A = [int(i) for i in input().split()]
A.sort(reverse = True)
B = max(0,N-(A[0]+A[1]))
if B > 0:
print("No")
else:
print("Yes")
```
No
| 10,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
Submitted Solution:
```
H,N = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
#print(A)
MOVES = len(A)
NUM = MOVES
#print(MOVES)
count = 0
flag = 0
while(MOVES > 0):
H -= A[MOVES-1]
MOVES -= 1
if(H < 1):
print('yes')
flag = 1
break
if(flag == 0):
print('no')
```
No
| 10,564 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Raccoon is fighting with a monster.
The health of the monster is H.
Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health.
Raccoon wins when the monster's health becomes 0 or below.
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq H \leq 10^9
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H N
A_1 A_2 ... A_N
Output
If Raccoon can win without using the same move twice or more, print `Yes`; otherwise, print `No`.
Examples
Input
10 3
4 5 6
Output
Yes
Input
20 3
4 5 6
Output
No
Input
210 5
31 41 59 26 53
Output
Yes
Input
211 5
31 41 59 26 53
Output
No
Submitted Solution:
```
H,N = map(int, input().split())
hisatsu = list(map(int,input().split()))
for i in range(N):
H -= hisatsu[i-1]
if H >> 0:
print(No)
else:
print(Yes)
```
No
| 10,565 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
"Correct Solution:
```
import heapq
from collections import defaultdict
N = int(input())
P = list(map(int,input().split()))
d_r = defaultdict(lambda:N+1)
h_r = []
d_r2 = defaultdict(lambda:N+1)
h_r2 = []
for i in range(N):
p = P[i]
while h_r2:
q = heapq.heappop(h_r2)
if q < p:
d_r2[q] = p
else:
heapq.heappush(h_r2,q)
break
while h_r:
q = heapq.heappop(h_r)
if q < p:
d_r[q] = p
heapq.heappush(h_r2,q)
else:
heapq.heappush(h_r,q)
break
heapq.heappush(h_r,p)
d_l = defaultdict(lambda:0)
h_l = []
d_l2 = defaultdict(lambda:0)
h_l2 = []
for i in range(N-1,-1,-1):
p = P[i]
while h_l2:
q = heapq.heappop(h_l2)
if q < p:
d_l2[q] = p
else:
heapq.heappush(h_l2,q)
break
while h_l:
q = heapq.heappop(h_l)
if q < p:
d_l[q] = p
heapq.heappush(h_l2,q)
else:
heapq.heappush(h_l,q)
break
heapq.heappush(h_l,p)
d = {}
for i in range(N):
d[P[i]] = i
d[N+1] = N
d[0] = -1
ans = 0
for i in range(N):
x = d[d_l2[P[i]]]
y = d[d_l[P[i]]]
z = d[d_r[P[i]]]
w = d[d_r2[P[i]]]
ans += P[i]*((y-x)*(z-i)+(w-z)*(i-y))
print(ans)
```
| 10,566 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
"Correct Solution:
```
def argsort(a):
return list(map(lambda z: z[1], sorted(zip(a, range(len(a))))))
N = int(input())
P = list(map(int, input().split()))
a = argsort(P)
left = [i for i in range(N)]
right = [i for i in range(N)]
result = 0
for i in range(1, N):
k = a[i - 1]
extend_left = k - 1 >= 0 and P[k - 1] < i
extend_right = k + 1 < N and P[k + 1] < i
if extend_left and extend_right:
L = left[k - 1]
R = right[k + 1]
elif extend_left:
L = left[k - 1]
R = k
elif extend_right:
R = right[k + 1]
L = k
else:
L = k
R = k
right[L] = R
left[R] = L
if L - 1 >= 0:
if L - 2 >= 0 and P[L - 2] < i:
LL = left[L - 2]
else:
LL = L - 1
result += ((L - 1) - LL + 1) * (R - k + 1) * i;
if R + 1 < N:
if R + 2 < N and P[R + 2] < i:
RR = right[R + 2]
else:
RR = R + 1
result += (RR - (R + 1) + 1) * (k - L + 1) * i;
print(result)
```
| 10,567 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from operator import itemgetter
n = int(readline())
ppp = list(map(int,readline().split()))
def BIT_add(i,x):
while i <= n:
tree[i] += x
i += i&(-i)
def BIT_sum(i):
s = 0
while i:
s += tree[i]
i -= i&(-i)
return s
def BIT_search(x):
# 二分探索。和がx以上となる最小のインデックス(>= 1)を返す
i = 0
s = 0
step = 1<<(n.bit_length()-1)
while step:
if i+step <= n and s + tree[i+step] < x:
i += step
s += tree[i]
step >>= 1
return i+1
q = sorted(enumerate(ppp,1),key=itemgetter(1),reverse=True)
tree = [0]*(n+1)
ans = 0
for i, p in q:
L = BIT_sum(i) # 左にある既に書き込んだ数の個数
BIT_add(i,1)
R = n-p-L # 右にある既に書き込んだ数の個数
LL = BIT_search(L-1) if L >= 2 else 0
LR = BIT_search(L) if L >= 1 else 0
RL = BIT_search(L+2) if R >= 1 else n+1
RR = BIT_search(L+3) if R >= 2 else n+1
ans += p*((LR-LL)*(RL-i)+(RR-RL)*(i-LR))
print(ans)
```
| 10,568 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
"Correct Solution:
```
import sys
stdin = sys.stdin
ni = lambda: int(ns())
nl = lambda: list(map(int, stdin.readline().split()))
nm = lambda: map(int, stdin.readline().split())
ns = lambda: stdin.readline().rstrip()
n = ni()
p = nl()
q = [0]*(n+1)
for i in range(n):
q[p[i]] = i+1
ans = 0
l = [0] + [i for i in range(n+1)]
r = [i+1 for i in range(n+1)] + [n+1]
for i in range(1,n+1):
v = q[i]
l1,r1 = l[v],r[v]
l2,r2 = l[l1],r[r1]
ans += i*((v-l1)*(r2-r1) + (r1-v)*(l1-l2))
l[r1] = l1
r[l1] = r1
print(ans)
```
| 10,569 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
"Correct Solution:
```
def solve():
N = int(input())
Ps = list(map(int, input().split()))
def makeBIT(numEle):
numPow2 = 2 ** (numEle-1).bit_length()
data = [0] * (numPow2+1)
return data, numPow2
def addValue(iA, A):
iB = iA + 1
while iB <= numPow2:
data[iB] += A
iB += iB & -iB
def getSum(iA):
iB = iA + 1
ans = 0
while iB > 0:
ans += data[iB]
iB -= iB & -iB
return ans
data, numPow2 = makeBIT(N)
iPs = list(range(N))
iPs.sort(key=lambda iP: Ps[iP])
ans = 0
for iP in reversed(iPs):
v = getSum(iP)
Bs = []
for x in range(v-1, v+3):
if x <= 0:
L = -1
elif getSum(numPow2-1) < x:
L = N
else:
maxD = numPow2.bit_length()-1
L = 0
S = 0
for d in reversed(range(maxD)):
if S+data[L+(1<<d)] < x:
S += data[L+(1<<d)]
L += 1<<d
Bs.append(L)
num = (Bs[1]-Bs[0])*(Bs[2]-iP) + (iP-Bs[1])*(Bs[3]-Bs[2])
ans += Ps[iP] * num
addValue(iP, 1)
print(ans)
solve()
```
| 10,570 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from operator import itemgetter
n = int(readline())
ppp = list(map(int,readline().split()))
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
self.depth = n.bit_length()
def sum(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.tree[i] += x
i += i & -i
def lower_bound(self, x):
""" 累積和がx以上になる最小のindexと、その直前までの累積和 """
sum_ = 0
pos = 0
for i in range(self.depth, -1, -1):
k = pos + (1 << i)
if k <= self.size and sum_ + self.tree[k] < x:
sum_ += self.tree[k]
pos += 1 << i
return pos + 1
q = sorted(enumerate(ppp,1),key=itemgetter(1),reverse=True)
bit = Bit(n+4)
bit.add(1,1)
bit.add(2,1)
bit.add(n+3,1)
bit.add(n+4,1)
ans = 0
for i, p in q:
f = bit.sum(i+2)
LL = max(2,bit.lower_bound(f-1))
LR = bit.lower_bound(f)
RL = bit.lower_bound(f+1)
RR = min(n+3,bit.lower_bound(f+2))
ans += p*((i+2-LR)*(RR-RL)+(LR-LL)*(RL-i-2))
bit.add(i+2,1)
print(ans)
```
| 10,571 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
"Correct Solution:
```
class SparseTable:
def __init__(self, a, func=max, one=-10**18):
self.table = [a[:]]
self.n = len(a)
self.logn = self.n.bit_length()
self.func = func
self.one = one
for i in map(lambda x: 1 << x, range(self.logn - 1)):
self.table.append([])
for j in range(self.n - i * 2 + 1):
self.table[-1].append(self.func(self.table[-2][j],
self.table[-2][j + i]))
def get_section(self, i, j):
length = j - i
log = length.bit_length() - 1
if length <= 0:
return self.one
a = self.func(self.table[log][i], self.table[log][j - (1<<log)])
return a
def low(m, x):
mi = 0
ma = m - 1
if ma < 0 or sp.get_section(0, m) <= x:
return - 1
while mi != ma:
mm = (mi + ma) // 2 + 1
if sp.get_section(mm, m) > x:
mi = mm
else:
ma = mm - 1
return mi
def high(m, x):
mi = m
ma = n - 1
if m >= n or sp.get_section(m, n) <= x:
return n
while mi != ma:
mm = (mi + ma) // 2
if sp.get_section(m, mm+1) > x:
ma = mm
else:
mi = mm + 1
return mi
n = int(input())
p = [int(i) for i in input().split()]
sp = SparseTable(p)
ans = 0
for i in range(n):
j = low(i, p[i])
k = low(j, p[i])
l = high(i, p[i])
m = high(l+1, p[i])
ans += p[i] * ((i-j) * (m-l) + (j-k) * (l-i))
print(ans)
```
| 10,572 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
"Correct Solution:
```
class BinaryIndexedTree:
def __init__(self, size):
self.data = [0] * (size+1)
self.msb = 1 << (size.bit_length()-1)
def add(self, i, w):
i += 1
while i < len(self.data):
self.data[i] += w
i += i & -i
def get_sum(self, i):
res = 0
while i > 0:
res += self.data[i]
i -= i & -i
return res
def __getitem__(self, i):
"""
[0,i)
"""
if isinstance(i, slice):
return self.get_sum(i.stop) if i.start is None else self.get_sum(i.stop) - self.get_sum(i.start)
else:
return 0 # fake value
__setitem__ = add
def bisect_left(self, v):
"""
return smallest i s.t v <= sum[:i]
"""
i = 0
k = self.msb
while k > 0:
i += k
if i < len(self.data) and self.data[i] < v:
v -= self.data[i]
else:
i -= k
k >>= 1
return i
def bisect_right(self, v):
"""
return smallest i s.t v < sum[:i]
"""
i = 0
k = self.msb
while k > 0:
i += k
if i < len(self.data) and self.data[i] <= v:
v -= self.data[i]
else:
i -= k
k >>= 1
return i
bisect = bisect_right
def naive(P):
def it():
for i in range(len(P)-1):
for j in range(i+1,len(P)):
yield sorted(P[i:j+1])[-2]
return sum(it())
def solve(P):
def it():
bit = BinaryIndexedTree(len(P))
for cnt, (v,i) in enumerate(sorted(((v,i) for i,v in enumerate(P)), reverse=True)):
bit[i] += 1
c = bit.get_sum(i)
low1 = -1 if c <= 0 else bit.bisect_left(c)
low2 = -1 if c <= 1 else bit.bisect_left(c-1)
up1 = len(P) if c > cnt-1 else bit.bisect_left(c+2)
up2 = len(P) if c > cnt-2 else bit.bisect_left(c+3)
yield v*((up1-i)*(low1-low2)+(i-low1)*(up2-up1))
return sum(it())
if __name__ == '__main__':
N = int(input())
P = list(map(int,input().split()))
print(solve(P))
```
| 10,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7
class BIT:
def __init__(self, n):
# 0-indexed
nv = 1
while nv < n:
nv *= 2
self.size = nv
self.tree = [0] * nv
def sum(self, i):
""" [0, i]を合計する """
s = 0
i += 1
while i > 0:
s += self.tree[i-1]
i -= i & -i
return s
def add(self, i, x):
""" 値の追加:添字i, 値x """
i += 1
while i <= self.size:
self.tree[i-1] += x
i += i & -i
def get(self, l, r=None):
""" 区間和の取得 [l, r) """
# 引数が1つなら一点の値を取得
if r is None: r = l + 1
res = 0
if r: res += self.sum(r-1)
if l: res -= self.sum(l-1)
return res
def bisearch_left(self, l, r, x):
""" 区間[l,r]で左からx番目の値がある位置 """
l_sm = self.sum(l-1)
ok = r + 1
ng = l - 1
while ng+1 < ok:
mid = (ok+ng) // 2
if self.sum(mid) - l_sm >= x:
ok = mid
else:
ng = mid
if ok != r + 1:
return ok
else:
return -1
def bisearch_right(self, l, r, x):
""" 区間[l,r]で右からx番目の値がある位置 """
r_sm = self.sum(r)
ok = l - 1
ng = r + 1
while ok+1 < ng:
mid = (ok+ng) // 2
if r_sm - self.sum(mid-1) >= x:
ok = mid
else:
ng = mid
if ok != l - 1:
return ok
else:
return -1
N = INT()
A = LIST()
# aの昇順に処理できるようにindexで並べておく
idxs = [0] * (N+1)
for i, a in enumerate(A):
idxs[a] = i + 1
bit = BIT(N+2)
# 先頭と末尾に番兵を仕込む
bit.add(0, 2)
bit.add(N+1, 2)
ans = [0] * (N+1)
# 大きいaから見ていく
for a in range(N, 0, -1):
# a(N~1)が格納されているindex
idx = idxs[a]
# 自分より小さいindexで2回目に自分より大きい値がある直前の場所
p = bit.bisearch_right(0, idx, 2) + 1
# 自分より小さいindexで最初に自分より大きい値がある直前の場所
q = bit.bisearch_right(0, idx, 1) + 1
# 自分より大きいindexで最初に自分より大きい値がある直前の場所
r = bit.bisearch_left(idx, N+1, 1) - 1
# 自分より大きいindexで2回目に自分より大きい値がある直前の場所
s = bit.bisearch_left(idx, N+1, 2) - 1
# aを使う回数 * a = (左に自分より大きい値がある時の通り数 + 右に自分より大きい値がある時の通り数) * a
ans[a] = ((q-p)*(r-idx+1) + (idx-q+1)*(s-r)) * a
# aを出現済とする
bit.add(idx, 1)
# 全てのaについての合計
print(sum(ans))
```
Yes
| 10,574 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
Submitted Solution:
```
N = int(input())
P = [0]+list(map(int,input().split()))+[N+1]
ans = 0
b = [0]*(N+2)
for i in range(N+2):
b[P[i]] = i
l1 = [max(0,i-1) for i in range(N+2)]
l2 = [max(0,i-2) for i in range(N+2)]
r1 = [min(N+1,i+1) for i in range(N+2)]
r2 = [min(N+1,i+2) for i in range(N+2)]
for i in range(N+1):
m = b[i]
x2,x1,y1,y2 = l2[m],l1[m],r1[m],r2[m]
hoge= i*(abs((m-x1)*(y2-y1)) + abs((y1-m)*(x1-x2)))
ans += hoge
#x1
r1[x1] = y1
r2[x1] = y2
#y1
l1[y1] = x1
l2[y1] = x2
#x2
r1[x2] = x1
r2[x2] = y1
#y2
l1[y2] = y1
l2[y2] = x1
print(ans)
```
Yes
| 10,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
Submitted Solution:
```
from bisect import bisect_left
import array
n = int(input())
p = []
for i, x in enumerate(map(int, input().split())):
p.append([x, i])
p.sort(reverse=True)
s = array.array('i', [-1, -1, p[0][1], n, n])
#print(p)
ans = 0
i = 2
for a, x in p[1:]:
t = bisect_left(s, x)
ans += a * ((x - s[t-1]) * (s[t+1] - s[t]) + (s[t] - x) * (s[t-1] - s[t-2]))
#print(t, s)
s.insert(t, x)
i += 1
print(ans)
```
Yes
| 10,576 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
Submitted Solution:
```
import sys
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip() # ignore trailing spaces
n = ni()
a = na()
st = []
ans = 0
gans = 0
for i in range(n):
v = a[i]
l = 0
bst = []
while len(st) > 0 and st[-1][1] < v:
h = st.pop(-1)
ans -= h[1] * h[2]
if h[0] < v:
h[0], h[1] = v, h[0]
else:
h[1] = v
ans += h[1]*h[2]
if len(bst) > 0 and bst[-1][0] == h[0] and bst[-1][1] == h[1]:
bst[-1][2] += h[2]
else:
bst.append(h)
st.extend(bst[::-1])
st.append([v, 0, 1])
gans += ans
print(gans)
```
Yes
| 10,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
Submitted Solution:
```
import sys
from bisect import bisect
class Node:
def __init__(self, key, height):
self.key = key #ノードの木
self.height = height #このノードを根とする部分木の高さ
self.left = None
self.right = None
def size(self, n): return 0 if n is None else n.height
def bias(self): #左の方が高いと正、右が高いと負の値を返す
return self.size(self.left) - self.size(self.right)
#木の高さの計算
def calcSize(self):
self.height = 1 + max(self.size(self.left), self.size(self.right))
class AVLTree:
def __init__(self):
self.root = None #根
self.change = False #修正フラグ
###############
#回転操作, 修正操作
###############
def rotateL(self, n): #ノードnの左回転
r = n.right; rl = r.left
r.left = n; n.right = rl
r.left.calcSize()
r.calcSize()
return r
def rotateR(self, n):
l = n.left; lr = l.right
l.right = n; n.left = lr
l.right.calcSize()
l.calcSize()
return l
def rotateLR(self, n): #二重回転;左回転→右回転
n.left = self.rotateL(n.left)
return self.rotateR(n)
def rotateRL(self, n):
n.right = self.rotateR(n.right)
return self.rotateL(n)
def balanceL(self, n):
if not self.change: return n
h = n.height
if n.bias() == 2:
if n.left.bias() >= 0: n = self.rotateR(n)
else: n = self.rotateLR(n)
else: n.calcSize()
self.change = (h != n.height)
return n
def balanceR(self, n):
if not self.change: return n
h = n.height
if n.bias() == -2:
if n.right.bias() <= 0: n = self.rotateL(n)
else: n = self.rotateRL(n)
else: n.calcSize()
self.change = (h != n.height)
return n
###############
#Nodeの追加
###############
def insert(self, key): self.root = self.insert_sub(self.root, key)
def insert_sub(self, t, key): #新たなノードの挿入。初期位置は根。
if t is None:
self.change = True
return Node(key, 1)
if key < t.key:
t.left = self.insert_sub(t.left, key)
return self.balanceL(t)
elif key > t.key:
t.right = self.insert_sub(t.right, key)
return self.balanceR(t)
else:
self.change = False
return t
###############
#Nodeの探索
###############
def search(self, key, leastValue, largestValue):
t = self.root
lb, hb = leastValue, largestValue
while t:
if key < t.key:
hb = t.key
t = t.left
else:
lb = t.key
t = t.right
return lb, hb
def solve():
input = sys.stdin.readline
N = int(input())
P = [int(p) for p in input().split()]
pindex = dict()
for i, p in enumerate(P): pindex[p - 1] = i
L, R = dict(), dict()
L[pindex[N-1]] = -1
R[pindex[N-1]] = N
L[-1] = L[N] = -1
R[-1] = R[N] = N
Ans = 0
if N == 10 ** 5:
appeared = []
appeared.append(-1)
appeared.append(pindex[N - 1])
appeared.append(N)
for i in reversed(range(N - 1)):
pid = pindex[i]
mid = bisect(appeared, pindex[i])
L[pid], R[pid] = appeared[mid - 1], appeared[mid]
Ans += (i + 1) * ((pid - L[pid]) * (R[R[pid]] - R[pid]) + (R[pid] - pid) * (L[pid] - L[L[pid]]))
appeared.insert(mid, pindex[i])
R[L[pid]] = L[R[pid]] = pid
else:
Ans = 0
T = AVLTree()
T.insert(pindex[N-1])
for i in reversed(range(N-1)):
pid = pindex[i]
L[pid], R[pid] = T.search(pid, -1, N)
Ans += (i + 1) * ((pid - L[pid]) * (R[R[pid]] - R[pid]) + (R[pid] - pid) * (L[pid] - L[L[pid]]))
T.insert(pid)
R[L[pid]] = L[R[pid]] = pid
print(Ans)
return 0
if __name__ == "__main__":
solve()
```
No
| 10,578 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
Submitted Solution:
```
N = int(input())
P = list(map(int,input().split()))
sum = 0
for L in range(N-1):
S = sorted([P[L],P[L+1]])
sum += S[0]
for R in range(L+2,N):
if P[R] > S[1]:
S[0] = S[1]
S[1] = P[R]
elif P[R] > S[0]:
S[0] = P[R]
sum += S[0]
print(sum)
```
No
| 10,579 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
Submitted Solution:
```
class B():
def __init__(self,N):
self.N = N
self.node = [0]*(self.N+1)
self.cnt = 0
def add(self,x): # 要素 x を追加
self.cnt += 1
while x <= self.N:
self.node[x] += 1
x += x & -x
def delete(self,x): # 要素 x を削除
self.cnt -= 1
while x <= self.N:
self.node[x] -= 1
x += x & -x
def count(self,x): # x以下の要素数
tmp = 0
while x > 0:
tmp += self.node[x]
x -= x & -x
return tmp
def get_max(self):
return self.get_ith(self.cnt)
def get_ith(self,i): # i 番目に小さい要素を取得
NG = -1
OK = self.N+1
while OK-NG > 1:
mid = (OK+NG)//2
#print(OK,NG,self.count(mid))
if self.count(mid) >= i:
OK = mid
else:
NG = mid
return OK
def search_low(self,x): # x より小さい最大の要素
xcn = self.count(x)
NG = -1
OK = x
while OK-NG > 1:
mid = (OK+NG)//2
#print(OK,NG,self.count(mid))
if self.count(mid) >= xcn:
OK = mid
else:
NG = mid
return OK
def search_high(self,x): # x より大きい最小の要素
xcn = self.count(x)
NG = x
OK = self.N + 1
while OK-NG > 1:
mid = (OK+NG)//2
#print(OK,NG,self.count(mid))
if self.count(mid) > xcn:
OK = mid
else:
NG = mid
return OK
import sys
stdin = sys.stdin
ni = lambda: int(ns())
nl = lambda: list(map(int, stdin.readline().split()))
nm = lambda: map(int, stdin.readline().split())
ns = lambda: stdin.readline().rstrip()
n = ni()
p = nl()
q = [0]*(n+1)
for i in range(n):
q[p[i]] = i+1
ans = 0
b = B(n)
b.add(q[-1])
for i in range(n-1,0,-1):
v = q[i]
l1 = b.search_low(v)
r1 = b.search_high(v)
l2 = b.search_low(l1)
r2 = b.search_high(r1)
ans += i*((r1-v)*(l1-l2) + (v-l1)*(r2-r1))
b.add(v)
print(ans)
```
No
| 10,580 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
Submitted Solution:
```
#! /Library/Frameworks/Python.framework/Versions/3.7/bin/python3
N = int(input())
P = list(map(int, input().split()))
s = 0
for i in range(N):
count = 0
a1 = i
a2 = i
a3 = i
a4 = i
while a2 > 0:
a2 -= 1
if (P[i] < P[a2]):
a1 = a2
if a1 == 0:
count = 1
else:
while a1 > 0:
a1 -= 1
if (P[i] < P[a1]):
count += (a2 - a1)
while a3 < N-1:
a3 += 1
if (P[i] < P[a3]):
a4 = a3
if a4 == 0:
count = 1
else:
while a4 > 0:
a4 += 1
if (P[i] < P[a4]):
count += (a4 - a3)
sum += P[i] * count
print(str(sum))
```
No
| 10,581 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
"Correct Solution:
```
import sys
sys.setrecursionlimit(2 * 10 ** 5 + 5)
def dfs(v, p, links):
farthest_d = 0
farthest_v = v
for u in links[v]:
if u == p:
continue
res_d, res_v = dfs(u, v, links)
if res_d > farthest_d:
farthest_d = res_d
farthest_v = res_v
return farthest_d + 1, farthest_v
def solve(n, links):
if n == 1:
return True
d, v = dfs(0, -1, links)
d, v = dfs(v, -1, links)
if (d + 1) % 3 == 0:
return False
return True
n = int(input())
links = [set() for _ in [0] * n]
for line in sys.stdin:
a, b = map(int, line.split())
a -= 1
b -= 1
links[a].add(b)
links[b].add(a)
print('First' if solve(n, links) else 'Second')
```
| 10,582 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
"Correct Solution:
```
class Tree():
def __init__(self, n, decrement=1):
self.n = n
self.edges = [[] for _ in range(n)]
self.root = None
self.depth = [-1]*n
self.size = [1]*n # 部分木のノードの数
self.decrement = decrement
def add_edge(self, u, v):
u, v = u-self.decrement, v-self.decrement
self.edges[u].append(v)
self.edges[v].append(u)
def add_edges(self, edges):
for u, v in edges:
u, v = u-self.decrement, v-self.decrement
self.edges[u].append(v)
self.edges[v].append(u)
def set_root(self, root):
root -= self.decrement
self.root = root
self.par = [-1]*self.n
self.depth[root] = 0
self.order = [root] # 帰りがけに使う
next_set = [root]
while next_set:
p = next_set.pop()
for q in self.edges[p]:
if self.depth[q] != -1: continue
self.par[q] = p
self.depth[q] = self.depth[p]+1
self.order.append(q)
next_set.append(q)
for p in self.order[::-1]:
for q in self.edges[p]:
if self.par[p] == q: continue
self.size[p] += self.size[q]
def diameter(self, path=False):
# assert self.root is not None
u = self.depth.index(max(self.depth))
dist = [-1]*self.n
dist[u] = 0
prev = [-1]*self.n
next_set = [u]
while next_set:
p = next_set.pop()
for q in self.edges[p]:
if dist[q] != -1: continue
dist[q] = dist[p]+1
prev[q] = p
next_set.append(q)
d = max(dist)
if path:
v = w = dist.index(d)
path = [v+1]
while w != u:
w = prev[w]
path.append(w+self.decrement)
return d, v+self.decrement, u+self.decrement, path
else: return d
def heavy_light_decomposition(self):
"""
heavy edge を並べてリストにした物を返す (1-indexed if decrement=True)
"""
# assert self.root is not None
self.vid = [-1]*self.n
self.hld = [-1]*self.n
self.head = [-1]*self.n
self.head[self.root] = self.root
self.heavy_node = [-1]*self.n
next_set = [self.root]
for i in range(self.n):
""" for tree graph, dfs ends in N times """
p = next_set.pop()
self.vid[p] = i
self.hld[i] = p+self.decrement
maxs = 0
for q in self.edges[p]:
""" encode direction of Heavy edge into heavy_node """
if self.par[p] == q: continue
if maxs < self.size[q]:
maxs = self.size[q]
self.heavy_node[p] = q
for q in self.edges[p]:
""" determine "head" of heavy edge """
if self.par[p] == q or self.heavy_node[p] == q: continue
self.head[q] = q
next_set.append(q)
if self.heavy_node[p] != -1:
self.head[self.heavy_node[p]] = self.head[p]
next_set.append(self.heavy_node[p])
return self.hld
def lca(self, u, v):
# assert self.head is not None
u, v = u-self.decrement, v-self.decrement
while True:
if self.vid[u] > self.vid[v]: u, v = v, u
if self.head[u] != self.head[v]:
v = self.par[self.head[v]]
else:
return u + self.decrement
def path(self, u, v):
""" u-v 間の最短経路をリストで返す """
p = self.lca(u, v)
u, v, p = u-self.decrement, v-self.decrement, p-self.decrement
R = []
while u != p:
yield u+self.decrement
u = self.par[u]
yield p+self.decrement
while v != p:
R.append(v)
v = self.par[v]
for v in reversed(R):
yield v+self.decrement
def distance(self, u, v):
# assert self.head is not None
p = self.lca(u, v)
u, v, p = u-self.decrement, v-self.decrement, p-self.decrement
return self.depth[u] + self.depth[v] - 2*self.depth[p]
def find(self, u, v, x):
return self.distance(u,x)+self.distance(x,v)==self.distance(u,v)
def path_to_list(self, u, v, edge_query=False):
"""
パス上の頂点の集合を self.hld 上の開区間の集合として表す
ここで、self.hld は heavy edge を並べて数列にしたものである
"""
# assert self.head is not None
u, v = u-self.decrement, v-self.decrement
while True:
if self.vid[u] > self.vid[v]: u, v = v, u
if self.head[u] != self.head[v]:
yield self.vid[self.head[v]], self.vid[v] + 1
v = self.par[self.head[v]]
else:
yield self.vid[u] + edge_query, self.vid[v] + 1
return
def point(self, u):
return self.vid[u-self.decrement]
def subtree_query(self, u):
u -= self.decrement
return self.vid[u], self.vid[u] + self.size[u]
def draw(self):
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
for x in range(self.n):
for y in self.edges[x]:
G.add_edge(x + self.decrement, y + self.decrement)
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos)
plt.axis("off")
plt.show()
##################################################################################################
import sys
input = sys.stdin.readline
N = int(input())
T = Tree(N)
for _ in range(N-1):
x, y = map(int, input().split())
T.add_edge(x, y)
T.set_root(1)
print("Second" if (T.diameter()+1)%3==2 else "First")
```
| 10,583 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
"Correct Solution:
```
def getD(graph):
# search edge
origin=1
d = 0
queue = Queue()
for it in graph[origin]:
queue.enqueue((it, origin, d+1)) # next, coming from, depth
while queue.size() > 0:
leaf, origin, d = queue.dequeue()
for it in graph[leaf]:
if it != origin:
queue.enqueue((it, leaf, d+1)) # next, coming from, depth
# print(d, leaf)
# search D
origin=leaf
d = 0
queue = Queue()
for it in graph[origin]:
queue.enqueue((it, origin, d+1)) # next, coming from, depth
while queue.size() > 0:
leaf, origin, d = queue.dequeue()
for it in graph[leaf]:
if it != origin:
queue.enqueue((it, leaf, d+1)) # next, coming from, depth
# print(d, leaf)
return d
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.head = None
self.last = None
self._size = 0
def enqueue(self, data):
if self.last is None:
self.head = Node(data)
self.last = self.head
else:
self.last.next = Node(data)
self.last = self.last.next
self._size += 1
def dequeue(self):
if self.head is None:
return None
else:
to_return = self.head.data
self.head = self.head.next
self._size -= 1
if self._size == 0:
self.head = None
self.last = None
return to_return
def size(self):
return self._size
def inside(y,x,H,W):
if 0<=y<H and 0<=x<W:
return True
else:
return False
def addQueueIfPossible(new_y, new_x, new_val, data, queue):
if inside(new_y, new_x, H, W) and data[new_y][new_x]==-1:
data[new_y][new_x] = new_val
queue.enqueue((new_y, new_x, new_val))
return True
else:
return False
n = int(input())
graph = [[] for _ in range(n+1)]
for i in range(n-1):
a,b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
if n==1:
print('First')
else:
d = getD(graph)
if (d+2)%3==0:
print('Second')
else:
print('First')
```
| 10,584 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
"Correct Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)
def dfs(idx, con, visited):
visited[idx] = True
max_depth = 0
max_len = 0
depths = []
if idx >= len(con):
return max_depth, max_len
for v in con[idx]:
if v < len(visited) and not visited[v]:
max_d, max_l = dfs(v, con, visited)
max_len = max(max_len, max_l)
depths.append(max_d + 1)
if len(depths) > 0:
depths.sort(reverse=True)
max_depth = depths[0]
if len(depths) > 1:
max_len = max(max_len, depths[0] + depths[1])
else:
max_len = max(max_len, depths[0])
visited[idx] = False
return max_depth, max_len
def solve(N: int, A: "List[int]", B: "List[int]"):
con = [[] for _ in range(N)]
for i in range(len(A)):
a = A[i] - 1
b = B[i] - 1
con[a].append(b)
con[b].append(a)
#print(con)
visited = [False] * N
max_depth, max_len = dfs(0, con, visited)
#print(max_len)
if (max_len + 1) % 3 == 2:
ret = 'Second'
else:
ret = 'First'
print(ret)
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
a = [int()] * (N-1) # type: "List[int]"
b = [int()] * (N-1) # type: "List[int]"
for i in range(N-1):
a[i] = int(next(tokens))
b[i] = int(next(tokens))
solve(N, a, b)
if __name__ == '__main__':
main()
```
| 10,585 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
"Correct Solution:
```
from collections import defaultdict
N = int(input())
abList = [list(map(int, input().split())) for _ in range(N-1)]
# 木構造の関係リスト作成
treeDict = defaultdict(list)
for a, b in abList:
treeDict[a].append(b)
treeDict[b].append(a)
# コストの辞書と疑似キューを作成
costDict = defaultdict(int)
treeQ = set()
# 葉(端)のコストを1にし、隣接ノードをキューに格納
for node in treeDict:
if len(treeDict[node]) == 1:
costDict[node] = 1
treeQ.add(treeDict[node][0])
# 1つを除く隣接ノードにコストが設定されている(!= 0)場合、
# 隣接ノードの最大コスト + 1 でコストを設定し、コスト未設定のノードをキューに格納。
# 上記をキューに値が入らなくなるまで繰り返す。
node = 1
while(treeQ):
tQ = set()
costList = []
for node in treeQ:
if costDict[node] != 0: break
decidedFlg = True
cost = -1
qNode = -1
for nextNode in treeDict[node]:
nextCost = costDict[nextNode]
if nextCost == 0:
# 隣接ノードがコスト未設定ならキューに格納
# 隣接ノードが2つコスト未設定ならbreak
if not decidedFlg:
cost = -1
qNode = -1
break
decidedFlg = False
qNode = nextNode
else:
# コストが設定されていれば大きいコストで更新
cost = max(cost, nextCost + 1)
if cost != -1:
costList.append((node, cost))
if qNode != -1:
tQ.add(qNode)
for cost in costList:
costDict[cost[0]] = cost[1]
treeQ = tQ
# コストが設定されていないノードを頂点として直径を図る
firstLen, secondLen = 0, 0
for nextNode in treeDict[node]:
cost = costDict[nextNode]
if cost > firstLen:
secondLen = firstLen
firstLen = cost
elif cost > secondLen:
secondLen = cost
diameter = firstLen + secondLen + 1
ans = "First" if diameter % 3 != 2 else "Second"
print(ans)
```
| 10,586 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
"Correct Solution:
```
n,*L=map(int,open(0).read().split())
con=[[]for _ in range(n)]
for a,b in zip(*[iter(L)]*2):
con[a-1].append(b-1)
con[b-1].append(a-1)
dist=[-1]*n
dist[0]=0
farthest=0
q=[0]
while q:
cur=q.pop()
for nxt in con[cur]:
if dist[nxt]<0:
dist[nxt]=dist[cur]+1
if dist[farthest]<dist[nxt]:
farthest=nxt
q.append(nxt)
dist=[-1]*n
dist[farthest]=0
diameter=0
q=[farthest]
while q:
cur=q.pop()
for nxt in con[cur]:
if dist[nxt]<0:
dist[nxt]=dist[cur]+1
diameter=max(diameter,dist[nxt])
q.append(nxt)
print("Second" if diameter%3==1 else "First")
```
| 10,587 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
"Correct Solution:
```
#!/usr/bin/env python3
import sys
import heapq
INF = float("inf")
def argmax(a):
m, n = -(1 << 31), -1
for i, v in enumerate(a):
if m < v:
m, n = v, i
return m, n
# 無向グラフを仮定する。
class Graph(object):
def __init__(self, N):
self.N = N
self.V = list(range(N))
self.E = [[] for _ in range(N)]
def add_edge(self, edge):
"""辺を加える。edgeは(始点, 終点、重み)からなるリスト
重みがなければ、重み1とする。
"""
if len(edge) == 2:
edge.append(1)
elif len(edge) != 3:
print("error in add_edge")
pass
s, t, w = edge
self.E[s].append([t, w])
self.E[t].append([s, w]) # 無向グラフを仮定。逆向きにも辺を張る
pass
def shortestPath(g: Graph, s: int):
""" グラフgにおいて、始点sから各頂点への最短路を求める
引数
g: グラフ, s: 始点
返り値
dist: 始点からの距離が格納されたリスト
prev: 始点から最短経路で移動する場合、各頂点に至る前の頂点のリスト
"""
dist = [INF]*g.N
dist[s] = 0
prev = [None]*g.N
Q = []
heapq.heappush(Q, (dist[s], s))
while len(Q) > 0:
_, u = heapq.heappop(Q)
for v, w in g.E[u]:
if dist[v] > dist[u] + w:
dist[v] = dist[u] + w
prev[v] = u
heapq.heappush(Q, (dist[v], v))
return dist, prev
def tree_diameter(g):
# 木の直径を求める。
# ダイクストラ法を二回行う実装。
dist, prev = shortestPath(g, 0)
m, s = argmax(dist)
dist, prev = shortestPath(g, s)
return max(dist)
def solve(N: int, a: "List[int]", b: "List[int]"):
g = Graph(N)
for aa, bb in zip(a, b):
g.add_edge([aa-1, bb-1])
L = tree_diameter(g)
if L % 3 == 1:
print("Second")
else:
print("First")
return
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
a = [int()] * (N-1) # type: "List[int]"
b = [int()] * (N-1) # type: "List[int]"
for i in range(N-1):
a[i] = int(next(tokens))
b[i] = int(next(tokens))
solve(N, a, b)
if __name__ == '__main__':
main()
```
| 10,588 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
"Correct Solution:
```
from collections import defaultdict
import sys
input = sys.stdin.readline
N = int(input())
# 例外処理
if (N == 1):
print("First")
quit()
tree = defaultdict(set)
tree_main = defaultdict(set)
for i in range(N-1):
a, b = tuple(map(int, input().split()))
tree[a].add(b)
tree[b].add(a)
tree_main[a].add(b)
tree_main[b].add(a)
def longest_path(tree, from_node=1):
cnt = 1
nearest_nodes = list(tree[from_node])
while len(nearest_nodes) > 0:
for one_step_node in nearest_nodes:
for two_step_node in tree[one_step_node]:
if two_step_node != from_node:
tree[two_step_node].remove(one_step_node)
tree[two_step_node].add(from_node)
tree[from_node].add(two_step_node)
tree[from_node].remove(one_step_node)
cnt += 1
nearest_nodes = list(tree[from_node])
return one_step_node, cnt
far, _ = longest_path(tree)
_, n = longest_path(tree_main, far)
print("Second" if n % 3 == 2 else "First")
```
| 10,589 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
n = int(input())
g = [[] for _ in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
g[a - 1].append(b - 1)
g[b - 1].append(a - 1)
s = [0]
d = [-1] * n
d[0] = 0
while s:
p = s.pop()
for node in g[p]:
if d[node] == -1:
s.append(node)
d[node] = d[p] + 1
idx = 0
for i in range(n):
if d[i] > d[idx]:
idx = i
s = [idx]
d = [-1] * n
d[idx] = 0
while s:
p = s.pop()
for node in g[p]:
if d[node] == -1:
s.append(node)
d[node] = d[p] + 1
m = 0
for i in range(n):
if d[i] > m:
m = d[i]
if m % 3 == 1:
print('Second')
else:
print('First')
```
Yes
| 10,590 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
n = int(input())
link = [[] for _ in range(n)]
for i in range(n-1):
a,b = list(map(int,input().split()))
link[a-1].append(b-1)
link[b-1].append(a-1)
from collections import deque
Q = deque()
Q.append([0,0])
visited=[-1]*n
visited[0]=0
mx_dist=0
mx_ind=0
while Q:
now,cnt = Q.popleft()
for nxt in link[now]:
if visited[nxt]!=-1:
continue
visited[nxt]=cnt+1
Q.append([nxt,cnt+1])
if mx_dist < cnt+1:
mx_dist=cnt+1
mx_ind = nxt
Q = deque()
Q.append([mx_ind,0])
visited=[-1]*n
visited[mx_ind]=0
mx_dist=0
while Q:
now,cnt = Q.popleft()
for nxt in link[now]:
if visited[nxt]!=-1:
continue
visited[nxt]=cnt+1
Q.append([nxt,cnt+1])
if mx_dist < cnt+1:
mx_dist=cnt+1
mx_ind = nxt
if (mx_dist-1)%3==0:
print("Second")
else:
print("First")
```
Yes
| 10,591 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
from collections import defaultdict as dd
N = int(input())
Es = dd(dict)
for _ in range(N-1):
a, b = map(int, input().split())
Es[a-1][b-1] = Es[b-1][a-1] = 1
# もっとも長いパスを見つける
q = [0]
visited = [False] * N
last = None
while q:
nq = []
for node in q:
last = node
visited[node] = True
for to in Es[node]:
if visited[to]:
continue
nq.append(to)
q = nq
q = [last]
visited = [False] * N
n = 0
while q:
n += 1
nq = []
for node in q:
visited[node] = True
for to in Es[node]:
if visited[to]:
continue
nq.append(to)
q = nq
if n % 3 == 2:
print('Second')
else:
print('First')
```
Yes
| 10,592 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
N=int(input())
if N==1:
print("First")
exit()
L=[[]for i in range(N+1)]
for i in range(N-1):
a,b=map(int,input().split())
L[a].append(b)
L[b].append(a)
#print(L)
C=[0 for i in range(N+1)]
D=[10000000 for i in range(N+1)]
D[1]=0
Q=[1]
for i in range(10**6):
if i==N:
break
for j in L[Q[i]]:
if D[j]==10000000:
Q.append(j)
D[j]=D[Q[i]]+1
#print(D)
F=0
cnt=0
for i in range(1,N+1):
if D[i]>cnt:
cnt=D[i]
F=i
d=[10000000 for i in range(N+1)]
d[F]=0
Q=[F]
for i in range(10**6):
if i==N:
break
for j in L[Q[i]]:
if d[j]==10000000:
Q.append(j)
d[j]=d[Q[i]]+1
#print(d)
ans=0
for i in range(1,N+1):
if d[i]>ans:
ans=d[i]
if ans%3==1:
print("Second")
else:
print("First")
```
Yes
| 10,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
N = int(input())
src = [tuple(map(lambda x:int(x)-1,input().split())) for i in range(N-1)]
es = [[] for i in range(N)]
for a,b in src:
es[a].append(b)
es[b].append(a)
if all(len(e)<=2 for e in es):
print('First' if N%2 else 'Second')
exit()
assert False
```
No
| 10,594 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
print(["Second","First"][int(input())%2])
```
No
| 10,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
N = int(input())
S = list(input())
ans = N % 2
if ans == 0:
print("Secound")
else:
print("First")
```
No
| 10,596 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Submitted Solution:
```
def s(x,v,d):
r=[d,v]
for u in g[v]:
if u!=x:
t=s(v,u,d+1)
if r[0]<t[0]:r=t
return r
n,*t=map(int,open(0).read().split())
g=[set()for _ in range(n+1)]
for a,b in zip(t[::2],t[1::2]):
g[a].add(b)
g[b].add(a)
print('SFeicrosntd'[s(0,s(0,1,0)[1],0)[0]%3!=1::2])
```
No
| 10,597 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi has an N \times N grid. The square at the i-th row and the j-th column of the grid is denoted by (i,j). Particularly, the top-left square of the grid is (1,1), and the bottom-right square is (N,N).
An integer, 0 or 1, is written on M of the squares in the Takahashi's grid. Three integers a_i,b_i and c_i describe the i-th of those squares with integers written on them: the integer c_i is written on the square (a_i,b_i).
Takahashi decides to write an integer, 0 or 1, on each of the remaining squares so that the condition below is satisfied. Find the number of such ways to write integers, modulo 998244353.
* For all 1\leq i < j\leq N, there are even number of 1s in the square region whose top-left square is (i,i) and whose bottom-right square is (j,j).
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq min(5 \times 10^4,N^2)
* 1 \leq a_i,b_i \leq N(1\leq i\leq M)
* 0 \leq c_i \leq 1(1\leq i\leq M)
* If i \neq j, then (a_i,b_i) \neq (a_j,b_j).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
:
a_M b_M c_M
Output
Print the number of possible ways to write integers, modulo 998244353.
Examples
Input
3 3
1 1 1
3 1 0
2 3 1
Output
8
Input
4 5
1 3 1
2 4 0
2 3 1
4 2 1
4 4 1
Output
32
Input
3 5
1 3 1
3 3 0
3 1 0
2 3 1
3 2 1
Output
0
Input
4 8
1 1 1
1 2 0
3 2 1
1 4 0
2 1 1
1 3 0
3 4 1
4 4 1
Output
4
Input
100000 0
Output
342016343
"Correct Solution:
```
from collections import Counter
import sys
MOD = 998244353
n, m = map(int, input().split())
d = Counter()
ans = 1
d_num = 0
def kaijou(a, n):
x = 1
while n > 0:
if n & 1 == 1:
x = (x * a) % MOD
a = (a ** 2) % MOD
n >>= 1
return x
for _ in range(m):
a, b, c = map(int, input().split())
d[(a-1) * n + b - 1] = c
if abs(a-b) >= 3:
if (b-1) * n + a - 1 not in d:
d_num += 1
d[(b-1) * n + a - 1] = c
elif d[(b-1) * n + a - 1] != d[(a-1) * n + b - 1]:
print(0)
sys.exit()
ans = (ans * kaijou(2, ((n-2) * (n-3) // 2) - d_num)) % MOD
e = 0
if 0 not in d:
e += 1
if 1 not in d:
e += 1
if n not in d:
e += 1
if n+1 not in d:
e += 1
if e == 0 and n*0+0 in d:
if (d[n*0+0] + d[n+1]) % 2 != (d[1] + d[n]) % 2:
ans *= 0
if e == 1 and n+1 not in d and n*0+0 in d:
d[n+1] = (d[1] + d[n]) % 2 - d[n*0+0]
ans = (ans * (2 ** max(0, e-1))) % MOD
for i in range(n-2):
e = 0
if n*i+i+2 not in d:
e += 1
if n*i+i+2*n not in d:
e += 1
if e == 0 and n*i+i+n+1 in d:
if (d[n*i+i+2] + d[n*i+i+n+1] + d[n*i+i+2*n]) % 2 != 0:
ans *= 0
if e == 0 and n*i+i+n+1 not in d:
d[n*i+i+n+1] = (d[n*i+i+2] + d[n*i+i+n*2]) % 2
ans = (ans * 499122177) % MOD
ans = (ans * (2 ** max(0, e-1))) % MOD
e = 0
if n*(i+1)+i+2 not in d:
e += 1
if n*(i+1)+i+1+n not in d:
e += 1
if n*(i+1)+i+n+2 not in d:
e += 1
if e == 0 and n*(i+1)+i+1 in d:
if (d[n*(i+1)+i+1] + d[n*(i+1)+i+n+2]) % 2 != (d[n*(i+1)+i+2] + d[n*(i+1)+i+1+n]) % 2:
ans *= 0
if e == 0 and n*(i+1)+i+1 not in d:
ans = (ans * 499122177) % MOD
if e == 1 and n*(i+1)+i+2+n not in d and n*(i+1)+i+1 in d:
d[n*(i+1)+i+2+n] = (d[n*(i+1)+i+2] + d[n*(i+1)+i+1+n]) % 2 - d[n*(i+1)+i+1]
ans = (ans * (2 ** max(0, e-1))) % MOD
print(ans)
```
| 10,598 |
Provide a correct Python 3 solution for this coding contest problem.
Takahashi has an N \times N grid. The square at the i-th row and the j-th column of the grid is denoted by (i,j). Particularly, the top-left square of the grid is (1,1), and the bottom-right square is (N,N).
An integer, 0 or 1, is written on M of the squares in the Takahashi's grid. Three integers a_i,b_i and c_i describe the i-th of those squares with integers written on them: the integer c_i is written on the square (a_i,b_i).
Takahashi decides to write an integer, 0 or 1, on each of the remaining squares so that the condition below is satisfied. Find the number of such ways to write integers, modulo 998244353.
* For all 1\leq i < j\leq N, there are even number of 1s in the square region whose top-left square is (i,i) and whose bottom-right square is (j,j).
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq min(5 \times 10^4,N^2)
* 1 \leq a_i,b_i \leq N(1\leq i\leq M)
* 0 \leq c_i \leq 1(1\leq i\leq M)
* If i \neq j, then (a_i,b_i) \neq (a_j,b_j).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1 c_1
:
a_M b_M c_M
Output
Print the number of possible ways to write integers, modulo 998244353.
Examples
Input
3 3
1 1 1
3 1 0
2 3 1
Output
8
Input
4 5
1 3 1
2 4 0
2 3 1
4 2 1
4 4 1
Output
32
Input
3 5
1 3 1
3 3 0
3 1 0
2 3 1
3 2 1
Output
0
Input
4 8
1 1 1
1 2 0
3 2 1
1 4 0
2 1 1
1 3 0
3 4 1
4 4 1
Output
4
Input
100000 0
Output
342016343
"Correct Solution:
```
from collections import Counter
import sys
MOD = 998244353
n, m = map(int, input().split())
d = Counter()
ans = 1
d_num = 0
def k(a, n):
x = 1
while n > 0:
if n&1 == 1:
x = (x*a) % MOD
a = (a**2) % MOD
n >>= 1
return x
for _ in range(m):
a, b, c = map(int, input().split())
d[(a-1)*n+b-1] = c
if abs(a-b) >= 3:
if (b-1)*n+a-1 not in d:
d_num += 1
d[(b-1)*n+a-1] = c
elif d[(b-1)*n+a-1] != d[(a-1)*n+b-1]:
print(0)
sys.exit()
ans = (ans*k(2, ((n-2)*(n-3)//2)-d_num))%MOD
e = 0
if 0 not in d:
e+=1
if 1 not in d:
e+=1
if n not in d:
e+=1
if n+1 not in d:
e+=1
if e == 0 and n*0+0 in d:
if (d[n*0+0]+d[n+1])%2!=(d[1]+d[n]) % 2:
ans *= 0
if e == 1 and n+1 not in d and n*0+0 in d:
d[n+1] = (d[1]+d[n])%2-d[n*0+0]
ans = (ans*(2**max(0, e-1))) % MOD
for i in range(n-2):
e = 0
if n*i+i+2 not in d:
e += 1
if n*i+i+2*n not in d:
e += 1
if e == 0 and n*i+i+n+1 in d:
if (d[n*i+i+2] + d[n*i+i+n+1] + d[n*i+i+2*n]) % 2 != 0:
ans *= 0
if e == 0 and n*i+i+n+1 not in d:
d[n*i+i+n+1] = (d[n*i+i+2] + d[n*i+i+n*2]) % 2
ans = (ans*499122177) % MOD
ans = (ans*(2 ** max(0, e-1))) % MOD
e=0
if n*(i+1)+i+2 not in d:
e += 1
if n*(i+1)+i+1+n not in d:
e += 1
if n*(i+1)+i+n+2 not in d:
e += 1
if e == 0 and n*(i+1)+i+1 in d:
if (d[n*(i+1)+i+1]+d[n*(i+1)+i+n+2]) % 2 != (d[n*(i+1)+i+2]+d[n*(i+1)+i+1+n])%2:
ans *= 0
if e == 0 and n*(i+1)+i+1 not in d:
ans = (ans*499122177) % MOD
if e == 1 and n*(i+1)+i+2+n not in d and n*(i+1)+i+1 in d:
d[n*(i+1)+i+2+n]=(d[n*(i+1)+i+2]+d[n*(i+1)+i+1+n])%2-d[n*(i+1)+i+1]
ans = (ans*(2**max(0, e-1))) % MOD
print(ans)
```
| 10,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.