message stringlengths 2 23.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 97 109k | cluster float64 0 0 | __index_level_0__ int64 194 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string. | instruction | 0 | 36,886 | 0 | 73,772 |
Tags: constructive algorithms, greedy, sortings, strings
Correct Solution:
```
T=int(input())
for i in range(T):
s=input()
if(s!=s[::-1]):
print(s)
elif(s==s[::-1]):
if(s.count(s[-1])==len(s)):
print(-1)
else:
print(s[1:]+s[0])
``` | output | 1 | 36,886 | 0 | 73,773 |
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 s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string.
Submitted Solution:
```
n = int(input())
for i in range(n):
s = input()
if s.count(s[0]) == len(s):
print(-1)
continue
a = [i for i in s]
if a[0] != a[len(s) -1]:
print(s)
continue
i = 0
while a[0] == a[i]:
i += 1
a[i], a[0] = a[0], a[i]
for i in range(len(a)):
print(a[i], end='')
print()
``` | instruction | 0 | 36,887 | 0 | 73,774 |
Yes | output | 1 | 36,887 | 0 | 73,775 |
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 s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string.
Submitted Solution:
```
import re
q=int(input())
for x in range(q):
s=''
s1=''
n=input()
c=n.count('a')
s=s+'a'*c
l=['a',]
for y in n:
if y in l:
continue
else:
c=n.count(y)
s=s+y*c
l.append(y)
for y in s:
s1=y+s1
if re.match(s,s1):
print("-1")
else:
print(s)
``` | instruction | 0 | 36,888 | 0 | 73,776 |
Yes | output | 1 | 36,888 | 0 | 73,777 |
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 s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string.
Submitted Solution:
```
n = int(input())
for item in range(n):
l = input()
if len(set(l)) == 1:
print(-1)
else:
print("".join(sorted(l)))
``` | instruction | 0 | 36,889 | 0 | 73,778 |
Yes | output | 1 | 36,889 | 0 | 73,779 |
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 s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string.
Submitted Solution:
```
for cas in range(int(input())):
s = input()
s = list(s)
ln = len(s)
s.sort()
if s[0] == s[-1]:
print(-1)
else:print("".join(s))
``` | instruction | 0 | 36,890 | 0 | 73,780 |
Yes | output | 1 | 36,890 | 0 | 73,781 |
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 s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string.
Submitted Solution:
```
n = int(input())
for i in range(n):
t= input()
if len(t) == t.count(t[0]):
print(-1)
elif t == t[::-1]:
for j in range(len(t)-1,-1,-1):
if t[j] != t[0]:
t = t[0] + t[-1] + t[2:len(t)-1] + t[j]
break
print(t)
else:
print(t)
``` | instruction | 0 | 36,891 | 0 | 73,782 |
No | output | 1 | 36,891 | 0 | 73,783 |
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 s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string.
Submitted Solution:
```
for _ in range(int(input())):
s = input().strip()
if s == s[::-1] and len(set(s)) == 1 :
print(-1)
elif s != s[::-1]:
print(s)
else:
print(s[:len(s)//2] + s[len(s)//2:][::-1])
``` | instruction | 0 | 36,892 | 0 | 73,784 |
No | output | 1 | 36,892 | 0 | 73,785 |
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 s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string.
Submitted Solution:
```
t = int(input())
answers = []
for i in range(0,t):
s = input()
res = ' '
x = s[0]
y = s[len(s)-1]
if (x != y):
res = s
else:
for i in range(1,len(s)):
if (s[i] != x and s[i] != y):
res = s[i] + x + s[2:i] + s[i+1:]
break
if (res == ' '):
answers.append(-1)
else:
answers.append(res)
for i in range(0, len(answers)):
print(answers[i])
``` | instruction | 0 | 36,893 | 0 | 73,786 |
No | output | 1 | 36,893 | 0 | 73,787 |
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 s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100) — number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string.
Submitted Solution:
```
t=int(input())
def reverse(string):
string = string[::-1]
return string
def palindrome(str):
rts=reverse(str)
if rts==(str):
return 1
else:
return 0
def special(str):
length=len(str)
a=str[0:int(length/2)]
b=str[length-1:int(length/2)-1:-1]
if palindrome(a+b)==0:
return a+b
else:
return special(a+b)
for i in range(t):
word=input()
change=-1
letter=word[0]
for char in word:
if char!=letter:
change=0
if len(word)==1 or len(word)==2 or change==-1:
print ("-1")
else:
if palindrome(word)==0:
print (word)
else:
print (special(word))
``` | instruction | 0 | 36,894 | 0 | 73,788 |
No | output | 1 | 36,894 | 0 | 73,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins. | instruction | 0 | 37,063 | 0 | 74,126 |
Tags: constructive algorithms, games
Correct Solution:
```
def palindrome(s):
n=len(s)
for i in range ((n+1)//2):
if s[i]!=s[n-i-1]:
return 0
return 1
def one(s):
n=len(s)
c=0
for i in range ((n+1)//2):
if s[i]!=s[n-i-1]:
c+=1
return c
for _ in range (int(input())):
n=int(input())
#a=list(map(int,input().split()))
s=input()
c=s.count('0')
if n%2 and s[n//2]=='0':
if c>2:
print("ALICE")
elif c==2:
print("DRAW")
else:
print("BOB")
elif palindrome(s):
print("BOB")
else:
print("ALICE")
``` | output | 1 | 37,063 | 0 | 74,127 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins. | instruction | 0 | 37,064 | 0 | 74,128 |
Tags: constructive algorithms, games
Correct Solution:
```
for i in range(int(input())):
n = int(input())
s = input()
if s == s[::-1]:
print('DRAW' if n == s.count('1') else('BOB' if s.count('0') % 2 == 0 or s.count('0') == 1 else 'ALICE'))
else:
print('DRAW' if s.count('0') == 2 and n % 2 == 1 and s[n//2] == '0' else 'ALICE')
``` | output | 1 | 37,064 | 0 | 74,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins. | instruction | 0 | 37,065 | 0 | 74,130 |
Tags: constructive algorithms, games
Correct Solution:
```
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
S = list(input())[: -1]
zero = S.count("0")
one = n - zero
diff = 0
for i in range(n): diff += S[i] != S[-1 - i]
if diff == 0:
if zero == 1:
print("BOB")
continue
if zero % 2 == 0:
print("BOB")
continue
else:
print("ALICE")
continue
if diff == 2:
if zero == 1:
print("ALICE")
continue
if zero == 2:
print("DRAW")
continue
if zero % 2 == 0:
print("ALICE")
continue
else:
print("ALICE")
continue
if diff > 2:
print("ALICE")
continue
``` | output | 1 | 37,065 | 0 | 74,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins. | instruction | 0 | 37,066 | 0 | 74,132 |
Tags: constructive algorithms, games
Correct Solution:
```
def getResult(n,s):
count = 0
for c in s:
if c == "0":
count +=1
v = check(s)
if v == 0:
if count%2==0 or count == 1:
return 'BOB'
else:
return "ALICE"
elif v == 1:
count -= 1
if count==0:
return 'ALICE'
elif count == 1:
return "DRAW"
elif count%2 == 0:
return "ALICE"
else:
return "ALICE"
else:
return "ALICE"
def check(s):
l = len(s)
v = 0
for i in range(l//2):
if s[i]!=s[l-i-1]:
v += 1
return v
t = int(input())
for _ in range(t):
n = int(input())
s = input()
print(getResult(n,s))
``` | output | 1 | 37,066 | 0 | 74,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins. | instruction | 0 | 37,067 | 0 | 74,134 |
Tags: constructive algorithms, games
Correct Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=0):
self.BIT = [0]*(n+1)
self.num = n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.size = n
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
if r==self.size:
r = self.num
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
for _ in range(int(input())):
n = int(input())
s = input()
if n%2==0:
a,b = 0,0
for i in range(n//2):
if s[i]=="0" and s[-i-1]=="0":
a += 1
elif (s[i],s[-i-1])!=("1","1"):
b += 1
if a!=0:
if b!=0:
print("ALICE")
else:
print("BOB")
else:
print("ALICE")
else:
if s[n//2]=="1":
a,b = 0,0
for i in range(n//2):
if s[i]=="0" and s[-i-1]=="0":
a += 1
elif (s[i],s[-i-1])!=("1","1"):
b += 1
if a!=0:
if b!=0:
print("ALICE")
else:
print("BOB")
else:
print("ALICE")
else:
a,b = 0,0
for i in range(n//2):
if s[i]=="0" and s[-i-1]=="0":
a += 1
elif (s[i],s[-i-1])!=("1","1"):
b += 1
if a==0:
if b==0:
print("BOB")
elif b==1:
print("DRAW")
else:
print("ALICE")
else:
print("ALICE")
``` | output | 1 | 37,067 | 0 | 74,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins. | instruction | 0 | 37,068 | 0 | 74,136 |
Tags: constructive algorithms, games
Correct Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BufferedIOBase, BytesIO, IOBase
def ispal(arr,n):
l=0
r=n-1
count=0
while l<r:
if arr[l]==arr[r]:
pass
else:
arr[l]=1
arr[r]=1
count+=1
l+=1
r-=1
return count
def main():
for _ in range(int(input())):
n=int(input())
arr=list(map(int,input()))
count=ispal(arr,n)
if count:
bob=count
zeroes=arr.count(0)
if n%2 and arr[n//2]==0:
if bob==1 and zeroes==1:
print("DRAW")
else:
print("ALICE")
else:
print("ALICE")
else:
zeroes=arr.count(0)
if n%2 and arr[n//2]==0:
zeroes-=1
if zeroes:
print("ALICE")
else:
print("BOB")
else:
print("BOB")
#----------------------------------------------------------------------------------------
def nouse0():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse1():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse2():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
def nouse3():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse4():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse5():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
# endregion
if __name__ == '__main__':
main()
``` | output | 1 | 37,068 | 0 | 74,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins. | instruction | 0 | 37,069 | 0 | 74,138 |
Tags: constructive algorithms, games
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
from heapq import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcde'
M = 10**9 + 7
EPS = 1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def INT():return int(input())
def STR():return input()
def INTs():return tuple(map(int,input().split()))
def ARRINT():return [int(i) for i in input().split()]
def ARRSTR():return [i for i in input().split()]
#-------------------------code---------------------------#
def solve(S):
n = len(S)
mid=0
X=0
Y=0
if n%2 and S[n//2]=="0":
mid=1
for i in range(n//2):
if S[i]=="0" and S[n-1-i]=="0":
X+=1
for i in range(n):
if S[i]=="0" and S[n-1-i]=="1":
Y+=1
if Y==0:
if X==0:
if mid==0:
print("DRAW")
else:
print("BOB")
else:
if mid==0:
print("BOB")
else:
print("ALICE")
elif Y==1:
if X==0 and mid==1:
print("DRAW")
elif mid==0:
print("ALICE")
else:
print("ALICE")
else:
print("ALICE")
for _ in range(INT()):
_ = INT()
solve(STR())
``` | output | 1 | 37,069 | 0 | 74,139 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins. | instruction | 0 | 37,070 | 0 | 74,140 |
Tags: constructive algorithms, games
Correct Solution:
```
#b1
for _ in range(int(input())):
input()
inp=str(input())
zz=0
zo=0
for i in range(len(inp)):
if inp[i]==inp[-i-1] and inp[i]=="0":
zz+=1
if inp[i]!=inp[-i-1]:
zo+=1
win=0
zo/=2
if zo==0:
if (zz%2==0 and zz>=2) or zz==1:
win=-1
if zz%2==1 and zz>1:
win=1
else:
if not(zz==zo and zz==1):
win=1
if win==1:
print("ALICE")
if win==-1:
print("BOB")
if win==0:
print("DRAW")
``` | output | 1 | 37,070 | 0 | 74,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
Submitted Solution:
```
import sys
#input = sys.stdin.readline
for _ in range(int(input())):
n=int(input())
s=input()
p=0
for i in range(n//2):
if s[i]!=s[-i-1]:
p+=1
if p==0:
o=s.count('0')
if o%2:
#o-=1
if o==1:
print('BOB')
else:
print('ALICE')
else:
if (o//2)%2==0:
print('BOB')
else:
print('BOB')
else:
o=s.count('0')
if o==2 and n%2 and s[n//2]=='0':
print('DRAW')
else:
print('ALICE')
``` | instruction | 0 | 37,071 | 0 | 74,142 |
Yes | output | 1 | 37,071 | 0 | 74,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
Submitted Solution:
```
from collections import defaultdict
for _ in range(int(input())):
n=int(input())
s=list(input())
if s.count('0')==0:
print('DRAW')
elif n==1:
if s[0]=='0':
print('BOB')
else:
print('DRAW')
elif s==s[::-1]:
if s.count('0')%2==0 or s.count('0')==1:
print('BOB')
else:
print('ALICE')
else:
l=0
r=n-1
c=0
zero=0
if n%2:
if s[n//2]=='0':
zero+=1
while(l<r):
if s[l]!=s[r]:
c+=1
else:
if s[l]=='0':
zero+=2
l+=1
r-=1
if zero==1 and c==1:
print('DRAW')
else:
print('ALICE')
``` | instruction | 0 | 37,072 | 0 | 74,144 |
Yes | output | 1 | 37,072 | 0 | 74,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
s = input()
zeros = s.count('0')
if s == s[::-1]:
if zeros == 1:
print('BOB')
continue
elif zeros % 2 == 1:
print('ALICE')
continue
print('BOB')
else:
if n % 2 == 1 and s[n // 2] == '0' and zeros == 2:
print('DRAW')
else:
print('ALICE')
``` | instruction | 0 | 37,073 | 0 | 74,146 |
Yes | output | 1 | 37,073 | 0 | 74,147 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
s=input()
cnt=0
for i in s:
if i=='0':
cnt+=1
if s==s[::-1]:
if cnt>1 and s[n//2]=='0' and n%2!=0:
print("ALICE")
else:
print("BOB")
else:
if cnt==2 and s[n//2]=='0' and n%2!=0:
print("DRAW")
else:
print("ALICE")
``` | instruction | 0 | 37,074 | 0 | 74,148 |
Yes | output | 1 | 37,074 | 0 | 74,149 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
Submitted Solution:
```
def isPalindrome(s):
for i in range(len(s) // 2):
if s[i] != s[len(s)-i-1]: return False
return True
for _ in range(int(input())):
player = 0
reverse = False
n = int(input())
s = list(input())
count = s.count('1')
score = [0, 0]
# isPalindrome = True
palindex = 0
try:
while True:
# print(''.join(s), player, palindex)
if not reverse and not isPalindrome(s):
reverse = True
elif len(s) % 2 and s[len(s) // 2] == '0':
s[len(s) // 2] = '1'
palindex = len(s) // 2
score[player] += 1
else:
if s[palindex] == '1':
palindex = s.index('0')
s[palindex] = '1'
# isPalindrome = False
else:
palindex = n - palindex - 1
s[palindex] = '1'
# isPalindrome = True
count += 1
score[player] += 1
player = (player + 1) % 2
# print(''.join(s), palindex)
# print(score)
# print()
except: pass
if score[0] == score[1]:
print('DRAW')
elif score[0] < score[1]:
print('ALICE')
else:
print('BOB')
``` | instruction | 0 | 37,075 | 0 | 74,150 |
No | output | 1 | 37,075 | 0 | 74,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
Submitted Solution:
```
t = int(input())
while t:
n = int(input())
s = input()
n = len(s)
cnt1 = cnt2 = 0
mid = int((n-1)/2)
for i in range(0, int((n+1)/2)):
if(s[i] != s[n-1-i]):
cnt1+=1
else:
if(s[i] == '0' and s[n-1-i] == '0'):
cnt2+=1
if ((n%2)==0) or (n%2!=0 and s[mid]=='1'):
if(cnt1==0):
if(cnt2==0):
print("DRAW")
else:
print("BOB")
else:
print("ALICE")
else:
if(cnt1==0):
if(cnt2==0):
print("BOB")
else:
print("ALICE")
else:
if(cnt2==0):
print("DRAW")
else:
if(cnt2>1):
print("ALICE")
else:
print("BOB")
t-=1
``` | instruction | 0 | 37,076 | 0 | 74,152 |
No | output | 1 | 37,076 | 0 | 74,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
Submitted Solution:
```
from bisect import bisect,bisect_left
from collections import *
from heapq import *
from math import gcd,ceil,sqrt,floor,inf
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
class UF:#秩+路径+容量,边数
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
self.size=AI(n,1)
self.edge=A(n)
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
self.edge[pu]+=1
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
self.edge[pu]+=self.edge[pv]+1
self.size[pu]+=self.size[pv]
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
self.edge[pv]+=self.edge[pu]+1
self.size[pv]+=self.size[pu]
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d=AI(n,inf)
d[s]=0
heap=[(0,s)]
vis=A(n)
while heap:
dis,u=heappop(heap)
if vis[u]:
continue
vis[u]=1
for v,w in graph[u]:
if d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def bell(s,g):#bellman-Ford
dis=AI(n,inf)
dis[s]=0
for i in range(n-1):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change=A(n)
for i in range(n):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change[v]=1
return dis
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j,n,m):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
#from random import randint
a=1001
dp=[[[inf]*2 for i in range(a)] for i in range(a)]
dp[0][0][0]=dp[0][0][1]=0
for i in range(a):
for j in range(a-i*2):
if i>1:
dp[i][j][0]=min(1-dp[i-2][j+1][1],dp[i][j][0])
if i&1:
dp[i][j][0]=min(1-dp[i-1][j][1],dp[i][j][0])
if j:
dp[i][j][0]=min(dp[i][j][0],1-dp[i][j-1][1])
if not j:
dp[i][j][1]=dp[i][j][0]
else:
dp[i][j][1]=min(-dp[i][j][0],dp[i][j][0])
'''
@lru_cache(None)
def check(s,t):
if s=='1'*n:
return 0
if s==s[::-1]:
t=0
res=inf
if t==0:
s=list(s)
for i in range(n):
if s[i]=='0':
s[i]='1'
tmp=''.join(s)
res=min(1-check(tmp,1),res)
s[i]='0'
return res
else:
return min(check(s,0),-check(s,0))'''
t=N()
#n=10
#t=1<<n
for i in range(t):
n=N()
'''
s=['0']*n
for j in range(n):
if i&1<<j:
s[j]='1'
s=''.join(s)'''
s=input()
d=0
cp=cs=0
l=0
r=n-1
while l<r:
if s[l]==s[r]:
if s[l]=='0':
cp+=2
else:
cs+=1
l+=1
r-=1
if l==r and s[l]=='0':
cp+=1
d=dp[cp][cs][1]
#ans=check(s,1)
#if d!=ans:
# print(s,d,ans)
if d<0:
ans="ALICE"
elif d==0:
ans='DRAW'
else:
ans="BOB"
print(ans)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
``` | instruction | 0 | 37,077 | 0 | 74,154 |
No | output | 1 | 37,077 | 0 | 74,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
Submitted Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
t = int(input())
for _ in range(t):
n = int(input())
s = input()
z = s.count('0')
a = sum(s[i] != s[-i - 1] for i in range(n // 2))
f = ((z - a) // 2) + 1
s = ((z - a) // 2) - 1
if n % 2:
f, s = s + 1, f
if (z - a) == 0:
f, s = 0, 0
if a:
# skip, change
sc = f + 1 < (a - 1) + s
scd = f + 1 == (a - 1) + s
# skip, no change
sn = s < a + s
snd = s == a + s
# no skip, change
nc = (a - 1) + s < f + 1
ncd = (a - 1) + s == f + 1
# no skip, no change
nn = a + f < s
nnd = a + f == s
if sc or sn or (nc and nn):
print("ALICE")
elif scd or snd or (ncd and nnd):
print("DRAW")
else:
print("BOB")
else:
print("ALICE" if f < s else "BOB")
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | instruction | 0 | 37,078 | 0 | 74,156 |
No | output | 1 | 37,078 | 0 | 74,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given P, a permutation of (1,\ 2,\ ...\ N).
A string S of length N consisting of `0` and `1` is a good string when it meets the following criterion:
* The sequences X and Y are constructed as follows:
* First, let X and Y be empty sequences.
* For each i=1,\ 2,\ ...\ N, in this order, append P_i to the end of X if S_i= `0`, and append it to the end of Y if S_i= `1`.
* If X and Y have the same number of high elements, S is a good string. Here, the i-th element of a sequence is called high when that element is the largest among the elements from the 1-st to i-th element in the sequence.
Determine if there exists a good string. If it exists, find the lexicographically smallest such string.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq P_i \leq N
* P_1,\ P_2,\ ...\ P_N are all distinct.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 ... P_N
Output
If a good string does not exist, print `-1`. If it exists, print the lexicographically smallest such string.
Examples
Input
6
3 1 4 6 2 5
Output
001001
Input
5
1 2 3 4 5
Output
-1
Input
7
1 3 2 5 6 4 7
Output
0001101
Input
30
1 2 6 3 5 7 9 8 11 12 10 13 16 23 15 18 14 24 22 26 19 21 28 17 4 27 29 25 20 30
Output
000000000001100101010010011101
Submitted Solution:
```
import itertools
N = int(input())
P = [int(x) for x in input().split()]
for S in itertools.product("01", repeat=N):
X_max, X_high = 0, 0
Y_max, Y_high = 0, 0
for i, s in enumerate(S):
t = P[i]
if s == "0" and t >= X_max:
X_max = t
X_high += 1
elif s == "1" and t >= Y_max:
Y_max = t
Y_high += 1
if X_high == Y_high:
print("".join(S))
exit()
else:
print(-1)
``` | instruction | 0 | 37,571 | 0 | 75,142 |
No | output | 1 | 37,571 | 0 | 75,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some programming website is establishing a secure communication protocol. For security reasons, they want to choose several more or less random strings.
Initially, they have a string s consisting of lowercase English letters. Now they want to choose q strings using the following steps, and you are to help them.
1. A string x consisting of lowercase English letters and integers l and r (1 ≤ l ≤ r ≤ |s|) are chosen.
2. Consider all non-empty distinct substrings of the s_l s_{l + 1} … s_r, that is all distinct strings s_i s_{i+1} … s_{j} where l ≤ i ≤ j ≤ r. Among all of them choose all strings that are lexicographically greater than x.
3. If there are no such strings, you should print -1. Otherwise print the lexicographically smallest among them.
String a is lexicographically less than string b, if either a is a prefix of b and a ≠ b, or there exists such a position i (1 ≤ i ≤ min(|a|, |b|)), such that a_i < b_i and for all j (1 ≤ j < i) a_j = b_j. Here |a| denotes the length of the string a.
Input
The first line of input contains a non-empty string s (1 ≤ |s| ≤ 10^{5}) consisting of lowercase English letters.
The second line contains an integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of strings to select.
Each of the next q lines contains two integers l, r (1 ≤ l ≤ r ≤ |s|) and a non-empty string x consisting of lowercase English letters. The total length of strings x for all queries does not exceed 2 ⋅ 10^{5}.
Output
Output q lines, each of them should contain the desired string or -1, if there is no such string.
Examples
Input
baa
5
1 2 ba
2 3 a
1 2 b
2 3 aa
1 3 b
Output
-1
aa
ba
-1
ba
Input
bacb
4
1 2 ba
2 3 ac
1 3 ac
3 4 c
Output
-1
c
b
cb
Input
bba
1
1 1 b
Output
-1
Note
Consider the first example.
The string s is "baa". The queries are as follows.
1. We consider the substring s_1 s_2 that is "ba". It has substrings "b", "a" and "ba", since none of them is greater than the query string "ba", the answer is -1.
2. We consider substring "aa". Among its substrings only "aa" is greater than the query string "a". So the answer is "aa".
3. We consider substring "ba". Out of "b", "a" and "ba" only "ba" is greater than the query string "b", so the answer is "ba".
4. We consider substring "aa". No substring of "aa" is greater than the query string "aa" so the answer is -1.
5. We consider substring "baa" and it has (among others) substrings "ba", "baa" which are greater than the query string "b". Since "ba" is lexicographically smaller than "baa", the answer is "ba".
Submitted Solution:
```
def retcount(li, x):
L = []
for i in range(len(li)):
for j in range(i, len(li)):
if i == j:
L.append(li[i])
else:
L.append(li[i]+li[j])
L.append(''.join(li))
L = [w for w in L if len(w)>x]
return L
s = input()
n = int(input())
for i in range(n):
l, r, q = map(str,input().split())
li = list(s[int(l)-1:int(r)])
n = len(q)
a = retcount(li, n)
if len(a) < 1:
print('-1')
else:
print(a[0])
``` | instruction | 0 | 37,750 | 0 | 75,500 |
No | output | 1 | 37,750 | 0 | 75,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova has won n trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.
The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.
Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.
Input
The first line contains one integer n (2 ≤ n ≤ 10^5) — the number of trophies.
The second line contains n characters, each of them is either G or S. If the i-th character is G, then the i-th trophy is a golden one, otherwise it's a silver trophy.
Output
Print the maximum possible length of a subsegment of golden trophies, if Vova is allowed to do at most one swap.
Examples
Input
10
GGGSGGGSGG
Output
7
Input
4
GGGG
Output
4
Input
3
SSS
Output
0
Note
In the first example Vova has to swap trophies with indices 4 and 10. Thus he will obtain the sequence "GGGGGGGSGS", the length of the longest subsegment of golden trophies is 7.
In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is 4.
In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than 0.
Submitted Solution:
```
x=int(input())
string=input()
last=0
new=0
maximum=0
if string.count("G")==0:
print(0)
else:
for i in string:
if i=="G":
new+=1
else:
maximum=new+last
last=new
new=0
if maximum==0:
print(x)
else:
if string.count("S")==1:
print(max(maximum,new+last))
else:
print(max(maximum+1,new+last+1))
``` | instruction | 0 | 37,780 | 0 | 75,560 |
No | output | 1 | 37,780 | 0 | 75,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova has won n trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.
The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.
Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.
Input
The first line contains one integer n (2 ≤ n ≤ 10^5) — the number of trophies.
The second line contains n characters, each of them is either G or S. If the i-th character is G, then the i-th trophy is a golden one, otherwise it's a silver trophy.
Output
Print the maximum possible length of a subsegment of golden trophies, if Vova is allowed to do at most one swap.
Examples
Input
10
GGGSGGGSGG
Output
7
Input
4
GGGG
Output
4
Input
3
SSS
Output
0
Note
In the first example Vova has to swap trophies with indices 4 and 10. Thus he will obtain the sequence "GGGGGGGSGS", the length of the longest subsegment of golden trophies is 7.
In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is 4.
In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than 0.
Submitted Solution:
```
x=int(input())
string=input()
last=0
new=0
maximum=0
if string.count("G")==0:
print(0)
else:
for i in string:
if i=="G":
new+=1
else:
maximum=new+last
last=new
new=0
if maximum==0:
print(x-string.count("S"))
else:
if string.count("S")==1:
print(max(maximum,new+last))
else:
maximum=max(maximum+1,new+last+1)
if maximum>=string.count("G"):
print(string.count("G"))
``` | instruction | 0 | 37,783 | 0 | 75,566 |
No | output | 1 | 37,783 | 0 | 75,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p consisting of exactly 26 integers from 1 to 26 (since it is a permutation, each integer from 1 to 26 occurs in p exactly once) and two strings s and t consisting of lowercase Latin letters.
A substring t' of string t is an occurence of string s if the following conditions are met:
1. |t'| = |s|;
2. for each i ∈ [1, |s|], either s_i = t'_i, or p_{idx(s_i)} = idx(t'_i), where idx(c) is the index of character c in Latin alphabet (idx(a) = 1, idx(b) = 2, idx(z) = 26).
For example, if p_1 = 2, p_2 = 3, p_3 = 1, s = abc, t = abcaaba, then three substrings of t are occurences of s (they are t' = abc, t' = bca and t' = aba).
For each substring of t having length equal to |s|, check if it is an occurence of s.
Input
The first line contains 26 integers p_1, p_2, ..., p_{26} (1 ≤ p_i ≤ 26, all these integers are pairwise distinct).
The second line contains one string s, and the third line contains one string t (2 ≤ |s| ≤ |t| ≤ 2 ⋅ 10^5) both consisting of lowercase Latin letters.
Output
Print a string of |t| - |s| + 1 characters, each character should be either 0 or 1. The i-th character should be 1 if and only if the substring of t starting with the i-th character and ending with the (i + |s| - 1)-th character (inclusive) is an occurence of s.
Example
Input
2 3 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
abc
abcaaba
Output
11001
Submitted Solution:
```
print("bing bing bong bong")
``` | instruction | 0 | 37,856 | 0 | 75,712 |
No | output | 1 | 37,856 | 0 | 75,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p consisting of exactly 26 integers from 1 to 26 (since it is a permutation, each integer from 1 to 26 occurs in p exactly once) and two strings s and t consisting of lowercase Latin letters.
A substring t' of string t is an occurence of string s if the following conditions are met:
1. |t'| = |s|;
2. for each i ∈ [1, |s|], either s_i = t'_i, or p_{idx(s_i)} = idx(t'_i), where idx(c) is the index of character c in Latin alphabet (idx(a) = 1, idx(b) = 2, idx(z) = 26).
For example, if p_1 = 2, p_2 = 3, p_3 = 1, s = abc, t = abcaaba, then three substrings of t are occurences of s (they are t' = abc, t' = bca and t' = aba).
For each substring of t having length equal to |s|, check if it is an occurence of s.
Input
The first line contains 26 integers p_1, p_2, ..., p_{26} (1 ≤ p_i ≤ 26, all these integers are pairwise distinct).
The second line contains one string s, and the third line contains one string t (2 ≤ |s| ≤ |t| ≤ 2 ⋅ 10^5) both consisting of lowercase Latin letters.
Output
Print a string of |t| - |s| + 1 characters, each character should be either 0 or 1. The i-th character should be 1 if and only if the substring of t starting with the i-th character and ending with the (i + |s| - 1)-th character (inclusive) is an occurence of s.
Example
Input
2 3 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
abc
abcaaba
Output
11001
Submitted Solution:
```
r=[0]
idx=dict()
j=0
for c in "abcdefghijklmnopqrstuvwxyz":
j=j+1
idx[c]=j
p=r+list(map(int,input().split()))
s=input("entrer s ")
t=input("entrer t" )
def testv ( ch,s , p ):
i=0
test= (ch[i]==s[i]) or(p[idx[s[i]]]==idx[ch[i]])
while ((test== True) and (i<len(s))):
test= (ch[i]==s[i]) or(p[idx[s[i]]]==idx[ch[i]])
i=i+1
return test
def cc (j):
if j<0 :
return ''
else:
return cc(j-1)+str(int((testv(t[j:j+len(s)],s,p))))
print(cc(len(t)-len(s)))
``` | instruction | 0 | 37,857 | 0 | 75,714 |
No | output | 1 | 37,857 | 0 | 75,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p consisting of exactly 26 integers from 1 to 26 (since it is a permutation, each integer from 1 to 26 occurs in p exactly once) and two strings s and t consisting of lowercase Latin letters.
A substring t' of string t is an occurence of string s if the following conditions are met:
1. |t'| = |s|;
2. for each i ∈ [1, |s|], either s_i = t'_i, or p_{idx(s_i)} = idx(t'_i), where idx(c) is the index of character c in Latin alphabet (idx(a) = 1, idx(b) = 2, idx(z) = 26).
For example, if p_1 = 2, p_2 = 3, p_3 = 1, s = abc, t = abcaaba, then three substrings of t are occurences of s (they are t' = abc, t' = bca and t' = aba).
For each substring of t having length equal to |s|, check if it is an occurence of s.
Input
The first line contains 26 integers p_1, p_2, ..., p_{26} (1 ≤ p_i ≤ 26, all these integers are pairwise distinct).
The second line contains one string s, and the third line contains one string t (2 ≤ |s| ≤ |t| ≤ 2 ⋅ 10^5) both consisting of lowercase Latin letters.
Output
Print a string of |t| - |s| + 1 characters, each character should be either 0 or 1. The i-th character should be 1 if and only if the substring of t starting with the i-th character and ending with the (i + |s| - 1)-th character (inclusive) is an occurence of s.
Example
Input
2 3 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
abc
abcaaba
Output
11001
Submitted Solution:
```
a=list(map(int,input().split()))
l=list(input())
k=list(input())
x=len(l)
s=k[0:x]
y=len(s)
final=''
ind=y
for i in range(len(k)-x+1):
c=0
for j in range(y):
if(s[j]==l[j])or(ord(s[j])-97==a[j]-1):
c+=1
if(c==x):
final=final+'1'
else:
final=final+'0'
s.pop(0)
if(i!=len(k)-x):
s.append(k[ind])
ind+=1
print(final)
``` | instruction | 0 | 37,858 | 0 | 75,716 |
No | output | 1 | 37,858 | 0 | 75,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p consisting of exactly 26 integers from 1 to 26 (since it is a permutation, each integer from 1 to 26 occurs in p exactly once) and two strings s and t consisting of lowercase Latin letters.
A substring t' of string t is an occurence of string s if the following conditions are met:
1. |t'| = |s|;
2. for each i ∈ [1, |s|], either s_i = t'_i, or p_{idx(s_i)} = idx(t'_i), where idx(c) is the index of character c in Latin alphabet (idx(a) = 1, idx(b) = 2, idx(z) = 26).
For example, if p_1 = 2, p_2 = 3, p_3 = 1, s = abc, t = abcaaba, then three substrings of t are occurences of s (they are t' = abc, t' = bca and t' = aba).
For each substring of t having length equal to |s|, check if it is an occurence of s.
Input
The first line contains 26 integers p_1, p_2, ..., p_{26} (1 ≤ p_i ≤ 26, all these integers are pairwise distinct).
The second line contains one string s, and the third line contains one string t (2 ≤ |s| ≤ |t| ≤ 2 ⋅ 10^5) both consisting of lowercase Latin letters.
Output
Print a string of |t| - |s| + 1 characters, each character should be either 0 or 1. The i-th character should be 1 if and only if the substring of t starting with the i-th character and ending with the (i + |s| - 1)-th character (inclusive) is an occurence of s.
Example
Input
2 3 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
abc
abcaaba
Output
11001
Submitted Solution:
```
p=[int(x) for x in input().split()]
s=input()
t=input()
S=len(s);T=len(t)
for i in range(T-S+1):
k=t[i:i+S]
f=0
for j in range(len(k)):
ca=p[ord(s[j])-96-1]
cb=ord(k[j])-96
#print(ca,cb)
if(s[j]==k[j] or ca==cb):
f+=1
if(f==3):
print(1,end='')
else:
print(0,end='')
``` | instruction | 0 | 37,859 | 0 | 75,718 |
No | output | 1 | 37,859 | 0 | 75,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.
Output
Print m lines, each should contain one integer — the answer to the question after the corresponding operation.
Example
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4
Output
1
2
0
Note
On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.
On the second operation the string "01100" is created. Now all strings of length k = 2 are present.
On the third operation the string "1111111111" is created. There is no zero, so the answer is 0. | instruction | 0 | 38,264 | 0 | 76,528 |
Tags: bitmasks, brute force, dp, implementation, strings
Correct Solution:
```
from sys import stdin, stdout
K = 20
def findAllStrings(s):
n = len(s)
sDict = {}
for i in range(1,K+1):
sDict[i]=set()
for x in range(n-i+1):
sDict[i].add(s[x:x+i])
return sDict
n = int(stdin.readline().rstrip())
stringDicts = []
stringEnd = []
stringBegin = []
for i in range(n):
s = stdin.readline().rstrip()
stringDicts.append(findAllStrings(s))
if len(s)<K:
stringEnd.append(s)
stringBegin.append(s)
else:
stringEnd.append(s[-20:])
stringBegin.append(s[:20])
m = int(stdin.readline().rstrip())
for _ in range(m):
a,b = map(int,stdin.readline().rstrip().split())
a-=1
b-=1
sDict1 = findAllStrings(stringEnd[a]+stringBegin[b])
sDict2 = stringDicts[a]
sDict3 = stringDicts[b]
sDict={}
for i in range(1,K+1):
sDict[i] = sDict1[i]|sDict2[i]|sDict3[i]
stringDicts.append(sDict)
for i in range(1,K+1):
if len(sDict[i])!=2**i:
print(i-1)
break
if len(stringBegin[a])<K and len(stringBegin[a])+len(stringBegin[b])<K:
stringBegin.append(stringBegin[a]+stringBegin[b])
elif len(stringBegin[a])<K:
s = stringBegin[a]+stringBegin[b]
stringBegin.append(s[:K])
else:
stringBegin.append(stringBegin[a])
if len(stringEnd[b])<K and len(stringEnd[a])+len(stringEnd[b])<K:
stringEnd.append(stringEnd[a]+stringEnd[b])
elif len(stringEnd[b])<K:
s = stringEnd[a]+stringEnd[b]
stringEnd.append(s[-K:])
else:
stringEnd.append(stringEnd[b])
``` | output | 1 | 38,264 | 0 | 76,529 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.
Output
Print m lines, each should contain one integer — the answer to the question after the corresponding operation.
Example
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4
Output
1
2
0
Note
On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.
On the second operation the string "01100" is created. Now all strings of length k = 2 are present.
On the third operation the string "1111111111" is created. There is no zero, so the answer is 0. | instruction | 0 | 38,265 | 0 | 76,530 |
Tags: bitmasks, brute force, dp, implementation, strings
Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def main():
n = I()
t = [[S(), [set() for _ in range(151)]] for _ in range(n)]
m = I()
q = [LI_() for _ in range(m)]
for c in t:
s = c[0]
l = len(s)
for i in range(1,min(151,l+1)):
for j in range(l-i+1):
c[1][i].add(s[j:j+i])
rr = []
for li,ri in q:
l = t[li]
r = t[ri]
c = ['',[l[1][i]|r[1][i] for i in range(151)]]
for i in range(1,min(150,len(l[0])+1)):
ls = l[0][-i:]
for j in range(1,min(151-i,len(r[0])+1)):
c[1][i+j].add(ls+r[0][:j])
c[0] = l[0] + r[0]
if len(c[0]) > 300:
c[0] = c[0][:150] + c[0][-150:]
t.append(c)
r = 0
for i in range(1,151):
tt = len(c[1][i])
if tt != 2**i:
break
r = i
rr.append(r)
return '\n'.join(map(str,rr))
print(main())
``` | output | 1 | 38,265 | 0 | 76,531 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.
Output
Print m lines, each should contain one integer — the answer to the question after the corresponding operation.
Example
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4
Output
1
2
0
Note
On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.
On the second operation the string "01100" is created. Now all strings of length k = 2 are present.
On the third operation the string "1111111111" is created. There is no zero, so the answer is 0. | instruction | 0 | 38,266 | 0 | 76,532 |
Tags: bitmasks, brute force, dp, implementation, strings
Correct Solution:
```
from sys import stdin, stdout
k = 20
def findAllStrings(s):
n = len(s)
sdict = {}
for i in range(1,k+1):
sdict[i]=set()
for x in range(n-i+1):
sdict[i].add(s[x:x+i])
return sdict
n = int(stdin.readline().rstrip())
strdict = []
stringend = []
stringbegin = []
for i in range(n):
s = stdin.readline().rstrip()
strdict.append(findAllStrings(s))
if len(s)<k:
stringend.append(s)
stringbegin.append(s)
else:
stringend.append(s[-20:])
stringbegin.append(s[:20])
m = int(stdin.readline().rstrip())
for _ in range(m):
a,b = map(int,stdin.readline().rstrip().split())
a-=1
b-=1
sdict1 = findAllStrings(stringend[a]+stringbegin[b])
sdict2 = strdict[a]
sdict3 = strdict[b]
sdict={}
for i in range(1,k+1):
sdict[i] = sdict1[i]|sdict2[i]|sdict3[i]
strdict.append(sdict)
for i in range(1,k+1):
if len(sdict[i])!=2**i:
print(i-1)
break
if len(stringbegin[a])<k and len(stringbegin[a])+len(stringbegin[b])<k:
stringbegin.append(stringbegin[a]+stringbegin[b])
elif len(stringbegin[a])<k:
s = stringbegin[a]+stringbegin[b]
stringbegin.append(s[:k])
else:
stringbegin.append(stringbegin[a])
if len(stringend[b])<k and len(stringend[a])+len(stringend[b])<k:
stringend.append(stringend[a]+stringend[b])
elif len(stringend[b])<k:
s = stringend[a]+stringend[b]
stringend.append(s[-k:])
else:
stringend.append(stringend[b])
``` | output | 1 | 38,266 | 0 | 76,533 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.
Output
Print m lines, each should contain one integer — the answer to the question after the corresponding operation.
Example
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4
Output
1
2
0
Note
On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.
On the second operation the string "01100" is created. Now all strings of length k = 2 are present.
On the third operation the string "1111111111" is created. There is no zero, so the answer is 0. | instruction | 0 | 38,267 | 0 | 76,534 |
Tags: bitmasks, brute force, dp, implementation, strings
Correct Solution:
```
from math import log
n = int(input())
p = [bin(p)[2:] for p in range(0,512)]
def mset(s):
ss = set()
for k in range(0,10):
for pi in range(0,2 ** k):
cs = p[pi]
cs = (k - len(cs)) * "0" + cs
if cs in s:
ss.add(cs)
return ss
def q(s):
for k in range(0,10):
for pi in range(0,2 ** k):
cs = p[pi]
cs = (k - len(cs)) * "0" + cs
if not cs in s:
return k - 1
s = [[v[:9], v[-9:], mset(v)] for v in [input() for i in range(n)]]
for qa, qb in [[int(v) - 1 for v in input().split()] for i in range(int(input()))]:
v = [s[qa][0], s[qb][1], mset(s[qa][1] + s[qb][0]) | s[qa][2] | s[qb][2]]
if len(v[0]) < 9:
v[0] = (v[0] + s[qb][0])[:9]
if len(v[1]) < 9:
v[1] = (s[qa][1] + s[qb][1])[-9:]
s += [v]
print(max(q(v[2]),0))
``` | output | 1 | 38,267 | 0 | 76,535 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.
Output
Print m lines, each should contain one integer — the answer to the question after the corresponding operation.
Example
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4
Output
1
2
0
Note
On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.
On the second operation the string "01100" is created. Now all strings of length k = 2 are present.
On the third operation the string "1111111111" is created. There is no zero, so the answer is 0. | instruction | 0 | 38,268 | 0 | 76,536 |
Tags: bitmasks, brute force, dp, implementation, strings
Correct Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
"""
created by shhuan at 2017/10/5 15:00
"""
N = int(input())
S = ['']
for i in range(N):
S.append(input())
M = int(input())
# t0 = time.time()
# N = 3
# S = ["", "00010110000", "110101110101101010101101101110100010000001101101011000010001011000010101", "11100101100111010"]
# M = 1000
A = [[set() for _ in range(10)] for _ in range(M+N+1)]
D = collections.defaultdict(int)
for i in range(1, N+1):
for j in range(1, 10):
s = S[i]
if j > len(s):
break
for k in range(len(s)-j+1):
A[i][j].add(int(s[k:k+j], 2))
if all(v in A[i][j] for v in range(2**j)):
D[i] = j
for i in range(M):
# a, b = random.randint(1, i+N), random.randint(1, i+N)
a, b = map(int, input().split())
s, sa, sb = S[a] + S[b], S[a], S[b]
if len(s) > 30:
S.append(s[:10] + s[-10:])
else:
S.append(s)
ai = i+N+1
d = max(D[a], D[b]) + 1
for dv in range(d, 10):
if len(sa) + len(sb) < dv:
break
A[ai][dv] = A[a][dv] | A[b][dv] | {int(v, 2) for v in {sa[-i:] + sb[:dv-i] for i in range(1, dv+1)} if len(v) == dv}
ans = d-1
for dv in range(d, 10):
if any(v not in A[ai][dv] for v in range(2**dv)):
break
ans = dv
print(ans)
D[ai] = ans
# print(time.time() - t0)
``` | output | 1 | 38,268 | 0 | 76,537 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.
Output
Print m lines, each should contain one integer — the answer to the question after the corresponding operation.
Example
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4
Output
1
2
0
Note
On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.
On the second operation the string "01100" is created. Now all strings of length k = 2 are present.
On the third operation the string "1111111111" is created. There is no zero, so the answer is 0.
Submitted Solution:
```
import sys
read = sys.stdin.readline
def solve(n, numbers, m, concatenation):
for a, b in concatenation:
numbers.append(numbers[a-1] + numbers[b-1])
for i in range(n, n+m):
cur = numbers[i]
str_zero = "0"
str_one = "1"
find = cur.find(str_zero)
while find != -1:
str_zero += "0"
find = cur.find(str_zero)
find = cur.find(str_one)
while find != -1:
str_one += "1"
find = cur.find(str_one)
print(str(min(len(str_zero)-1, len(str_one)-1)))
def run():
n = int(read().replace("\n", "").replace("\r\n", ""))
numbers = []
for _ in range(n):
numbers.append(read().replace("\n", "").replace("\r\n", ""))
m = int(read().replace("\n", "").replace("\r\n", ""))
concatenation = []
for _ in range(m):
concatenation.append(list(map(int, read().replace("\n", "").replace("\r\n", "").split())))
solve(n, numbers, m, concatenation)
run()
``` | instruction | 0 | 38,269 | 0 | 76,538 |
No | output | 1 | 38,269 | 0 | 76,539 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.
Output
Print m lines, each should contain one integer — the answer to the question after the corresponding operation.
Example
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4
Output
1
2
0
Note
On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.
On the second operation the string "01100" is created. Now all strings of length k = 2 are present.
On the third operation the string "1111111111" is created. There is no zero, so the answer is 0.
Submitted Solution:
```
def kont(a,b):
ed=max(sp[a][1],sp[b][1])
ze=max(sp[a][0],sp[b][0])
if sp[a][4]==sp[b][2]:
if sp[a][4]=='1':
ed=max(ed,sp[a][5]+sp[b][3])
else:
ze=max(ed,sp[a][5]+sp[b][3])
if sp[b][6]==max(sp[b][3],sp[b][5]) and sp[b][4]==sp[a][2]:
kend=sp[b][6]+sp[a][5]
end=sp[b][2]
else:
kend=sp[b][5]
end=sp[b][4]
if sp[a][6]==max(sp[a][3],sp[a][5]) and sp[b][2]==sp[a][4]:
kbe=sp[a][6]+sp[b][3]
be=sp[b][2]
else:
kbe=sp[a][3]
be=sp[a][2]
sp.append((ze,ed,be,kbe,end,kend,sp[a][6]+sp[b][6]))
print(min(ed,ze))
n=int(input())
sp=[]
for o in range(n):
s=input()
ze=0
ed=0
el=s[0]
k=1
p=len(s)
for i in range(1,p):
if s[i]==el:
k+=1
else:
if el=='0':
ze=max(ze,k)
else:
ed=max(ed,k)
k=1
el=s[i]
if el=='0':
ze=max(ze,k)
else:
ed=max(ed,k)
end=el
kend=k
el=s[0]
k=1
for i in range(1,p):
if s[i]==el:
k+=1
else:
break
sp.append((ze,ed,el,k,end,kend,p))
n=int(input())
for i in range(n):
a,b=map(int,input().split())
a-=1
b-=1
kont(a,b)
``` | instruction | 0 | 38,270 | 0 | 76,540 |
No | output | 1 | 38,270 | 0 | 76,541 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.
Output
Print m lines, each should contain one integer — the answer to the question after the corresponding operation.
Example
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4
Output
1
2
0
Note
On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.
On the second operation the string "01100" is created. Now all strings of length k = 2 are present.
On the third operation the string "1111111111" is created. There is no zero, so the answer is 0.
Submitted Solution:
```
from math import log
n = int(input())
p = [bin(p)[2:] for p in range(0,256)]
def q(s):
for k in range(0,10):
for pi in range(0,2**k):
cs = p[pi]
cs = (k-len(cs))*"0"+cs
if not cs in s:
return k - 1
s = [(v, q(v)) for v in [input() for i in range(n)]]
for qa, qb in [[int(v) - 1 for v in input().split()] for i in range(int(input()))]:
vs = s[qa][0] + s[qb][0]
qs = q(vs)
if len(vs) > 100:
vs = vs[:50] + vs[-50:]
v = (vs, max(qs, s[qa][1], s[qb][1], 0))
s += [v]
print(v[1])
``` | instruction | 0 | 38,271 | 0 | 76,542 |
No | output | 1 | 38,271 | 0 | 76,543 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n strings s1, s2, ..., sn consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation saisbi is saved into a new string sn + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2k such strings) are substrings of the new string. If there is no such k, print 0.
Input
The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s1, s2, ..., sn (1 ≤ |si| ≤ 100), one per line. The total length of strings is not greater than 100.
The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers ai abd bi (1 ≤ ai, bi ≤ n + i - 1) — the number of strings that are concatenated to form sn + i.
Output
Print m lines, each should contain one integer — the answer to the question after the corresponding operation.
Example
Input
5
01
10
101
11111
0
3
1 2
6 5
4 4
Output
1
2
0
Note
On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1.
On the second operation the string "01100" is created. Now all strings of length k = 2 are present.
On the third operation the string "1111111111" is created. There is no zero, so the answer is 0.
Submitted Solution:
```
from math import log
n = int(input())
p = [bin(p)[2:] for p in range(0,256)]
def q(s):
for k in range(0,10):
for pi in range(0,2**k):
cs = p[pi]
cs = (k-len(cs))*"0"+cs
if not cs in s:
return k - 1
node = lambda s: (s[:9],s[-9:],q(s))
s = [node(v) for v in [input() for i in range(n)]]
for qa, qb in [[int(v) - 1 for v in input().split()] for i in range(int(input()))]:
vs = s[qa][0] + "#" + s[qa][1] + s[qb][0] + "#" + s[qb][1]
v = (vs.replace("#","")[:9], vs.replace("#","")[-9:], max(0, s[qa][2], s[qb][2], q(vs)))
s += [v]
print(v)
``` | instruction | 0 | 38,272 | 0 | 76,544 |
No | output | 1 | 38,272 | 0 | 76,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoyaliu
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input
The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.
Output
Print a single integer — the number of subsequences "QAQ" in the string.
Examples
Input
QAQAQYSYIOIWIN
Output
4
Input
QAQQQZZYNOIWIN
Output
3
Note
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | instruction | 0 | 38,273 | 0 | 76,546 |
Tags: brute force, dp
Correct Solution:
```
"""
tb
"""
s=input()
c=0
l=len(s)
arr=[0]
for i in s:
if i=='Q':
arr.append(arr[-1]+1)
else:
arr.append(arr[-1])
for i in range(l):
if s[i]=='A':
c=c+arr[i+1]*(arr[-1]-arr[i+1])
print(c)
``` | output | 1 | 38,273 | 0 | 76,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoyaliu
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input
The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.
Output
Print a single integer — the number of subsequences "QAQ" in the string.
Examples
Input
QAQAQYSYIOIWIN
Output
4
Input
QAQQQZZYNOIWIN
Output
3
Note
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | instruction | 0 | 38,274 | 0 | 76,548 |
Tags: brute force, dp
Correct Solution:
```
s = input()
res = 0
for i in range(0, len(s)):
if s[i] == 'Q':
for i in range(i + 1, len(s)):
if s[i] == 'A':
for i in range(i + 1, len(s)):
if s[i] == 'Q':
res += 1
print(res)
``` | output | 1 | 38,274 | 0 | 76,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoyaliu
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input
The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.
Output
Print a single integer — the number of subsequences "QAQ" in the string.
Examples
Input
QAQAQYSYIOIWIN
Output
4
Input
QAQQQZZYNOIWIN
Output
3
Note
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | instruction | 0 | 38,275 | 0 | 76,550 |
Tags: brute force, dp
Correct Solution:
```
a=[]
for i in input():
if i in "AQ":
a.append(i)
n=len(a)
count=0
for i in range(n):
for j in range(n):
for k in range(n):
if a[i]==a[k]=="Q" and a[j]=="A" and i<j<k:
count+=1
print(count)
``` | output | 1 | 38,275 | 0 | 76,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoyaliu
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input
The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.
Output
Print a single integer — the number of subsequences "QAQ" in the string.
Examples
Input
QAQAQYSYIOIWIN
Output
4
Input
QAQQQZZYNOIWIN
Output
3
Note
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | instruction | 0 | 38,276 | 0 | 76,552 |
Tags: brute force, dp
Correct Solution:
```
s = input()
res = 0
while True:
a = s.find("A")
if a == -1:
break
res += s[:a].count("Q") * s[a + 1:].count("Q")
s = s[:a] + s[a + 1:]
print(res)
``` | output | 1 | 38,276 | 0 | 76,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoyaliu
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input
The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.
Output
Print a single integer — the number of subsequences "QAQ" in the string.
Examples
Input
QAQAQYSYIOIWIN
Output
4
Input
QAQQQZZYNOIWIN
Output
3
Note
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | instruction | 0 | 38,277 | 0 | 76,554 |
Tags: brute force, dp
Correct Solution:
```
s = input()
cnt = 0
for i in range(len(s)):
for j in range(i + 1, len(s)):
for k in range(j + 1, len(s)):
if s[i] == s[k] == 'Q' and s[j] == 'A':
cnt += 1
print(cnt)
``` | output | 1 | 38,277 | 0 | 76,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoyaliu
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input
The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.
Output
Print a single integer — the number of subsequences "QAQ" in the string.
Examples
Input
QAQAQYSYIOIWIN
Output
4
Input
QAQQQZZYNOIWIN
Output
3
Note
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | instruction | 0 | 38,278 | 0 | 76,556 |
Tags: brute force, dp
Correct Solution:
```
s = str(input())
c=0
for i in range(len(s)):
for j in range(i,len(s)):
for k in range(j,len(s)):
if s[i]=="Q" and s[j]=="A" and s[k]=="Q": c+=1
print(c)
``` | output | 1 | 38,278 | 0 | 76,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoyaliu
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input
The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.
Output
Print a single integer — the number of subsequences "QAQ" in the string.
Examples
Input
QAQAQYSYIOIWIN
Output
4
Input
QAQQQZZYNOIWIN
Output
3
Note
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | instruction | 0 | 38,279 | 0 | 76,558 |
Tags: brute force, dp
Correct Solution:
```
a = 0
d = 0
ans = 0
for i in input():
if i == "Q":
ans += d
a += 1
elif i== "A":
d += a
print(ans)
``` | output | 1 | 38,279 | 0 | 76,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoyaliu
Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.
Input
The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters.
Output
Print a single integer — the number of subsequences "QAQ" in the string.
Examples
Input
QAQAQYSYIOIWIN
Output
4
Input
QAQQQZZYNOIWIN
Output
3
Note
In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN". | instruction | 0 | 38,280 | 0 | 76,560 |
Tags: brute force, dp
Correct Solution:
```
s=list(input())
cnt=0
for i in range(len(s)):
if s[i]=='Q':
for j in range(i,len(s)):
if s[j]=='A':
for k in range(j,len(s)):
if s[k]=='Q':
cnt+=1
print(cnt)
``` | output | 1 | 38,280 | 0 | 76,561 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.