text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n — the number of techniques that the wrestlers have used (1 ≤ n ≤ 2·105).
The following n lines contain integer numbers ai (|ai| ≤ 109, ai ≠ 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Submitted Solution:
```
n = int(input())
player1 = []
player2 = []
arr = []
while n:
n -= 1
a = int(input())
arr.append(a)
if a > 0:
player1.append(a)
else:
player2.append(-a)
if sum(player1) != (sum(player2)):
if sum(player1) > (sum(player2)):
print('first')
else:
print('second')
elif player1 != player2:
if player2 > player1:
print('second')
else:
print('first')
else:
if arr[-1] > 0:
print('first')
else:
print('second')
```
Yes
| 2,000 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n — the number of techniques that the wrestlers have used (1 ≤ n ≤ 2·105).
The following n lines contain integer numbers ai (|ai| ≤ 109, ai ≠ 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Submitted Solution:
```
from sys import stdin
n=int(stdin.readline())
first,second,sum1,sum2,last='','',0,0,0
for i in range(n):
x=int(stdin.readline())
if x>0:first+=str(x);sum1+=x
else:second+=str(-x);sum2+=(-x)
last=x
if sum1>sum2:print('first')
elif sum1<sum2:print('second')
else:
if first>second:print('first')
elif first<second:print('second')
else:
if last>0:print('first')
else:print('second')
```
No
| 2,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n — the number of techniques that the wrestlers have used (1 ≤ n ≤ 2·105).
The following n lines contain integer numbers ai (|ai| ≤ 109, ai ≠ 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Submitted Solution:
```
def main(n,a):
x = [i for i in a if i >= 0]
y = [-i for i in a if i < 0]
print("X: ",x)
print("Y: ",y)
if sum(x)!=sum(y):
winner = sum(y) > sum(x)
else:
winner = [j>i for i,j in zip(x,y) if j!=i]
if winner != []:
winner = winner[0]
else:
winner = a[-1] < 0
print(["first","second"][winner])
def main_input():
n = int(input())
a = [int(input()) for i in range(n)]
main(n,a)
if __name__ == "__main__":
main_input()
#main(5,[1,2,-3,-4,3])
#main(3,[-1,-2,3])
#main(2,[4,-4])
#main(7,[1,2,-3,4,5,-6,7])
```
No
| 2,002 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n — the number of techniques that the wrestlers have used (1 ≤ n ≤ 2·105).
The following n lines contain integer numbers ai (|ai| ≤ 109, ai ≠ 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Submitted Solution:
```
"""
Template written to be used by Python Programmers.
Use at your own risk!!!!
Owned by adi0311(rating - 5 star at CodeChef and Specialist at Codeforces).
"""
import sys
import bisect
import heapq
from math import *
from collections import defaultdict as dd # defaultdict(<datatype>) Free of KeyError.
from collections import deque # deque(list) append(), appendleft(), pop(), popleft() - O(1)
from collections import Counter as c # Counter(list) return a dict with {key: count}
from itertools import combinations as comb
from bisect import bisect_left as bl, bisect_right as br, bisect
# sys.setrecursionlimit(2*pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(var)
def l(): return list(map(int, data().split()))
def sl(): return list(map(str, data().split()))
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [[val for i in range(n)] for j in range(m)]
n = int(data())
first, second = [], []
f, s = 0, 0
for i in range(n):
a = int(data())
if a < 0:
second.append(abs(a))
s += abs(a)
continue
first.append(a)
f += a
if s > f:
out("second")
exit()
if f > s:
out("first")
exit()
for i in range(0, min(len(first), len(second))):
if first[i] > second[i]:
out("first")
exit()
if second[i] > first[i]:
out("second")
exit()
if len(first) > len(second):
out("first")
exit()
out("second")
```
No
| 2,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n — the number of techniques that the wrestlers have used (1 ≤ n ≤ 2·105).
The following n lines contain integer numbers ai (|ai| ≤ 109, ai ≠ 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Submitted Solution:
```
import sys
a, b = [], []
for _ in range(int(sys.stdin.readline())):
x = int(sys.stdin.readline())
if x > 0:
a.append(x)
else:
b.append(-x)
print("first" if a > b else "second")
```
No
| 2,004 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Tags: constructive algorithms, strings
Correct Solution:
```
s, t = input(), input()
for i in range(len(s)):
if s[i] == 'z':
continue
c = chr(ord(s[i]) + 1)
str = s[0:i] + c + ('a' * (len(s) - i - 1));
if (str < t) :
print(str)
exit();
print("No such string")
```
| 2,005 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Tags: constructive algorithms, strings
Correct Solution:
```
# In case of length of s and t equal 1
# Calculate difference between s and t
# If difference is larger than 1
# Print next alphabet character in ASCII table
# Else
# Print 'No such string'
# Else
# Create a new string which is a clone of s
# Loop from start to end of both string s and t
# Calculate absolute difference between s[i] and t[i]
# If difference is larger than or equal to 0
# Identify next alphabet character
# If s[i] equal to 'z'
# Replace current character of clone string with 'a'
# Else
# Replace current character of clone string with next alphabet character in ASCII table
# Compare clone string with s and t
# If clone string is larger than s and smaller than t
# Print clone string
# Exit from program
#
# If there is no such string is printed while looping
# Print 'No such string'
s = input()
t = input()
length = len(s)
if length == 1:
dist = abs(ord(t) - ord(s))
if dist > 1:
print(chr(ord(s) + 1))
else:
print('No such string')
else:
s_clone = list(s)
for i in range(length - 1, -1, -1):
dist = abs(ord(t[i]) - ord(s[i]))
if dist >= 0:
if s[i] == 'z':
s_clone[i] = 'a'
else:
s_clone[i] = chr(ord(s[i]) + 1)
if ''.join(s_clone) > s and ''.join(s_clone) < t:
print(''.join(s_clone))
exit()
print('No such string')
```
| 2,006 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Tags: constructive algorithms, strings
Correct Solution:
```
s = input()
t = input()
s = [i for i in s]
t = [i for i in t]
i = len(s)-1
while(i>=0):
if(s[i]=='z'):
s[i] = 'a'
else:
a = ord(s[i])+1
s[i] = chr(a)
break
i -= 1
s = ''.join(s)
t = ''.join(t)
if(s>=t):
print('No such string')
else:
print(s)
```
| 2,007 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Tags: constructive algorithms, strings
Correct Solution:
```
# http://codeforces.com/problemset/problem/169/A
# A. Chores
def read_input():
a = input()
b = input()
return (a, b)
def do_middle_string(a, b):
c = list(a)
for i in range(len(c) - 1, -1, -1):
# print(i)
if c[i] == 'z':
c[i] = 'a'
else:
c[i] = chr(ord(c[i]) + 1)
break
c = "".join(c)
if a >= c or b <= c:
return None
return c
def main():
a, b = read_input()
result = do_middle_string(a, b)
print(result if result else "No such string")
if __name__ == '__main__':
main()
```
| 2,008 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Tags: constructive algorithms, strings
Correct Solution:
```
s = input()
t = input()
index = len(s)-1
y = ord("z")
while index >= 0:
x = ord(s[index])
if x < y:
s = s[0:index]+chr(x+1)+"a"*(len(t)-index-1)
break
index -=1
if s == t:
print("No such string")
else:
print(s)
```
| 2,009 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Tags: constructive algorithms, strings
Correct Solution:
```
s = input()
t = input()
k = 1
stri = ""
for i in s[::-1]:
m= ord(i) + k
if m> 122:
k = 1
stri += "a"
else:
k= 0
stri += chr(m)
if stri[::-1] == t:
print("No such string")
else:
print(stri[::-1])
```
| 2,010 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Tags: constructive algorithms, strings
Correct Solution:
```
s = list(input())
t = list(input())
for i in range(len(s) - 1, -1, -1):
if s[i] == 'z':
s[i] = 'a'
else:
s[i] = chr(ord(s[i]) + 1)
break
print(''.join(s) if s < t else "No such string")
```
| 2,011 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Tags: constructive algorithms, strings
Correct Solution:
```
s = input().strip()
t = input().strip()
r = list(s)
for i in range(len(s)-1, -1, -1):
if s[i] == 'z':
r[i] = 'a'
else:
r[i] = chr(ord(s[i]) + 1)
break
r = ''.join(r)
if t == r:
print("No such string")
else:
print(r)
```
| 2,012 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Tags: constructive algorithms, strings
Correct Solution:
```
from __future__ import print_function
# python 3 default
def main():
s = list(raw_input())
t = list(raw_input())
# map to ascii code
s_num = map(ord, s)
t_num = map(ord, t)
s_plus1 = list(s_num)
# z = 122
for i in range(len(s)-1, -1, -1):
s_plus1[i] += 1
if s_plus1[i] == 123: # z -> a
s_plus1[i] = 97 # a
else:
break
# check if splus1 < t
for i in range(len(s)):
if s_plus1[i] < t_num[i]:
print(''.join(map(chr, s_plus1)))
return 0
print('No such string')
return 1
if __name__ == '__main__':
main()
```
| 2,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Submitted Solution:
```
s = str(input())
t = str(input())
r = ""
l = len(s)
for i in range(l):
if s[i] == t[i]:
r += s[i]
continue
else:
if ord(s[i]) + 1 < ord(t[i]):
r += chr(ord(s[i])+1)
r += "a"*(l - len(r))
print(r)
exit()
else:
x = r
y = r
x += s[i]
x += "z"*(l - len(x))
y += t[i]
y += "a"*(l - len(y))
if x == s:
if y == t:
print("No such string")
exit()
else:
print(y)
exit()
else:
print(x)
exit()
```
Yes
| 2,014 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Submitted Solution:
```
def f(a,b):
if a==b:return False
if ord(a[0])<ord(b[0]):return True
if ord(a[0])>ord(b[0]):return False
return f(a[1:],b[1:])
def g(a):
if a[-1]=='z':return g(a[:-1])+'a'
return a[:-1]+chr(ord(a[-1])+1)
a=g(input())
b=input()
print(a if f(a,b)else'No such string')
```
Yes
| 2,015 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Submitted Solution:
```
s = input()
t = input()
fi = s
ok = False
for i in range(len(s) - 1, -1, -1):
if s[i] == 'z': continue
tm = len(s)
s = s[:i] + chr(ord(s[i]) + 1)
for j in range(i + 1, tm):
s += 'a'
if fi < s and s < t:
print(s)
exit()
print("No such string")
```
Yes
| 2,016 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Submitted Solution:
```
u = input()
v = input()
z, n = 1001, len(u)
for i in range(n):
if u[i] != v[i]:
z = i
break
if z > 1000:
print('No such string')
elif ord(v[z]) - ord(u[z]) < 2:
x, y = 1001, 0
for i in range(z+1,n):
if u[i] != 'z':
x, y = i, 1
break
if v[i] != 'a':
x, y = i, 2
break
if y < 1:
print('No such string')
else:
print(u[:z], end = '')
if y == 1:
print(u[z:x] + 'z' + u[x+1:n])
else:
print(v[z:x] + 'a' + v[x+1:n])
else:
print(u[:z] + chr(ord(u[z]) + 1) + u[z+1:n])
```
Yes
| 2,017 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Submitted Solution:
```
s = input()
t = input()
if len(s) == 1 and len(t) == 1:
dist = ord(t) - ord(s)
if dist <= 1:
print('No such string')
else:
print(chr(ord(s) + 1))
else:
s_arr = list(s)
t_arr = list(t)
result = ''
sum = 0
for i in range(len(s)):
dist = abs(ord(t[i]) - ord(s[i]))
sum += dist
if dist > 1:
next_letter = chr(ord(s[i]) + 1)
if next_letter > 'z':
next_letter = 'a'
result += ''.join(next_letter)
else:
result += ''.join(s[i])
if sum <= 1:
print('No such string')
else:
print(result)
```
No
| 2,018 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Submitted Solution:
```
from string import ascii_lowercase
m = {v: i for i, v in enumerate(ascii_lowercase)}
a = input()
b = input()
s, ans = "", False
for i in range(len(a)):
if (m[b[i]] - m[a[i]] > 1):
s += ascii_lowercase[m[a[i]] + 1] + a[i+1:]
ans = True
break
elif (m[b[i]] - m[a[i]] == 1):
s += a[i]
all_z = True
for c in a[i+1:]:
if c != 'z':
s += ascii_lowercase[m[c]+1]
all_z = False
else:
s += c
if not all_z:
ans = True
break
else:
s += a[i]
if ans:
print(s)
else:
print("No such string")
```
No
| 2,019 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Submitted Solution:
```
a=input()
b=input()
l=len(a)
p=0
s=""
for i in range(l):
if ord(b[i])-ord(a[i])>1:
s=s+chr(ord(a[i])+1)
else:
p=1
break
if p!=1:
print(s)
else:
print("No such string")
```
No
| 2,020 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t.
Let's help Vitaly solve this easy problem!
Input
The first line contains string s (1 ≤ |s| ≤ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.
The second line contains string t (|t| = |s|), consisting of lowercase English letters.
It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.
Output
If the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).
If such string exists, print it. If there are multiple valid strings, you may print any of them.
Examples
Input
a
c
Output
b
Input
aaa
zzz
Output
kkk
Input
abcdefg
abcdefh
Output
No such string
Note
String s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Submitted Solution:
```
line0 = input()
line1 = input()
numData0 = []
numData1 = []
c = 0
def PlayNow(arg):
for i in range(len(arg)):
print(chr(arg[i]), end='')
for i in range(len(line0)):
numData0.append(ord(line0[i]))
numData1.append(ord(line1[i]))
for i in range(len(line0)):
if (numData1[i] - numData0[i]) >= 1:
if (numData1[i] - numData0[i]) >= 2:
numData0[i] += 1
PlayNow(numData0)
c = 1
break
else:
for x in range(i+1, len(line0)):
if numData0[x] < ord('z'):
numData0[x] += 1
PlayNow(numData0)
c = 1
break
if c is 1:
break
if c is 0:
print('No such string')
```
No
| 2,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Tags: implementation, strings
Correct Solution:
```
n = int(input())
t = input()
if n > len(set(t)):
print('NO')
else:
pos = [0 for _ in range(len(t)+1)]
dis = set()
c = 0
for i in range(len(t)):
if t[i] not in dis:
dis.add(t[i])
pos[c] = i
c = c+1
pos[n] = len(t)
print('YES')
for i in range(n):
print(t[pos[i]:pos[i+1]])
```
| 2,022 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Tags: implementation, strings
Correct Solution:
```
import sys
k = int(input())
q = input()
if len(set(q)) < k:
print('NO')
else:
first = ''
s = ''
print('YES')
for i in range(len(q)):
if q[i] not in first:
if len(s) > 0:
print(s)
s =''
s = q[i]
first += q[i]
k -= 1
if k == 0:
s += q[i+1:len(q)]
print(s)
break
else:
s += q[i]
```
| 2,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Tags: implementation, strings
Correct Solution:
```
k = int(input())
q = input()
b = []
for x in range(len(q)):
if q[0: x + 1].count(q[x]) == 1:
b.append(q[x])
else:
b[-1] += q[x]
if len(b) >= k:
print("YES")
for x in range(k-1):
print(b[x])
for y in range(k, len(b)):
b[k-1] += b[y]
print(b[k-1])
if len(b) < k:
print("NO")
```
| 2,024 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Tags: implementation, strings
Correct Solution:
```
n = int(input())
s = list(str(input()))
dif = list(dict.fromkeys(s))
ans = []
if(n==1):
print('YES')
print(''.join(s))
else:
cur = 0
pnt = 0
lst = s[0]
cnt = 1
used = [s[0]]
for i in range(len(s)):
if(s[i] not in used):
if(i==len(s)-1 or cnt== n-1):
ans.append(''.join(s[cur:i]))
ans.append(''.join(s[i:]))
break
else:
ans.append(''.join(s[cur:i]))
cur = int(i)
cnt+=1
used.append(s[i])
if(len(ans)==n):
print('YES')
for i in range(n):
print(ans[i])
else:
print('NO')
```
| 2,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Tags: implementation, strings
Correct Solution:
```
n = int(input())
s = input()
arr = []
for i in range(len(s)):
if s[i] not in s[:i]:
arr.append(i)
if (len(arr) < n):
print('NO')
exit()
print('YES')
for i in range(n - 1):
print(s[arr[i] : arr[i + 1]])
if len(arr) >= n:
print(s[arr[n - 1] : len(s)])
```
| 2,026 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Tags: implementation, strings
Correct Solution:
```
k = int(input())
s = input()
ans = []
cur = ""
se = set()
for i in range(len(s)):
if s[i] not in se:
if len(cur) > 0:
ans.append(cur)
cur = ""
cur = s[i]
se.add(s[i])
else:
cur += s[i]
if cur:
ans.append(cur)
l = len(ans)
if len(ans) < k:
print("NO")
else:
print("YES")
for i in range(k, len(ans)):
ans[k-1] += ans[i]
print("\n".join(ans[:k]))
```
| 2,027 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Tags: implementation, strings
Correct Solution:
```
# 544A
# O(|q|) time
# O(|q|) space
__author__ = 'artyom'
# SOLUTION
def main():
b = [False] * 26
n = read()
s = read(0)
if n == 1:
return ['YES', s]
tokens = ['YES']
token = ''
i = 1
p = 0
for c in s:
if not b[ord(c) - 97]:
b[ord(c) - 97] = True
if token:
tokens.append(token)
i += 1
if i == n:
break
else:
token = ''
token += c
p += 1
tokens.append(s[p:])
if len(tokens) - 1 < n:
return 'NO'
return tokens
# HELPERS
def read(mode=1, size=None):
# 0: String
# 1: Integer
# 2: List of strings
# 3: List of integers
# 4: Matrix of integers
if mode == 0: return input().strip()
if mode == 1: return int(input().strip())
if mode == 2: return input().strip().split()
if mode == 3: return list(map(int, input().strip().split()))
a = []
for _ in range(size):
a.append(read(3))
return a
def write(s="\n"):
if s is None: s = ''
if isinstance(s, tuple) or isinstance(s, list): s = '\n'.join(map(str, s))
s = str(s)
print(s, end="\n")
write(main())
```
| 2,028 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Tags: implementation, strings
Correct Solution:
```
import sys
import math
import bisect
def solve(s, k):
d = dict()
for i in range(len(s)):
if s[i] not in d:
d[s[i]] = i
A = list(d.values())
#print('s: %s, k: %d, A: %s' % (s, k, A))
if len(A) < k:
return None
B = []
for i in range(k):
if i == k - 1:
B.append(s[A[i]:])
else:
B.append(s[A[i]:A[i+1]])
return B
def main():
k = int(input())
s = input()
ans = solve(s, k)
if ans:
print('YES')
for a in ans:
print(a)
else:
print('NO')
if __name__ == "__main__":
main()
```
| 2,029 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Submitted Solution:
```
n = int(input())
q = input()
if n > len(q):
print("NO")
else:
if n == 1:
print("YES")
print(q)
else:
arr = [0]*len(q)
for x in range(0, len(q)):
arr[x] = q[x]
con = arr[0]
res = []
count = 0
x = 0
used = ["-1"]*len(q)
used[0] = con
usedCount = 0
while count < n-1:
if x + 1 < len(arr) and (arr[x] == arr[x+1] or arr[x+1] in used):
con += arr[x+1]
x += 1
else:
res.append(con)
usedCount += 1
if x + 1 < len(arr):
used[usedCount] = arr[x+1]
con = arr[x+1]
count +=1
x += 1
totalLen = 0
for x in range(0, count):
totalLen += len(res[x])
res.append(q[totalLen:])
for x in res:
if x.isspace() or x == "":
res.remove(x)
res1 = set(res)
length = 0
for each in res1:
length += 1
if res[len(res) - 1] == "-1" or length < n:
print("NO")
else:
print("YES")
for x in res:
print(x)
```
Yes
| 2,030 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Submitted Solution:
```
n = int(input())
s = input()
a = []
if len(s) < n:
print ("NO")
else:
for i in s:
if len(a) == n:
break
if i in a:
continue
else:
a.append(i)
l = []
for i in range(len(a)):
if i == len(a)-1:
l.append(s[s.index(a[i]):])
else:
l.append(s[s.index(a[i]):s.index(a[i+1])])
if len(a) == n:
print ("YES")
for i in l:
print (i)
else:
print ("NO")
```
Yes
| 2,031 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Submitted Solution:
```
K = int(input())
used = set()
S = input()
indexes = []
ind = 0
while len(indexes) < K and ind < len(S):
if S[ind] not in used:
indexes += [ind]
used.add(S[ind])
ind += 1
if len(indexes) < K:
print("NO")
else:
print("YES")
for i, v in enumerate(indexes):
if i == len(indexes) - 1:
print(S[v:])
else:
print(S[v:indexes[i+1]])
```
Yes
| 2,032 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Submitted Solution:
```
r = lambda : map(int,input().split())
import sys
n = int(input())
s = input()
q = set()
if n>len(set(s)) :
print('NO')
else :
print('YES')
k = 0
ans = []
for i in range(len(s)) :
if k==n : break
if s[i] not in q :
ans.append(i)
q.add(s[i])
k+=1
ans.append(len(s))
for i in range(len(ans)-1) :
print(s[ans[i]:ans[i+1]])
```
Yes
| 2,033 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Submitted Solution:
```
n = int(input())
q = input()
if n > len(q):
print("NO")
else:
if n == 1:
print("YES")
print(q)
else:
arr = [0]*len(q)
for x in range(0, len(q)):
arr[x] = q[x]
con = arr[0]
res = ["-1"]*n
count = 0
x = 0
while(count < n-1):
if arr[x] == arr[x+1]:
con += arr[x+1]
x += 1
else:
res[count] = con
con = arr[x+1]
count +=1
x += 1
res[count] = q[3:]
res1 = set(res)
length = 0
for each in res1:
length += 1
if res[len(res) - 1] == "-1" or length < n:
print("NO")
else:
print("YES")
for x in res:
print(x)
```
No
| 2,034 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Submitted Solution:
```
from collections import defaultdict
def cutter(a, cuts):
if cuts == 1:
return [a]
comparador = set([a[0]])
aux = a[0]
ans = []
flag = True
for i in range(1, len(a)):
# print(a[i])
if a[i] not in comparador:
ans.append(aux)
aux = a[i]
comparador.union(set([a[i]]))
else:
aux += a[i]
# print(aux)
if len(ans) == cuts - 1 :
ans.append(a[i:])
break
return ans
def isBeautiful(a):
mapa = defaultdict(int)
for i in a:
mapa[i[0]] += 1
if mapa[i[0]] > 1:
return False
return True
def func():
n = int(input())
p = input()
if len(p) < n:
print('NO')
return
lista = cutter(p, n)
# print(lista)
if len(lista) < n:
print('NO')
return
if isBeautiful(lista):
print('YES')
for i in lista:
print(i)
else:
print('NO')
return
func()
```
No
| 2,035 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Submitted Solution:
```
N = int(input())
S = input()
found = set()
for i in range(len(S)):
k = S[i]
if(not (k in found)):
found.add(k)
if(len(found)>=N):
print("YES")
ptr1 = 0
count = 0
found.remove(S[ptr1])
for i in range(len(S)):
#print (found)
if(count==N-1):
print(S[ptr1:])
break
if(i>0 and (S[i] in found)):
print(S[ptr1:i])
ptr1=i
count+=1
found.remove(S[ptr1])
else:
print("NO")
```
No
| 2,036 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string q. A sequence of k strings s1, s2, ..., sk is called beautiful, if the concatenation of these strings is string q (formally, s1 + s2 + ... + sk = q) and the first characters of these strings are distinct.
Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.
Input
The first line contains a positive integer k (1 ≤ k ≤ 26) — the number of strings that should be in a beautiful sequence.
The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.
Output
If such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1, s2, ..., sk.
If there are multiple possible answers, print any of them.
Examples
Input
1
abca
Output
YES
abca
Input
2
aaacas
Output
YES
aaa
cas
Input
4
abc
Output
NO
Note
In the second sample there are two possible answers: {"aaaca", "s"} and {"aaa", "cas"}.
Submitted Solution:
```
# http://codeforces.com/problemset/problem/544/A
def main():
n = int(input())
s = str(input())
if n > len(s):
print('NO')
return
elif n == 1:
print('YES')
print(s)
else:
strings = []
letters = len(set(list(s)))
if letters < n:
print('NO')
return
curr = s[0]
comp = s[0]
used = {s[0]: 1}
cant = 0
for i in range(1, len(s)):
if s[i] == comp:
curr += s[i]
else:
check = used.get(s[i], -1)
if check != -1:
curr += s[i]
if i == len(s) - 1:
strings.append(curr)
break
continue
else:
strings.append(curr)
cant += 1
if cant == n:
strings[-1] = strings[-1] + s[i:]
break
curr = s[i]
comp = s[i]
used[comp] = 1
if i == len(s) - 1:
strings.append(curr)
break
print('YES')
for i in strings:
print(i)
main()
```
No
| 2,037 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
(n, m) = (int(t) for t in input().split())
s = [c for c in input()]
fs = 0
for i in range(1, len(s)):
if s[i] == '.' and s[i - 1] == '.':
fs += 1
out = []
for k in range(m):
t = input().split()
i = int(t[0]) - 1
c = t[1]
if (c == '.') != (s[i] == '.'):
if i - 1 > -1 and s[i - 1] == '.':
fs += 1 if c == '.' else -1
if i + 1 < len(s) and s[i + 1] == '.':
fs += 1 if c == '.' else -1
s[i] = c
out.append(str(fs))
out.append('\n')
print(''.join(out), end='')
```
| 2,038 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
from heapq import heapify,heappop,heappush
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
#def input(): return sys.stdin.readline().strip()m
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
n,m = aj()
s = ['$'] + [*input()] + ['$']
count = 0
for i in range(len(s)-1):
if s[i] == s[i+1] == '.':
count += 1
for i in range(m):
a,b = input().split()
a = int(a)
if s[a] == b == '.':
print(count)
elif s[a] != '.' and b!= '.':
print(count)
elif s[a] == '.':
if s[a-1] == '.':
count -= 1
if s[a+1] == '.':
count -= 1
print(count)
s[a] = b
else:
if s[a-1] == '.':
count += 1
if s[a+1] == '.':
count += 1
print(count)
s[a] = b
```
| 2,039 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
def solve(string, updates):
count = sum(string) - sum([not string[i] and string[i + 1]
for i in range(len(string) - 1)])
for (pos, val) in updates:
if string[pos] != val:
sign = 1 if val else -1
count += sign
count += sign * (string[pos - 1] and string[pos + 1])
count -= sign * (not string[pos - 1] and not string[pos + 1])
string[pos] = val
yield count
def read_input():
from sys import stdin
input_lines = stdin.readline
(n, m) = map(int, input_lines().split())
string = [False] + [c == '.' for c in input_lines()] + [False]
def parse_update(line):
pos, val = line.split()
return int(pos), val == '.'
updates = (parse_update(input_lines()) for _ in range(m))
return string, updates
def main():
string, updates = read_input()
for x in solve(string, updates):
print(x)
main()
```
| 2,040 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
n, m = map(int, input().split())
a = list(input())
res=0
b = []
for i in range(1, n):
if a[i]+a[i-1] =='..':
res += 1
for i in range(m):
g, c = input().split()
p = int(g)-1
if p > 0 and a[p-1] + a[p] == '..':
res -= 1
if p + 1 < n and a[p+1] + a[p] == '..':
res -= 1
a[p] = c
if p > 0 and a[p-1] + a[p] == '..':
res += 1
if p + 1 < n and a[p+1] + a[p] == '..':
res += 1
b.append(str(res))
print(' '.join(b))
```
| 2,041 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
import sys
n, m = map(int, sys.stdin.readline().split())
s = input()
left = 0
right = 0
ans = 0
while True:
left = s.find('.', right)
if left < 0:
break
right = left+1
while right < n and s[right] == '.':
right += 1
if right - left > 1:
ans += right-left-1
l = list(s)
ans_list = []
for i in range(m):
query = list(sys.stdin.readline().split())
xi = int(query[0]) - 1
ci = query[1]
if (ci == '.' and l[xi] == '.') or (ci != '.' and l[xi] != '.'):
pass
elif ci == '.' and l[xi] != '.':
if xi > 0 and l[xi-1] == '.':
ans += 1
if xi < n-1 and l[xi+1] == '.':
ans += 1
elif ci != '.' and l[xi] == '.':
if xi > 0 and l[xi-1] == '.':
ans -= 1
if xi < n-1 and l[xi+1] == '.':
ans -= 1
ans_list.append(ans)
l[xi] = ci
print('\n'.join(map(str, ans_list)))
```
| 2,042 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
n, m = map(int, input().split())
s = [c != '.' for c in input()] + [1]
k = sum(s[i] == s[i + 1] == 0 for i in range(n - 1))
t = [0] * m
for i in range(m):
x, c = input().split()
x, c = int(x) - 1, c != '.'
if not s[x]:
if c: k += s[x - 1] + s[x + 1] - 2
elif not c: k += 2 - s[x - 1] - s[x + 1]
s[x] = c
t[i] = k
print('\n'.join(map(str, t)))
```
| 2,043 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
from sys import stdin
input = stdin.readline
n,m = map(int,input().split())
s = list((0,1)[c == '.'] for c in list(input()))
res = 0
cnt = 0
for k in s:
if k == 1:
cnt += 1
else:
res += max(cnt-1,0)
cnt = 0
res += max(0,cnt-1)
for i in range(m):
x,c = input().split()
x = int(x)
nc = (0,1)[c == '.']
if s[x-1] != nc:
diff = 0
if x < n:
if s[int(x)] == 1: diff += 1
if x > 1:
if s[int(x-2)] == 1: diff += 1
if nc == 1:
res += diff
else:
res -= diff
s[x-1] = nc
print(res)
```
| 2,044 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Tags: constructive algorithms, data structures, implementation
Correct Solution:
```
from sys import stdin,stdout
input = stdin.readline
import operator
from array import array
n,m = map(int,input().split())
def calc():
s = array('B',[0])
s.extend(c == '.' for c in input())
res = sum(map(operator.mul,s[1:],s))
for i in range(m):
x,c = input().split()
x = int(x)
nc = c == '.'
if s[x] != nc:
diff = s[x-1] + s[x+1]
res += (-diff,diff) [nc]
s[x] = nc
yield str(res)
stdout.write('\n'.join(calc()))
```
| 2,045 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Submitted Solution:
```
import sys
input = sys.stdin.readline
def segtree(i,a,tree,l,r):
if l==r:
tree[i]=a[l]
return tree[i]
m=(l+r)//2
tree[i]= segtree(2*i+1,a,tree,l,m) + segtree(2*i+2,a,tree,m+1,r)
return tree[i]
def update(i,a,tree,l,r,ind):
if ind<l or ind>r:
return
elif l==r:
tree[i]=a[l]
return
m=(l+r)//2
update(2*i+1,a,tree,l,m,ind)
update(2*i+2,a,tree,m+1,r,ind)
tree[i]=tree[2*i+1]+tree[2*i+2]
n,m=map(int,input().split())
s=list(input())
a=[0]*n
for i in range(1,n):
if s[i]=='.' and s[i-1]=='.':
a[i]=1
i=0
while 2**i<=n:
i=i+1
tree=[0]*(2**(i+1)-1)
segtree(0,a,tree,0,n-1)
for _ in range(m):
i,c=input().split()
i=int(i)-1
if c=='.':
if s[i]!='.':
if i>0:
if s[i-1]=='.':
a[i]=1
update(0,a,tree,0,n-1,i)
if i+1<n:
if s[i+1]=='.' and a[i+1]==0:
a[i+1]=1
update(0,a,tree,0,n-1,i+1)
else:
if s[i]=='.':
a[i]=0
update(0,a,tree,0,n-1,i)
if i+1<n and a[i+1]==1:
a[i+1]=0
update(0,a,tree,0,n-1,i+1)
s[i]=c
sys.stdout.write(str(tree[0]) + "\n")
```
Yes
| 2,046 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Submitted Solution:
```
import sys
def count(s):
sm = 0
ln = 0
i = 0
while i < len(s):
cnt = 0
while i < len(s) and s[i] == '.':
cnt += 1
i += 1
if cnt > 1:
sm += cnt
ln += 1
i += 1
return sm - ln
n, m = map(int, sys.stdin.readline().split())
string = ['#'] + list(input()) + ['#']
ans = count(string)
arans = [0 for i in range(m)]
for _ in range(m):
i, s = sys.stdin.readline().split()
i = int(i)
if s == '.':
if string[i] == s:
sys.stdout.write(str(ans)+'\n')
continue
string[i] = s
if string[i + 1] == '.': ans += 1
if string[i - 1] == '.': ans += 1
else:
if '.' != string[i]:
sys.stdout.write(str(ans)+'\n')
continue
string[i] = s
if string[i + 1] == '.': ans -= 1
if string[i - 1] == '.': ans -= 1
sys.stdout.write(str(ans)+'\n')
```
Yes
| 2,047 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Submitted Solution:
```
n, m = map(int, input().split())
s = [True] + [c != '.' for c in input()] + [True]
ans = sum(s[i] == s[i + 1] == 0 for i in range(1, n + 1))
out = [0] * m
for i in range(m):
pos, c = input().split()
pos, c = int(pos), c != '.'
if not s[pos]:
if c: ans -= 2 - (s[pos - 1] + s[pos + 1])
else:
if not c: ans += 2 - (s[pos - 1] + s[pos + 1])
s[pos] = c
out[i] = ans
print('\n'.join(map(str, out)))
import time, sys
sys.stderr.write('{0:.3f} ms\n'.format(time.clock() * 1000));
# by Andrey Kim
```
Yes
| 2,048 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Submitted Solution:
```
n, m = map(int, input().split())
s = [c != '.' for c in input()] + [1]
f = sum(s[i] == 0 and s[i + 1] != 1 for i in range(n))
t = [0] * m
for i in range(m):
x, c = input().split()
x, c = int(x) - 1, c != '.'
d = s[x - 1] + s[x + 1] - 2
f += (c - s[x]) * d
s[x], t[i] = c, f
print('\n'.join(map(str, t)))
```
Yes
| 2,049 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Submitted Solution:
```
n, m = [int(x) for x in input().split()]
s = [x for x in input()]
ans = 0
c = 0
for i in range(len(s)):
if s[i] == '.':
c += 1
else:
if c > 1:
ans += c - 1
c = 0
if c != 0:
ans += c - 1
for i in range(m):
n, sym = [x for x in input().split()]
if sym == ".":
if int(n) != len(s) and s[int(n)] == '.':
ans += 1
if int(n) != 1 and s[int(n) - 2] == '.':
ans += 1
else:
if s[int(n) - 1] == '.':
if int(n) != len(s) and s[int(n)] == '.':
ans -= 1
if int(n) != 1 and s[int(n) - 2] == '.':
ans -= 1
s[int(n) - 1] = sym
print(ans)
```
No
| 2,050 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Submitted Solution:
```
# -*- coding: utf-8 -*-
# Baqir Khan
# Software Engineer (Backend)
n, m = map(int, input().split())
s = list(str(input()))
ans = 0
for i in range(n - 1):
if s[i] == "." and s[i + 1] == ".":
ans += 1
while m:
m -= 1
inp = input().split()
index = int(inp[0]) - 1
char = inp[1]
if char == ".":
if index != 0 and index != n - 1 and s[index + 1] == "." and s[index - 1] == ".":
ans += 2
elif (index != 0 and s[index - 1] == ".") or (index != n - 1 and s[index + 1] == "."):
ans += 1
elif s[index] == ".":
if index != 0 and index != n - 1 and s[index + 1] == "." and s[index - 1] == ".":
ans -= 2
elif (index != 0 and s[index - 1] == ".") or (index != n - 1 and s[index + 1] == "."):
ans -= 1
s[index] = char
print(ans)
```
No
| 2,051 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Submitted Solution:
```
import sys,os,io
import math,bisect,operator
inf,mod = float('inf'),10**9+7
# sys.setrecursionlimit(10 ** 6)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
Neo = lambda : list(map(int,input().split()))
# test, = Neo()
n,m = Neo()
s = ['*']+list(input())+['*']
t = 0
for i,j in zip(s,s[1:]):
if i+j == '..':
t += 1
for i in range(m):
ind,c = input().split()
ind = int(ind)
if c == '.':
if s[ind] != '.':
if s[ind-1]+s[ind+1] == '..':
t += 2
s[ind] = c
elif s[ind-1] == '.' or s[ind+1] == '.':
t += 1
s[ind] = c
else:
if s[ind-1]+s[ind]+s[ind+1] == '...':
t -= 2
s[ind] = c
elif s[ind-1]+s[ind] == '..' or s[ind]+s[ind+1] == '..':
t -= 1
s[ind] = c
else:
s[ind] = c
print(t)
```
No
| 2,052 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Output
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Examples
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
Note
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....".
* after the first query f(hb..bz....) = 4 ("hb[..]bz...." → "hb.bz[..].." → "hb.bz[..]." → "hb.bz[..]" → "hb.bz.")
* after the second query f(hbс.bz....) = 3 ("hbс.bz[..].." → "hbс.bz[..]." → "hbс.bz[..]" → "hbс.bz.")
* after the third query f(hbс.bz..f.) = 1 ("hbс.bz[..]f." → "hbс.bz.f.")
Note to the second sample test.
The original string is ".cc.".
* after the first query: f(..c.) = 1 ("[..]c." → ".c.")
* after the second query: f(....) = 3 ("[..].." → "[..]." → "[..]" → ".")
* after the third query: f(.a..) = 1 (".a[..]" → ".a.")
* after the fourth query: f(aa..) = 1 ("aa[..]" → "aa.")
Submitted Solution:
```
from sys import stdin, stdout
input = stdin.readline
n, m = map(int, input().split())
s = list(input())
f = 0
ans = []
for i in range(1,n):
if s[i] == s[i-1] and s[i] == '.':
f+= 1
for i in range(m):
x, ch = input().split()
x = int(x) - 1
if s[x] != ch:
if ch == '.':
if x > 0 and s[x-1] == '.':
f += 1
if x < n - 1 and s[x+1] == '.':
f += 1
else:
if x > 0 and s[x-1] == '.':
f -= 1
if x < n - 1 and s[x+1] == '.':
f -= 1
s[x] = ch
ans.append(f)
stdout.write("\n".join(map(str,ans)))
```
No
| 2,053 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Tags: implementation
Correct Solution:
```
# your code goes here
def read_data():
maps = [input() for n in range(8)]
return maps
def decode(maps):
step_b = 1000
step_a = 1000
for col in range(8):
mina, maxa = find_range(maps, col, 'W')
minb, maxb = find_range(maps, col, 'B')
if mina < minb:
step_a = min(step_a, mina)
if maxb > maxa:
step_b = min(step_b, 7 - maxb)
if step_a <= step_b:
return 'A'
else:
return 'B'
def find_range(maps, col, ch):
minc = float('inf')
maxc = - float('inf')
for row in range(8):
if maps[row][col] == ch:
minc = min(minc, row)
maxc = max(maxc, row)
return minc, maxc
maps = read_data()
print(decode(maps))
```
| 2,054 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Tags: implementation
Correct Solution:
```
a=[[] for i in range(8)]
colw=[]
colb=[]
for i in range(8):
a[i]=input()
for v in range(8):
if a[i][v]=='W':
colw.append([i,v])
elif a[i][v]=='B':
colb.append([i,v])
w=0
minw=8
for i in range(len(colw)):
for v in range(colw[i][0]):
if a[v][colw[i][1]]!='B':
w+=1
else:
w=0
break
if w>0 and w<minw:
minw=w
w=0
b=0
minb=8
for i in range(len(colb)):
for v in range(7,colb[i][0],-1):
if a[v][colb[i][1]]!='W':
b+=1
else:
b=0
break
if b>0 and b<minb:
minb=b
b=0
if minb<minw:
print('B')
else:
print('A')
```
| 2,055 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Tags: implementation
Correct Solution:
```
# 592A
# θ(8*8) time
# θ(8*8) space
__author__ = 'artyom'
# SOLUTION
def main(n):
bd = [None] * n
for i in range(n):
bd[i] = read(0)
w = n
z = [0] * n
for i in range(n):
for j in range(n):
if bd[i][j] == 'W':
if z[j] == 0:
w = i
break
elif bd[i][j] == 'B':
z[j] = 1
else:
continue
break
b = n
z = [0] * n
for i in range(n - 1, -1, -1):
for j in range(n):
if bd[i][j] == 'B':
if z[j] == 0:
b = n - 1 - i
break
elif bd[i][j] == 'W':
z[j] = 1
else:
continue
break
return w <= b
# HELPERS
def read(mode=1, size=None):
# 0: String
# 1: Integer
# 2: List of strings
# 3: List of integers
# 4: Matrix of integers
if mode == 0: return input().strip()
if mode == 1: return int(input().strip())
if mode == 2: return input().strip().split()
if mode == 3: return list(map(int, input().strip().split()))
a = []
for _ in range(size):
a.append(read(3))
return a
def write(s='\n'):
if s is None: s = ''
if isinstance(s, tuple) or isinstance(s, list): s = ' '.join(map(str, s))
s = str(s)
print(s)
write(['B', 'A'][main(8)])
```
| 2,056 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Tags: implementation
Correct Solution:
```
white, black = [set() for _ in range(8)], [set() for _ in range(8)]
for row in range(8):
for col, c in enumerate(input().strip()):
if c == 'W':
white[col].add(row)
elif c == 'B':
black[col].add(row)
min_w, max_b = 7, 0
for col in range(8):
for w in white[col]:
if all(b > w for b in black[col]) and w < min_w:
min_w = w
for b in black[col]:
if all(b > w for w in white[col]) and b > max_b:
max_b = b
#print(min_w, max_b)
if min_w <= 7 - max_b:
print('A')
else:
print('B')
```
| 2,057 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Tags: implementation
Correct Solution:
```
l = []
for i in range(8):
x = input()
l.append(x)
#Aがwhile 上を目指す、Bがblack 下を目指す
bl = [10 for i in range(8)]
wh = [10 for i in range(8)]
for i in range(8):
for j in range(8):
if l[i][j] == "B" and bl[j] == 10:
bl[j] = i
if l[i][j] == "W" and wh[j] == 10:
wh[j] = i
a = 10
for i in range(8):
if wh[i] < 10:
if wh[i] < bl[i]:
a = min(a,wh[i])
bl = [10 for i in range(8)]
wh = [-1 for i in range(8)]
for i in range(7,-1,-1):
for j in range(8):
if l[i][j] == "B" and bl[j] == 10:
bl[j] = i
if l[i][j] == "W" and wh[j] == -1:
wh[j] = i
b = -1
for i in range(8):
if bl[i] < 10:
if bl[i] > wh[i] and wh[i] != 10:
b = max(b,bl[i])
#print (bl)
#print (wh)
#print (b)
bb = 7-b
aa = a
if aa <= bb:
print ("A")
else:
print ("B")
```
| 2,058 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Tags: implementation
Correct Solution:
```
field = []
def check_row(x, y, choise):
if choise:
for i in range(x):
if field[i][y] == 'B':
return False
return True
else:
i = 7
while i != x:
if field[i][y] == 'W':
return False
i -= 1
return True
def find_best_w():
for i in range(8):
if 'W' in field[i]:
for j in range(len(field[i])):
if field[i][j] == 'W':
if check_row(i, j, True):
return i
def find_best_b():
i = 7
while i != -1:
if 'B' in field[i]:
for j in range(len(field[i])):
if field[i][j] == 'B':
if check_row(i, j, False):
return i
i -= 1
def solution():
for i in range(8):
field.append(input())
#print(find_best_w())
#print(find_best_b())
return find_best_w() - 1 < 7 - find_best_b()
print('A' if solution() else 'B', end="")
```
| 2,059 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Tags: implementation
Correct Solution:
```
a = [list(input()) for j in range(8)]
cntW = 10
cntB = 10
for i in range(8):
for j in range(8):
if a[i][j] == 'W':
b1 = True
for k in range(i):
if a[k][j] != '.':
b1 = False
if b1:
cntW = min(cntW, i)
elif a[i][j] == 'B':
b1 = True
for k in range(i + 1, 8):
if a[k][j] != '.':
b1 = False
if b1:
cntB = min(cntB, 7 - i)
if cntW <= cntB:
print('A')
else:
print('B')
```
| 2,060 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Tags: implementation
Correct Solution:
```
def on_same_col(point, arr, flag):
for p in arr:
if (flag and p[0] < point[0] and p[1] == point[1]
or not flag and p[0] > point[0] and p[1] == point[1]):
return True
return False
whites = []
blacks = []
min_white = 10
min_black = 10
for row in range(8):
row_str = input()
for col in range(8):
if row_str[col] == "W":
whites.append((row, col))
if row_str[col] == "B":
blacks.append((row, col))
for white in whites:
if not on_same_col((white[0], white[1]), blacks, True) \
and white[0] < min_white:
min_white = white[0]
for black in blacks:
if not on_same_col((black[0], black[1]), whites, False) \
and 7 - black[0] < min_black:
min_black = 7 - black[0]
if min_white <= min_black:
print("A")
else:
print("B")
```
| 2,061 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Submitted Solution:
```
arr = []
for i in range(8):
arr.append(input())
white = black = 0
for i in range(1,8):
for j in range(8):
if arr[i][j]=='W':
check = 0
for k in range(i):
if arr[k][j]!='.':
check = 1
break
if check==0:
white = i
break
if white:
break
for i in range(-2,-9,-1):
for j in range(8):
if arr[i][j]=='B':
check = 0
for k in range(-1,i,-1):
if arr[k][j]!='.':
check = 1
break
if check == 0:
black = 7-(8+i)
break
if black:
break
if white==0 or black==0:
if white==0:
print('B')
else:
print('A')
elif white<=black:
print('A')
else:
print('B')
```
Yes
| 2,062 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Submitted Solution:
```
def main():
ww, bb = [8], [8]
for col in zip(*[input() for _ in range(8)]):
_wb = ([8], [8], [])
for i, c in enumerate(col):
_wb["WB.".find(c)].append(i)
_w, _b, _ = _wb
w, b = min(_w), min(_b)
if w < b:
ww.append(w)
_w[0] = _b[0] = -1
w, b = max(_w), max(_b)
if w < b:
bb.append(7 - b)
print("AB"[min(ww) > min(bb)])
if __name__ == '__main__':
main()
```
Yes
| 2,063 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Submitted Solution:
```
board = [input(),input(),input(),input(),input(),input(),input(),input()]
b = -99
for i in range(8):
for j in range(7,-1,-1):
piece = board[j][i]
if piece == 'W':
break
if piece == 'B':
b = max(b,j)
break
b = 7-b
w = 99
for i in range(8):
for j in range(8):
piece = board[j][i]
if piece == 'B':
break
if piece == 'W':
w = min(w,j)
if b < w:
print('B')
else:
print('A')
```
Yes
| 2,064 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Submitted Solution:
```
A=[]
for i in range(8):
A+=[input()]
mA, mB = None ,None
for r in range(8):
for c in range(8):
if A[r][c] == 'W':
v = True
for x in range(r):
if A[x][c] == 'B':
v=False
break
if v:
if mA == None:
mA = r
else:
mA = min(mA, r)
if A[r][c] == 'B':
v = True
for x in range(r+1,8):
if A[x][c] == 'W':
v=False
break
if v:
if mB == None:
mB = 7 - r
else:
mB = min(mB, 7-r)
if not mA or mA > mB:
print("B")
else:
print("A")
```
Yes
| 2,065 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Submitted Solution:
```
M=[input() for i in range(8)]
l=[]
p=100000000
for i in range(8) :
for j in range(8) :
if M[i][j]=='W' and j not in l :
p=i
break
if M[i][j]=='B' :
l.append(j)
if p!=100000000 :
break
l=[]
for i in range(7,-1,-1) :
for j in range(7,-1,-1) :
if M[i][j]=='B' and j not in l :
if p<8-i-1 :
print('A')
else :
print('B')
exit()
if M[i][j]=='W' :
l.append(j)
print('A')
```
No
| 2,066 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Submitted Solution:
```
S = [input() for _ in range(8)]
S = list(''.join(x) for x in zip(*S))
valid = [s for s in S if s.replace('.', '') not in ['BW', '']]
bdist = 1000
wdist = 1000
for s in valid:
if 'B' in s:
bdist = min(bdist, 8 - s.rfind('B'))
if 'W' in s:
wdist = min(wdist, 8 - s[::-1].rfind('W'))
if bdist < wdist:
print('B')
else:
print('A')
```
No
| 2,067 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Submitted Solution:
```
str_pos = []
for i in range(8):
str_pos.append(list(input()))
stolb_pos = []
for i in range(8):
stolb = []
for j in range(8):
stolb.append(str_pos[j][i])
stolb_pos.append(stolb)
indexes = []
for i in range(len(stolb_pos)):
W_index = None
B_index = None
for j in range(len(stolb_pos[i])):
if stolb_pos[i][j] == "W":
W_index = j + 1
if stolb_pos[i][j] == "B":
B_index = j + 1
indexes.append([W_index, B_index])
best_W = 100
best_B = 100
for index in indexes:
if index[0] and index[1]:
if index[0] < index[1]:
if best_W > index[0]:
best_W = index[0]
if best_B > 7 - index[1]:
best_B = 7 - index[1]
elif index[0]:
if best_W > index[0]:
best_W = index[0]
elif index[1]:
if best_B > 7 - index[1]:
best_B = 7 - index[1]
if best_B < best_W:
print("A")
else:
print("B")
```
No
| 2,068 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».
This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.
<image>
Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.
There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.
Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.
Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.
Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.
Input
The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.
It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.
Output
Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.
Examples
Input
........
........
.B....B.
....W...
........
..W.....
........
........
Output
A
Input
..B.....
..W.....
......B.
........
.....W..
......B.
........
........
Output
B
Note
In the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.
Submitted Solution:
```
x=[]
for i in range(8):
a=input()
x.append(list(a))
a,b=8,1
for i in range(8):
u=1
for j in range(8):
if x[j][i]=="W":
u=1
elif x[j][i]=="B":
u=j+1
b=max(b,u)
for i in range(8):
u=8
for j in range(8):
if x[j][i]=="W":
u=j+1
elif x[j][i]=="B":
u=8
break
a=min(a,u)
b=8-b
a-=1
if a<=b:
print("A")
else:
print("B")
```
No
| 2,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.
The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.
What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.
Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.
Help the King to calculate this characteristic for each of his plan.
Input
The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cities in the kingdom.
Each of the next n - 1 lines contains two distinct integers ui, vi (1 ≤ ui, vi ≤ n) — the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads.
The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of King's plans.
Each of the next q lines looks as follows: first goes number ki — the number of important cities in the King's plan, (1 ≤ ki ≤ n), then follow exactly ki space-separated pairwise distinct numbers from 1 to n — the numbers of important cities in this plan.
The sum of all ki's does't exceed 100 000.
Output
For each plan print a single integer — the minimum number of cities that the barbarians need to capture, or print - 1 if all the barbarians' attempts to isolate important cities will not be effective.
Examples
Input
4
1 3
2 3
4 3
4
2 1 2
3 2 3 4
3 1 2 4
4 1 2 3 4
Output
1
-1
1
-1
Input
7
1 2
2 3
3 4
1 5
5 6
5 7
1
4 2 4 6 7
Output
2
Note
In the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective.
In the second sample the cities to capture are 3 and 5.
Tags: dfs and similar, divide and conquer, dp, graphs, sortings, trees
Correct Solution:
```
import sys
from collections import deque
def solve():
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
writelines = sys.stdout.writelines
N = int(readline())
G = [[] for i in range(N)]
for i in range(N-1):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
# Euler tour technique
S = []
FS = [0]*N; LS = [0]*N
depth = [0]*N
stk = [-1, 0]
it = [0]*N
while len(stk) > 1:
v = stk[-1]
i = it[v]
if i == 0:
FS[v] = len(S)
depth[v] = len(stk)
if i < len(G[v]) and G[v][i] == stk[-2]:
it[v] += 1
i += 1
if i == len(G[v]):
LS[v] = len(S)
stk.pop()
else:
stk.append(G[v][i])
it[v] += 1
S.append(v)
L = len(S)
lg = [0]*(L+1)
# Sparse Table
for i in range(2, L+1):
lg[i] = lg[i >> 1] + 1
st = [[L]*(L - (1 << i) + 1) for i in range(lg[L]+1)]
st[0][:] = S
b = 1
for i in range(lg[L]):
st0 = st[i]
st1 = st[i+1]
for j in range(L - (b<<1) + 1):
st1[j] = (st0[j] if depth[st0[j]] <= depth[st0[j+b]] else st0[j+b])
b <<= 1
INF = 10**18
ans = []
Q = int(readline())
G0 = [[]]*N
P = [0]*N
deg = [0]*N
KS = [0]*N
A = [0]*N
B = [0]*N
for t in range(Q):
k, *vs = map(int, readline().split())
for i in range(k):
vs[i] -= 1
KS[vs[i]] = 1
vs.sort(key=FS.__getitem__)
for i in range(k-1):
x = FS[vs[i]]; y = FS[vs[i+1]]
l = lg[y - x + 1]
w = st[l][x] if depth[st[l][x]] <= depth[st[l][y - (1 << l) + 1]] else st[l][y - (1 << l) + 1]
vs.append(w)
vs.sort(key=FS.__getitem__)
stk = []
prv = -1
for v in vs:
if v == prv:
continue
while stk and LS[stk[-1]] < FS[v]:
stk.pop()
if stk:
G0[stk[-1]].append(v)
G0[v] = []
it[v] = 0
stk.append(v)
prv = v
que = deque()
prv = -1
P[vs[0]] = -1
for v in vs:
if v == prv:
continue
for w in G0[v]:
P[w] = v
deg[v] = len(G0[v])
if deg[v] == 0:
que.append(v)
prv = v
while que:
v = que.popleft()
if KS[v]:
a = 0
for w in G0[v]:
ra = A[w]; rb = B[w]
if depth[v]+1 < depth[w]:
a += min(ra, rb+1)
else:
a += ra
A[v] = INF
B[v] = a
else:
a = 0; b = c = INF
for w in G0[v]:
ra = A[w]; rb = B[w]
a, b, c = a + ra, min(a + rb, b + ra), min(b + rb, c + min(ra, rb))
A[v] = min(a, b+1, c+1)
B[v] = b
p = P[v]
if p != -1:
deg[p] -= 1
if deg[p] == 0:
que.append(p)
v = min(A[vs[0]], B[vs[0]])
if v >= INF:
ans.append("-1\n")
else:
ans.append("%d\n" % v)
for v in vs:
KS[v] = 0
writelines(ans)
solve()
```
| 2,070 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.
The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.
What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.
Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.
Help the King to calculate this characteristic for each of his plan.
Input
The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cities in the kingdom.
Each of the next n - 1 lines contains two distinct integers ui, vi (1 ≤ ui, vi ≤ n) — the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads.
The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of King's plans.
Each of the next q lines looks as follows: first goes number ki — the number of important cities in the King's plan, (1 ≤ ki ≤ n), then follow exactly ki space-separated pairwise distinct numbers from 1 to n — the numbers of important cities in this plan.
The sum of all ki's does't exceed 100 000.
Output
For each plan print a single integer — the minimum number of cities that the barbarians need to capture, or print - 1 if all the barbarians' attempts to isolate important cities will not be effective.
Examples
Input
4
1 3
2 3
4 3
4
2 1 2
3 2 3 4
3 1 2 4
4 1 2 3 4
Output
1
-1
1
-1
Input
7
1 2
2 3
3 4
1 5
5 6
5 7
1
4 2 4 6 7
Output
2
Note
In the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective.
In the second sample the cities to capture are 3 and 5.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
writelines = sys.stdout.writelines
N = int(readline())
G = [[] for i in range(N)]
for i in range(N-1):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
# Euler tour technique
S = []
FS = [0]*N; LS = [0]*N
depth = [0]*N
def dfs(v, p, d):
depth[v] = d
FS[v] = len(S)
S.append(v)
for w in G[v]:
if w == p:
continue
dfs(w, v, d+1)
S.append(v)
LS[v] = len(S)
S.append(v)
dfs(0, -1, 0)
L = len(S)
lg = [0]*(L+1)
# Sparse Table
for i in range(2, L+1):
lg[i] = lg[i >> 1] + 1
st = [[L]*L for i in range(lg[L]+1)]
st[0][:] = S
b = 1
for i in range(lg[L]):
st0 = st[i]
st1 = st[i+1]
for j in range(L - (b<<1) + 1):
st1[j] = (st0[j] if depth[st0[j]] <= depth[st0[j+b]] else st0[j+b])
b <<= 1
INF = 10**18
ans = []
Q = int(readline())
G0 = [None for i in range(N)]
KS = [0]*N
for t in range(Q):
k, *vs = map(int, readline().split())
for i in range(k):
vs[i] -= 1
KS[vs[i]] = 1
vs.sort(key=FS.__getitem__)
for i in range(len(vs)-1):
x = FS[vs[i]]; y = FS[vs[i+1]]
l = lg[y - x + 1]
w = st[l][x] if depth[st[l][x]] <= depth[st[l][y - (1 << l) + 1]] else st[l][y - (1 << l) + 1]
vs.append(w)
vs.sort(key=FS.__getitem__)
prv = -1
for v in vs:
if v == prv:
continue
G0[v] = []
prv = v
stk = []
prv = -1
for v in vs:
if v == prv:
continue
while stk and LS[stk[-1]] < FS[v]:
stk.pop()
if stk:
G0[stk[-1]].append(v)
stk.append(v)
prv = v
def dfs(v):
if KS[v]:
a = 0
for w in G0[v]:
ra, rb = dfs(w)
if depth[v]+1 < depth[w]:
a += min(ra, rb+1)
else:
a += ra
return INF, a
a = 0; b = c = INF
for w in G0[v]:
ra, rb = dfs(w)
a, b, c = a + ra, min(a + rb, b + ra), min(b + rb, c + min(ra, rb))
if KS[v]:
return INF, a
return min(a, c+1), b
a, b = dfs(vs[0])
v = min(a, b)
if v >= INF:
ans.append("-1\n")
else:
ans.append("%d\n" % v)
for v in vs:
KS[v] = 0
writelines(ans)
```
No
| 2,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.
The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.
What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.
Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.
Help the King to calculate this characteristic for each of his plan.
Input
The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cities in the kingdom.
Each of the next n - 1 lines contains two distinct integers ui, vi (1 ≤ ui, vi ≤ n) — the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads.
The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of King's plans.
Each of the next q lines looks as follows: first goes number ki — the number of important cities in the King's plan, (1 ≤ ki ≤ n), then follow exactly ki space-separated pairwise distinct numbers from 1 to n — the numbers of important cities in this plan.
The sum of all ki's does't exceed 100 000.
Output
For each plan print a single integer — the minimum number of cities that the barbarians need to capture, or print - 1 if all the barbarians' attempts to isolate important cities will not be effective.
Examples
Input
4
1 3
2 3
4 3
4
2 1 2
3 2 3 4
3 1 2 4
4 1 2 3 4
Output
1
-1
1
-1
Input
7
1 2
2 3
3 4
1 5
5 6
5 7
1
4 2 4 6 7
Output
2
Note
In the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective.
In the second sample the cities to capture are 3 and 5.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
writelines = sys.stdout.writelines
N = int(readline())
G = [[] for i in range(N)]
for i in range(N-1):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
# Euler tour technique
S = []
FS = [0]*N; LS = [0]*N
depth = [0]*N
def dfs(v, p, d):
depth[v] = d
FS[v] = len(S)
S.append(v)
for w in G[v]:
if w == p:
continue
dfs(w, v, d+1)
S.append(v)
LS[v] = len(S)
S.append(v)
dfs(0, -1, 0)
L = len(S)
lg = [0]*(L+1)
# Sparse Table
for i in range(2, L+1):
lg[i] = lg[i >> 1] + 1
st = [[L]*L for i in range(lg[L]+1)]
st[0][:] = S
b = 1
for i in range(lg[L]):
st0 = st[i]
st1 = st[i+1]
for j in range(L - (b<<1) + 1):
st1[j] = (st0[j] if depth[st0[j]] <= depth[st0[j+b]] else st0[j+b])
b <<= 1
INF = 10**18
ans = []
Q = int(readline())
G0 = [None for i in range(N)]
KS = [0]*N
for t in range(Q):
k, *vs = map(int, readline().split())
for i in range(k):
vs[i] -= 1
KS[vs[i]] = 1
vs.sort(key=FS.__getitem__)
for i in range(len(vs)-1):
x = FS[vs[i]]; y = FS[vs[i+1]]
l = lg[y - x + 1]
w = st[l][x] if depth[st[l][x]] <= depth[st[l][y - (1 << l) + 1]] else st[l][y - (1 << l) + 1]
vs.append(w)
vs.sort(key=FS.__getitem__)
prv = -1
for v in vs:
if v == prv:
continue
G0[v] = []
prv = v
stk = []
prv = -1
for v in vs:
if v == prv:
continue
while stk and LS[stk[-1]] < FS[v]:
stk.pop()
if stk:
G0[stk[-1]].append(v)
stk.append(v)
prv = v
def dfs(v):
a = 0; b = c = INF
for w in G0[v]:
ra, rb = dfs(w)
rb += (depth[w] - depth[v]) - 1
a, b, c = a + ra, min(a + rb, b + ra), min(b + rb, c + min(ra, rb))
if KS[v]:
return min(b, c), min(a, b, c)
b += 1; c += 1
return min(a, c), min(b, c)
a, b = dfs(vs[0])
if a == 0:
ans.append("-1\n")
elif a >= INF:
ans.append("0\n")
else:
ans.append("%d\n" % a)
for v in vs:
KS[v] = 0
writelines(ans)
```
No
| 2,072 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
s = {} #dic
d = {} #dic
p = set() #set
mx = - 10**15
mi = -mx
ans = 2
for i in range(n) :
if a[i] in s :
s[a[i]] += 1
else :
s[a[i]] = 1
mx = max(mx,a[i])
mi = min(mi,a[i])
if 0 in s : ans = max(ans,s[0])
for i in range(n) :
for j in range(n) :
if (j==i) or (a[i]==0 and a[j]==0) or ((a[i], a[j]) in p) : continue
f0 = a[i]; f1 = a[j]; ansi = 2; f2 = 0;
d = {}
p.add((a[i], a[j]))
while True :
f2 = f1 + f0
f0 = f1
f1 = f2
if (f2 > mx) or (f2 < mi) : break
if f2 in s :
d[f2] = s[f2]
else : break
f0 = a[i]; f1 = a[j];
if f1==f0 :
d[f0] = s[f0] - 2
else :
d[f0] = s[f0] - 1
d[f1] = s[f1] - 1
while True :
f2 = f1 + f0
f0 = f1
f1 = f2
if (f2 > mx) or (f2 < mi) : break
if (f2 in d) and (d[f2] > 0) :
ansi += 1
d[f2] -= 1
else : break
ans = max(ans, ansi)
print(ans)
```
| 2,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
D = {}
for x in a:
if x in D:
D[x] += 1
else:
D[x] = 1
maxans = 0
def check(x, y):
num = 2
D[x] -= 1
D[y] -= 1
while x+y in D and D[x+y] > 0:
D[x+y] -= 1
x, y = y, x+y
num += 1
ans = num
while num > 2:
D[y] += 1
x, y = y-x, x
num -= 1
D[x] += 1
D[y] += 1
return ans
for x in D:
for y in D:
if x == y and D[x] == 1: continue
maxans = max(check(x, y), maxans)
print(maxans)
```
| 2,074 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
def rec(a, b):
res, c = 0, a + b
if d.get(c) and d[c] > 0:
d[c] -= 1
res = rec(b, c) + 1
d[c] += 1
return res
input()
d = {}
for i in map(int, input().split()):
if d.get(i):
d[i] += 1
else:
d[i] = 1
ans = 2
for a in d:
for b in d:
if a != b or d[a] > 1:
d[a] -= 1
d[b] -= 1
cnt = rec(a, b) + 2
d[a] += 1
d[b] += 1
ans = max(ans, cnt)
print(ans)
```
| 2,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
def go(a, b):
res, c = 0, a + b
if d.get(c) and d[c] > 0:
d[c] -= 1
res = go(b, c) + 1
d[c] += 1
return res
input()
d = {}
for i in map(int, input().split()):
if d.get(i): d[i] += 1
else: d[i] = 1
ans = 2
for a in d:
for b in d:
if a != b or d[a] > 1:
d[a] -= 1; d[b] -= 1
cnt = go(a, b) + 2
d[a] += 1; d[b] += 1
ans = max(cnt, ans)
print(ans)
```
| 2,076 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
from collections import Counter
input()
s = Counter(map(int, input().split()))
n = 0
for q in s:
s[q] -= 1
for a in s:
if not s[a]: continue
t = [a]
s[a] -= 1
b = q + a
while s.get(b, 0):
s[b] -= 1
t.append(b)
a, b = b, a + b
n = max(n, len(t))
for c in t: s[c] += 1
s[q] += 1
print(n + 1)
```
| 2,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
ans = a.count(0)
d = {}
for i in a:
if i not in d:
d[i] = 1
else:
d[i] += 1
ans = max(ans, 2)
for i in range(n):
for j in range(n):
if(i != j and (a[i] != 0 or a[j] != 0)):
first = a[i]
second = a[j]
temp = [first, second]
third = first + second
while(True):
if abs(third) > int(1e9):
break
if third not in d:
break
temp.append(third)
first = second
second = third
third = first + second
count = 0
f = 1
for k in range(len(temp)):
if d[temp[k]] > 0:
d[temp[k]] -= 1
count += 1
else:
f = 0
for j in range(k):
d[temp[j]] += 1
break
if f:
for k in temp:
d[k] += 1
ans = max(ans, count)
print(ans)
```
| 2,078 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
from copy import *
length=int(input())
arr=list(map(int,input().split()))
d=dict()
for i in arr:
d[i]=d.get(i,0)+1
ans=0
for i in range(len(arr)):
for j in range(len(arr)):
if i!=j:
if arr[i]==0 and arr[j]==0:
ans=max(ans,d[arr[i]])
else:
count=2
a=arr[i]
b=arr[j]
d[a]-=1
d[b]-=1
for k in range(100):
if d.get(a+b):
count+=1
d[a+b]-=1
c=a+b
a=b
b=c
else:
d[a]+=1
d[b]+=1
ans=max(ans,count)
break
y=count-2
while y>0:
c=b-a
d[c]=d.get(c,0)+1
b=a
a=c
y-=1
print(ans)
```
| 2,079 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Tags: brute force, dp, hashing, implementation, math
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <=key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n=int(input())
l=list(map(int,input().split()))
cou= {}
for i in l:
if i in cou:
cou[i]+=1
else:
cou[i]=1
def find(x,y):
num = 2
cou[x] -= 1
cou[y] -= 1
while x + y in cou and cou[x + y] > 0:
cou[x + y] -= 1
x, y = y, x + y
num += 1
ans = num
while num > 2:
cou[y] += 1
x, y = y - x, x
num -= 1
cou[x] += 1
cou[y] += 1
return ans
ans=2
for x in cou:
for y in cou:
if x == y and cou[x] == 1: continue
ans = max(find(x, y), ans)
print(ans)
```
| 2,080 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
# [https://codeforces.com/contest/633/submission/16384934]
import sys, collections
sys.setrecursionlimit(10000)
d = collections.defaultdict(int)
def go(a, b):
res, c = 0, a + b
if d.get(c) and d[c] > 0:
d[c] -= 1
res = go(b, c) + 1
d[c] += 1
return res
input()
for i in map(int, input().split()):
d[i] += 1
ans = 2
for a in d:
for b in d:
if a != b or d[a] > 1:
d[a] -= 1; d[b] -= 1
cnt = go(a, b) + 2
d[a] += 1; d[b] += 1
ans = max(cnt, ans)
print(ans)
```
Yes
| 2,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
def go(a,b):
ret,c=0,a+b
if d.get(c) and d[c]>0:
d[c]-=1
ret=go(b,c)+1
d[c]+=1
return ret
input()
d={}
for i in map(int,input().split()):
if d.get(i):d[i]+=1
else: d[i]=1
ans=2
for a in d:
for b in d:
if a!=b or d[a]>1:
d[a]-=1
d[b]-=1
temp=go(a,b)+2
ans=max(temp,ans)
d[a]+=1
d[b]+=1
print(ans)
```
Yes
| 2,082 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
import random, math
from copy import deepcopy as dc
from bisect import bisect_left, bisect_right
from collections import Counter
# Function to call the actual solution
def solution(li):
ma = {}
for i in range(len(li)):
ma[li[i]] = ma.get(li[i], 0) + 1
# ma1 = dc(ma)
ans = 0
# li = list(set(li))
for i in range(len(li)):
for j in range(len(li)):
if i != j:
f0 = li[i]
f1 = li[j]
if f0 == 0 and f1 == 0:
ans = max(ans, ma[0])
continue
ma[f0] -= 1
ma[f1] -= 1
cur = 2
while True:
nxt = f0 + f1
if nxt in ma and ma[nxt] > 0:
f0 = f1 + 1 - 1
f1 = nxt + 1 - 1
ma[nxt] -= 1
cur += 1
else:
break
cur1 = 2
ma[f0] += 1
ma[f1] += 1
while cur1 < cur:
prev = f1 - f0
f1 = f0 + 1 - 1
f0 = prev + 1 - 1
ma[prev] += 1
cur1 += 1
ans = max(ans, cur)
return ans
# Function to take input
def input_test():
n = int(input())
li = list(map(int, input().strip().split(" ")))
out = solution(li)
print(out)
# Function to test my code
def test():
pass
input_test()
# test()
```
Yes
| 2,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from collections import Counter
n = int(input())
s = Counter(map(int, input().split()))
n = 0
for q in s:
s[q] -= 1
for a in s:
if s[a]:
t = [a]
s[a] -= 1
b = q + a
while s.get(b, 0):
s[b] -= 1
t.append(b)
a, b = b, a + b
n = max(n, len(t))
for c in t:
s[c] += 1
s[q] += 1
print(n + 1)
```
Yes
| 2,084 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
n=ni()
l=li()
d=Counter(l)
ans=0
for i in range(n):
d[l[i]]-=1
for j in range(n):
if i==j:
continue
if l[i]==0 and l[j]==0:
ans=max(ans,d[0]+1)
continue
d[l[j]]-=1
temp=2
prev=l[j]
curr=l[i]+l[j]
ans1=[]
while d[curr]:
temp+=1
d[curr]-=1
ans1.append(curr)
prev,curr=curr,prev+curr
ans=max(ans,temp)
for k in ans1:
d[k]+=1
d[l[j]]+=1
d[l[i]]+=1
pn(ans)
```
Yes
| 2,085 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
n=ni()
l=li()
d=Counter(l)
ans=0
for i in range(n):
for j in range(n):
if i==j:
continue
if l[i]==0 and l[j]==0:
ans=max(ans,d[0])
continue
temp=2
prev=l[j]
curr=l[i]+l[j]
while d[curr]:
temp+=1
prev,curr=curr,prev+curr
ans=max(ans,temp)
pn(ans)
```
No
| 2,086 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from sys import stdin
n=int(stdin.readline().strip())
s=tuple(map(int,stdin.readline().strip().split()))
st=set(s)
ans=2
n=min(100,n)
for i in range(n):
for j in range(n):
if j==i:
continue
x=2
f1=s[j]
f2=s[j]+s[i]
while(f2 in st):
x+=1;
f3=f1;
f1=f2;
f2+=f3;
if(x>ans):
ans=x
print(ans)
```
No
| 2,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
from collections import Counter
n = int(input())
s = Counter(map(int, input().split()))
n = 0
for q in s:
s[q] -= 1
for a in s:
if s[a]:
t = [a]
s[a] -= 1
b = q + a
while s.get(b, 0):
s[b] -= 1
t.append(b)
a, b = b, a + b
n = max(n, len(t))
for c in t:
s[c] += 1
s[q] += 1
print(n)
```
No
| 2,088 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
import random, math
from copy import deepcopy as dc
from bisect import bisect_left, bisect_right
from collections import Counter
# Function to call the actual solution
def solution(li):
ma = {}
for i in range(len(li)):
ma[li[i]] = ma.get(li[i], 0) + 1
# ma1 = dc(ma)
ans = 0
# li = list(set(li))
for i in range(len(li)):
for j in range(len(li)):
if i != j:
f0 = li[i]
f1 = li[j]
if f0 == 0 and f1 == 0:
ans = max(ans, ma[0]-2)
continue
ma[f0] -= 1
ma[f1] -= 1
cur = 2
while True:
nxt = f0 + f1
if nxt in ma and ma[nxt] > 0:
f0 = f1 + 1 - 1
f1 = nxt + 1 - 1
ma[nxt] -= 1
cur += 1
else:
break
cur1 = 2
ma[f0] += 1
ma[f1] += 1
while cur1 < cur:
prev = f1 - f0
f1 = f0 + 1 - 1
f0 = prev + 1 - 1
ma[prev] += 1
cur1 += 1
ans = max(ans, cur)
return ans
# Function to take input
def input_test():
n = int(input())
li = list(map(int, input().strip().split(" ")))
out = solution(li)
print(out)
# Function to test my code
def test():
pass
input_test()
# test()
```
No
| 2,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if
1. the sequence consists of at least two elements
2. f0 and f1 are arbitrary
3. fn + 2 = fn + 1 + fn for all n ≥ 0.
You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai.
The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).
Output
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
Examples
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
Note
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is <image>, <image>, <image>, <image>, 28.
Submitted Solution:
```
n = int(input())
a = [int(i) for i in input().split()]
ans = a.count(0)
s = set(a)
for i in range(n):
for j in range(n):
if i == j or a[i] == a[j] == 0: continue
ln = 2
a1 = a[i]
a2 = a[j]
while (a1 + a2) in s and ln < 100:
a1, a2 = a2, a1 + a2
ln += 1
ans = max(ans, ln)
print(ans)
```
No
| 2,090 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
def main():
n = int(input())
seq = [int(c) for c in input().split()]
ans = []
m = n - 1
while m > 0:
for i in range(m):
if seq[i + 1] < seq[i]:
seq[i + 1], seq[i] = seq[i], seq[i + 1]
ans.append((i + 1, i + 2))
m -= 1
out = []
for e in ans:
out.append('%d %d' % e)
print('\n'.join(out))
if __name__ == "__main__":
main()
```
| 2,091 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
n=int(input())
t=list(map(int,input().split()))
for i in range(n):
a=sorted((t[j],j) for j in range(n))
x,j=a[i]
if j>i:
for k in range(j,i,-1):
print(k,k+1)
t[k],t[k-1]=t[k-1],t[k]
```
| 2,092 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
for i in range(n):
for j in range(n - i - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
print(j + 1, j + 2)
```
| 2,093 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
import os
n = int(input())
a = list(map(int, input().split(' ')))
s = []
for i in range (n, -1, -1):
for j in range(i-1):
if a[j] <= a[j+1]:
continue
a[j], a[j+1] = a[j+1], a[j]
s.append('{} {}'.format(j+1, j+2))
print(os.linesep.join(s))
```
| 2,094 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
n = int(input())
l = list(map(int, input().split()))
while l != list(sorted(l)):
for i in range(len(l)-1):
if l[i] > l[i+1]:
temp = l[i]
l[i] = l[i+1]
l[i+1] = temp
print(i+1, i+2)
```
| 2,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
n = int(input())
a = [int(s) for s in input().split()]
for j in range(n):
k = 0
i = 0
while i < n-1:
if a[i] > a[i+1]:
k += 1
tmp = a[i]
a[i] = a[i+1]
a[i+1] = tmp
print(i+1, i+2)
i += 2
i = 1
while i < n-1:
if a[i] > a[i+1]:
k += 1
tmp = a[i]
a[i] = a[i+1]
a[i+1] = tmp
print(i+1, i+2)
i += 2
if k == 0:
break
```
| 2,096 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
from sys import stdin,stdout
n=int(stdin.readline().strip())
#n,m=map(int,stdin.readline().strip().split())
s=list(map(int,stdin.readline().strip().split()))
flag=True
while flag:
flag=False
x=0
while x<n-1:
if s[x]>s[x+1]:
flag=True
y=s[x+1]
s[x+1]=s[x]
s[x]=y
stdout.write("%d %d \n" %(x+1,x+2))
x+=2
else:
x+=1
```
| 2,097 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Tags: constructive algorithms, implementation, sortings
Correct Solution:
```
def zoo(lst):
result = list()
for i in range(len(lst) + 2):
for j in range(len(lst) - 1):
if lst[j] > lst[j + 1]:
result.append([j + 1, j + 2])
lst[j], lst[j + 1] = lst[j + 1], lst[j]
return result
n = int(input())
a = [int(x) for x in input().split()]
for elem in zoo(a):
print(*elem)
```
| 2,098 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
Input
The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo.
The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.
Output
Print the sequence of operations that will rearrange the animals by non-decreasing height.
The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed.
The number of operations should not exceed 20 000.
If the animals are arranged correctly from the start, you are allowed to output nothing.
Examples
Input
4
2 1 4 3
Output
1 4
Input
7
36 28 57 39 66 69 68
Output
1 4
6 7
Input
5
1 2 1 2 1
Output
2 5
3 4
1 4
1 4
Note
Note that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.
Submitted Solution:
```
n=int(input())
a=list(map(int, input().split() ) )
def swap(i):
global a
x=a[i]
a[i]=a[i+1]
a[i+1]=x
print(i+1, i+2)
c=True
while c:
c=False
for i in range(n):
if i<n-1 and a[i]>a[i+1]:
swap(i)
c=True
```
Yes
| 2,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.