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 |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Submitted Solution:
```
s=input()
n=len(s)
tot=0
S=list(s)
for i in range(n-1,-1,-1):
if s[i]=='0':
tot+=1
elif tot:
tot-=1
else:
S[i]='0'
print(''.join(S))
``` | instruction | 0 | 44,685 | 0 | 89,370 |
Yes | output | 1 | 44,685 | 0 | 89,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Submitted Solution:
```
from sys import stdin
s=stdin.readline().strip()
dp=[0 for i in range(len(s)+2)]
ons=[0 for i in range(len(s)+2)]
zs=[0 for i in range(len(s)+2)]
for i in range(len(s)-1,-1,-1):
if s[i]=="1":
ons[i]+=1
if(i!=len(s)-1):
ons[i]+=ons[i+1]
z=0
for i in range(len(s)-1,-1,-1):
if(s[i]=="1"):
dp[i]=max(1+ons[i+1],z)
else:
dp[i]=max(dp[i+1]+1,1+ons[i+1])
z=dp[i]
zs[i]=z
ans=""
for i in range(len(s)):
if s[i]=="1":
x=dp[i]
y=1+dp[i+1]
if x==y:
ans+="0"
else:
ans+="1"
else:
ans+="0"
print(ans)
``` | instruction | 0 | 44,686 | 0 | 89,372 |
Yes | output | 1 | 44,686 | 0 | 89,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Submitted Solution:
```
S = input()
N = len(S)
p = q = 0
prv = S[0]
c = 0
C = []
if S[0] == '1':
C.append(0)
for ch in S:
if ch != prv:
C.append(c)
c = 1
prv = ch
else:
c += 1
C.append(c)
ans = []
r = 0
L = len(C)
for i in range(L-1, -1, -1):
c = C[i]
if i % 2:
r += c
if i != L-1:
m = max(min(c-1, r), 0)
else:
m = max(min(c, r), 0)
if m:
r -= m
ans.append("0"*m + "1"*(c-m))
else:
ans.append("1"*c)
else:
r -= c
ans.append("0"*c)
ans.reverse()
print(*ans, sep='')
``` | instruction | 0 | 44,687 | 0 | 89,374 |
Yes | output | 1 | 44,687 | 0 | 89,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Submitted Solution:
```
S = list(map(int,input().strip()))
N = len(S)
stack = []
for i in range(N):
s = S[i]
if s == 0 and stack and stack[-1][0] == 1:
stack.pop()
else:
stack.append((s, i))
T = S[:]
for i in tuple(map(list, zip(*stack)))[1]:
T[i] = 0
print(''.join(map(str, T)))
``` | instruction | 0 | 44,688 | 0 | 89,376 |
Yes | output | 1 | 44,688 | 0 | 89,377 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Submitted Solution:
```
pp = input()
z = 1 if pp[0]=='0' else 0
zc = [z]
l = 1
lndl = [l]
for p in pp[1:]:
l = max(z + 1, l + (1 if p == '1' else 0))
z += 1 if p == '0' else 0
lndl.append(l)
zc.append(z)
lnda = lndl[-1]
o = 1 if pp[-1]=='1' else 0
oc = [o]
l = 1
lndr = [l]
for p in reversed(pp[:-1]):
l = max(o + 1, l + (1 if p == '0' else 0))
o += 1 if p == '1' else 0
lndr.append(l)
oc.append(o)
oc.reverse()
lndr.reverse()
jj = []
ez = 0
if pp[0] == '1':
if max(oc[1], lndr[1] + 1) != lnda :
jj.append('1')
else:
jj.append('0')
ez += 1
else:
jj.append('0')
for p, l, o, z, r in zip(pp[1:-1],lndl, oc[2:], zc, lndr[2:]):
if p == '1':
if max(l + o, z + ez + 1 + r) != lnda:
jj.append('1')
else:
jj.append('0')
ez += 1
else:
jj.append('0')
jj.append('0')
print(''.join(jj))
``` | instruction | 0 | 44,689 | 0 | 89,378 |
No | output | 1 | 44,689 | 0 | 89,379 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Submitted Solution:
```
a=input()
a=list(a)
l=[]
for i in range(0,len(a)):
l.append([a[i],i])
i=1
while(i<len(l)):
if l[i][0]=='0' and l[i-1][0]=='1':
l.pop(i)
l.pop(i-1)
i-=2
i+=1
for i in range(0,len(l)):
a[l[i][1]]=0
print (*a,sep="")
``` | instruction | 0 | 44,690 | 0 | 89,380 |
No | output | 1 | 44,690 | 0 | 89,381 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Submitted Solution:
```
s = input()
def check(l, r, s):
m = 0
c = 1
for i in range(l + 1, r):
if s[i] >= s[i - 1]:
c += 1
else:
m = max(m, c)
c = 1
m = max(m, c)
return m
t = [0 for i in range(len(s))]
for i in range(len(s)):
if i < (len(s) - 1):
#print(1)
if s[i] == '1' and s[i + 1] == '0':
t[i] = 1
for i in t:
print(i, end = '')
``` | instruction | 0 | 44,691 | 0 | 89,382 |
No | output | 1 | 44,691 | 0 | 89,383 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Submitted Solution:
```
def int_multiple():
return [int(c) for c in input().split()]
def int_single():
return int(input())
def str_multiple():
return [c for c in input().split()]
def str_single():
return input()
# start
ss = str_single()
fst = ""
sec = ""
ss += "1"
s = [c for c in ss]
for i in range(0, len(s)-1):
fst = s[i]
sec = s[i+1]
if fst == "1" and sec == "1":
s[i] = "0"
d = ""
for i in range(len(s)-1):
d += s[i]
print(d)
``` | instruction | 0 | 44,692 | 0 | 89,384 |
No | output | 1 | 44,692 | 0 | 89,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different with hard version only by constraints on total answers length
It is an interactive problem
Venya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask two types of queries:
* ? l r – ask to list all substrings of s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.
* ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses.
The player can ask no more than 3 queries of the first type.
To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)^2.
Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.
Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.
Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.
Input
First line contains number n (1 ≤ n ≤ 100) — the length of the picked string.
Interaction
You start the interaction by reading the number n.
To ask a query about a substring from l to r inclusively (1 ≤ l ≤ r ≤ n), you should output
? l r
on a separate line. After this, all substrings of s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.
In the case, if you ask an incorrect query, ask more than 3 queries of the first type or there will be more than (n+1)^2 substrings returned in total, you will receive verdict Wrong answer.
To guess the string s, you should output
! s
on a separate line.
After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.
Hack format
To hack a solution, use the following format:
The first line should contain one integer n (1 ≤ n ≤ 100) — the length of the string, and the following line should contain the string s.
Example
Input
4
a
aa
a
cb
b
c
c
Output
? 1 2
? 3 4
? 4 4
! aabc | instruction | 0 | 44,725 | 0 | 89,450 |
Tags: brute force, constructive algorithms, interactive, math
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
# M = mod = 998244353
def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))))
# def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip('\n').split(' ')]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n').split(' ')]
def li3():return [int(i) for i in input().rstrip('\n')]
n = val()
cnt1 = Counter()
cnt2 = Counter()
print('? 1 ' + str(n),flush = True)
le = 0
for i in range(n):
for j in range(i+1,n+1):le += 1
for j in range(le):
cnt1[''.join(sorted(st()))] += 1
if n == 1:
for i in cnt1.keys():
print('! ' + str(i),flush = True)
exit()
print('? 2 ' + str(n),flush = True)
le = 0
for i in range(1,n):
for j in range(i+1,n+1):le += 1
# print(le)
for i in range(le):
cnt2[''.join(sorted(st()))] += 1
cnt1 -= cnt2
cnt1 = sorted(list(cnt1),key = lambda x:len(x))
s = ''
currcount = Counter()
for i in cnt1:
currcount = Counter(s)
for j in i:
if not currcount[j]:
s += j
break
currcount[j] -= 1
print('! ' + s,flush = True)
``` | output | 1 | 44,725 | 0 | 89,451 |
Provide a correct Python 3 solution for this coding contest problem.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
Output
5 | instruction | 0 | 45,159 | 0 | 90,318 |
"Correct Solution:
```
import sys
from collections import Counter
from string import ascii_lowercase
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 19 + 7
EPS = 10 ** -10
class RollingHash:
""" 文字列stringの部分文字列のハッシュを構築する。O(N) """
def __init__(self, string):
self.n = len(string)
self.BASE = 1234
self.MASK30 = (1 << 30) - 1
self.MASK31 = (1 << 31) - 1
self.MASK61 = (1 << 61) - 1
self.MOD = self.MASK61
self.hash = [0] * (self.n + 1)
self.pow = [1] * (self.n + 1)
for i, char in enumerate(string):
self.hash[i + 1] = self.calc_mod(self.mul(self.hash[i], self.BASE) + ord(char))
self.pow[i + 1] = self.calc_mod(self.mul(self.pow[i], self.BASE))
def calc_mod(self, x):
""" x mod 2^61-1 を返す """
xu = x >> 61
xd = x & self.MASK61
x = xu + xd
if x >= self.MOD:
x -= self.MASK61
return x
def mul(self, a, b):
""" a*b mod 2^61-1 を返す """
au = a >> 31
ad = a & self.MASK31
bu = b >> 31
bd = b & self.MASK31
mid = ad * bu + au * bd
midu = mid >> 30
midd = mid & self.MASK30
return self.calc_mod(au * bu * 2 + midu + (midd << 31) + ad * bd)
def get_hash(self, l, r):
""" string[l,r)のハッシュ値を返すO(1) """
res = self.calc_mod(self.hash[r] - self.mul(self.hash[l], self.pow[r - l]))
return res
def merge(self, h1, h2, length2):
""" ハッシュ値h1と長さlength2のハッシュ値h2を結合するO(1) """
return self.calc_mod(self.mul(h1, self.pow[length2]) + h2)
def get_lcp(self, l1, r1, l2, r2):
"""
string[l1:r2]とstring[l2:r2]の長共通接頭辞(Longest Common Prefix)の
長さを求めるO(log|string|)
"""
ng = min(r1 - l1, r2 - l2) + 1
ok = 0
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if self.get_hash(l1, l1 + mid) == self.get_hash(l2, l2 + mid):
ok = mid
else:
ng = mid
return ok
N = INT()
se = set()
A = []
for i in range(N):
s = input()
s = s[::-1]
rh = RollingHash(s)
A.append((s, rh))
se.add(rh.get_hash(0, len(s)))
ch = {}
for c in ascii_lowercase:
ch[c] = RollingHash(c).get_hash(0, 1)
ans = 0
for s, rh in A:
C = Counter(s)
for i in range(len(s)):
for c in C:
if rh.merge(rh.get_hash(0, i), ch[c], 1) in se:
ans += 1
C[s[i]] -= 1
if C[s[i]] == 0:
del C[s[i]]
ans -= N
print(ans)
``` | output | 1 | 45,159 | 0 | 90,319 |
Provide a correct Python 3 solution for this coding contest problem.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
Output
5 | instruction | 0 | 45,160 | 0 | 90,320 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**7)
N = int(input())
S = []
a = ord('a')
for _ in range(N):
S.append([ord(c) - a for c in input()][::-1])
_end = -1 #'_'
_count = -2 #'#'
def get_count(root):
to_visit = [root]
while to_visit:
current = to_visit[-1]
if _count in current:
to_visit.pop()
continue
else:
done = True
c = [0] * 26 + [1 if _end in current else 0]
for k, n in current.items():
if k in (_end, _count):
continue
if _count not in n:
done = False
break
if k not in (_end, _count):
cc = n[_count]
#print(k, cc)
for i, v in enumerate(cc):
if i == k:
c[k] += cc[-1]
else:
c[i] += v
if done:
current[_count] = c
to_visit.pop()
else:
for k, v in current.items():
if k not in (_end, _count):
to_visit.append(v)
return current[_count]
if _count in root:
return root[_count]
else:
c = [0] * 26 + [1 if _end in root else 0]
for k, n in root.items():
if k not in (_end, _count):
cc = get_count(n)
#print(k, cc)
for i, v in enumerate(cc):
if i == k:
c[k] += cc[-1]
else:
c[i] += v
root[_count] = c
return c
def make_trie(words):
root = dict()
for word in words:
current_dict = root
for letter in word:
#letter = ord(letter)
current_dict = current_dict.setdefault(letter, {})
current_dict[_end] = _end
return root
def get_subtree(trie, word):
current_dict = trie
for letter in word:
#letter = ord(letter)
if letter not in current_dict:
return {}
current_dict = current_dict[letter]
return current_dict
def in_trie(trie, word):
return _end in get_subtree(trie, word)
trie = make_trie(S)
#print(trie)
#print(get_subtree(trie, 'cy'))
#print(in_trie(trie, 'cy'))
#print(in_trie(trie, 'cyx'))
ans = 0
for s in S:
count = get_count(get_subtree(trie, s[:-1]))
#print(s, '#', count[s[-1]], count)
ans += count[s[-1]]
print((ans - N))
``` | output | 1 | 45,160 | 0 | 90,321 |
Provide a correct Python 3 solution for this coding contest problem.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
Output
5 | instruction | 0 | 45,162 | 0 | 90,324 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**8)
from collections import defaultdict,Counter
def saiki(cnts):
hitomozi = []
d = defaultdict(lambda: [])
heads = defaultdict(lambda: 0)
for s,c in cnts:
if len(s)==1:
hitomozi.append(s[0])
else:
for k,v in c.items():
if v>0:
heads[k] += 1
t = s[-1]
c[t] -= 1
s.pop(-1)
d[t].append([s,c])
for h in hitomozi:
ans[0] += heads[h]
for v in d.values():
if len(v)<=1:
continue
saiki(v)
return
N = int(input())
S = [list(input()) for _ in range(N)]
ans = [0]
cnts = []
for s in S:
cnts.append([s,Counter(s)])
saiki(cnts)
print(ans[0])
``` | output | 1 | 45,162 | 0 | 90,325 |
Provide a correct Python 3 solution for this coding contest problem.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
Output
5 | instruction | 0 | 45,163 | 0 | 90,326 |
"Correct Solution:
```
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, itertools, math, time
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n):
res = [None] * n
for i in range(n):
res[i] = II()
return res
def LIR(n):
res = [None] * n
for i in range(n):
res[i] = LI()
return res
def FR(n):
res = [None] * n
for i in range(n):
res[i] = IF()
return res
def LIF(n):
res = [None] * n
for i in range(n):
res[i] = IF()
return res
def SR(n):
res = [None] * n
for i in range(n):
res[i] = S()
return res
def LSR(n):
res = [None] * n
for i in range(n):
res[i] = LS()
return res
mod = 1000000007
inf = float('INF')
#solve
def solve():
n = II()
s = [None] * n
dp = [None] * n
for i in range(n):
dp[i] = [-1] * 26
s[i] = [input().rstrip()[::-1], i]
for i in range(n):
si,_ = s[i]
dpi = dp[i]
for j in range(len(si)):
x = ord(si[j]) - ord("a")
dpi[x] = j
d = [s]
ans = 0
for i in range(10 ** 6):
nd = []
if not d: break
for lis in d:
tmp = [[] for i in range(26)]
for l, k in lis:
p = ord(l[i]) - ord("a")
if len(l) == i + 1:
for x, m in lis:
if k != m:
if dp[m][p] >= i:
ans += 1
else:
tmp[p].append((l, k))
for k in tmp:
if k:
nd.append(k)
d = nd
print(ans)
return
#main
if __name__ == '__main__':
solve()
``` | output | 1 | 45,163 | 0 | 90,327 |
Provide a correct Python 3 solution for this coding contest problem.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
Output
5 | instruction | 0 | 45,166 | 0 | 90,332 |
"Correct Solution:
```
import sys;input=sys.stdin.readline
N, = map(int, input().split())
MOD=67280421310721
S = []
for _ in range(N):
s = input().strip()
S.append(s)
S.sort(key=lambda x:len(x))
D = dict()
dd = set()
R = 0
for s in S:
l = len(s)
d = [0]*26
for c in dd:
d[c] += 1
tmp=0
for i in range(l-1, -1, -1):
ee = ord(s[i]) - 97
tmp = 100*tmp+(ee+1)
tmp %= MOD
R += d[ee]
d[ee] = 0
if tmp in D:
for c in D[tmp]:
d[c] += 1
if i == 1:
nn = tmp
if l != 1:
if nn not in D:
D[nn] = set()
D[nn].add(ee)
else:
dd.add(ee)
print(R)
``` | output | 1 | 45,166 | 0 | 90,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha didn't do his math homework for today's lesson once again. As a punishment, his teacher Dr. Andrew decided to give him a hard, but very useless task.
Dr. Andrew has written two strings s and t of lowercase English letters at the blackboard. He reminded Misha that prefix of a string is a string formed by removing several (possibly none) of its last characters, and a concatenation of two strings is a string formed by appending the second string to the right of the first string.
The teacher asked Misha to write down on the blackboard all strings that are the concatenations of some non-empty prefix of s and some non-empty prefix of t. When Misha did it, Dr. Andrew asked him how many distinct strings are there. Misha spent almost the entire lesson doing that and completed the task.
Now he asks you to write a program that would do this task automatically.
Input
The first line contains the string s consisting of lowercase English letters. The second line contains the string t consisting of lowercase English letters.
The lengths of both string do not exceed 105.
Output
Output a single integer — the number of distinct strings that are concatenations of some non-empty prefix of s with some non-empty prefix of t.
Examples
Input
aba
aa
Output
5
Input
aaaaa
aaaa
Output
8
Note
In the first example, the string s has three non-empty prefixes: {a, ab, aba}. The string t has two non-empty prefixes: {a, aa}. In total, Misha has written five distinct strings: {aa, aaa, aba, abaa, abaaa}. The string abaa has been written twice.
In the second example, Misha has written eight distinct strings: {aa, aaa, aaaa, aaaaa, aaaaaa, aaaaaaa, aaaaaaaa, aaaaaaaaa}.
Submitted Solution:
```
num = []
k=0
s=input()
t=input()
temp=s[0]+t[0]
num.append (temp)
for i in range (1,(len(s)+1)):
for j in range(1,(len(t)+1)):
for value in num:
if value!=temp:
temp=s[:i]+t[:j]
num.append (temp)
for value in num:
k=k+1
print(k)
``` | instruction | 0 | 45,414 | 0 | 90,828 |
No | output | 1 | 45,414 | 0 | 90,829 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha didn't do his math homework for today's lesson once again. As a punishment, his teacher Dr. Andrew decided to give him a hard, but very useless task.
Dr. Andrew has written two strings s and t of lowercase English letters at the blackboard. He reminded Misha that prefix of a string is a string formed by removing several (possibly none) of its last characters, and a concatenation of two strings is a string formed by appending the second string to the right of the first string.
The teacher asked Misha to write down on the blackboard all strings that are the concatenations of some non-empty prefix of s and some non-empty prefix of t. When Misha did it, Dr. Andrew asked him how many distinct strings are there. Misha spent almost the entire lesson doing that and completed the task.
Now he asks you to write a program that would do this task automatically.
Input
The first line contains the string s consisting of lowercase English letters. The second line contains the string t consisting of lowercase English letters.
The lengths of both string do not exceed 105.
Output
Output a single integer — the number of distinct strings that are concatenations of some non-empty prefix of s with some non-empty prefix of t.
Examples
Input
aba
aa
Output
5
Input
aaaaa
aaaa
Output
8
Note
In the first example, the string s has three non-empty prefixes: {a, ab, aba}. The string t has two non-empty prefixes: {a, aa}. In total, Misha has written five distinct strings: {aa, aaa, aba, abaa, abaaa}. The string abaa has been written twice.
In the second example, Misha has written eight distinct strings: {aa, aaa, aaaa, aaaaa, aaaaaa, aaaaaaa, aaaaaaaa, aaaaaaaaa}.
Submitted Solution:
```
str1 = input()
str2 = input()
str1_res = [str1[: i] for i in range(1, len(str1) + 1)]
str2_res = [str2[: i] for i in range(1, len(str2) + 1)]
result = str()
for s in str1_res:
for s2 in str2_res:
a = s + s2
if a not in result:
result += ' ' + a
result = result.strip()
print(len(result.split(' ')))
``` | instruction | 0 | 45,415 | 0 | 90,830 |
No | output | 1 | 45,415 | 0 | 90,831 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha didn't do his math homework for today's lesson once again. As a punishment, his teacher Dr. Andrew decided to give him a hard, but very useless task.
Dr. Andrew has written two strings s and t of lowercase English letters at the blackboard. He reminded Misha that prefix of a string is a string formed by removing several (possibly none) of its last characters, and a concatenation of two strings is a string formed by appending the second string to the right of the first string.
The teacher asked Misha to write down on the blackboard all strings that are the concatenations of some non-empty prefix of s and some non-empty prefix of t. When Misha did it, Dr. Andrew asked him how many distinct strings are there. Misha spent almost the entire lesson doing that and completed the task.
Now he asks you to write a program that would do this task automatically.
Input
The first line contains the string s consisting of lowercase English letters. The second line contains the string t consisting of lowercase English letters.
The lengths of both string do not exceed 105.
Output
Output a single integer — the number of distinct strings that are concatenations of some non-empty prefix of s with some non-empty prefix of t.
Examples
Input
aba
aa
Output
5
Input
aaaaa
aaaa
Output
8
Note
In the first example, the string s has three non-empty prefixes: {a, ab, aba}. The string t has two non-empty prefixes: {a, aa}. In total, Misha has written five distinct strings: {aa, aaa, aba, abaa, abaaa}. The string abaa has been written twice.
In the second example, Misha has written eight distinct strings: {aa, aaa, aaaa, aaaaa, aaaaaa, aaaaaaa, aaaaaaaa, aaaaaaaaa}.
Submitted Solution:
```
#import re
string1 = input()
string2 = input()
list1 = []
list2 = []
for i in range(len(string1)):
string = string1[0:len(string1) - i]
list1.append(string)
for i in range(len(string2)):
string = string2[0:len(string2) - i]
list2.append(string)
#print(list1)
#print(list2)
#print(s)
print(len(list1) * len(list2))
``` | instruction | 0 | 45,416 | 0 | 90,832 |
No | output | 1 | 45,416 | 0 | 90,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Misha didn't do his math homework for today's lesson once again. As a punishment, his teacher Dr. Andrew decided to give him a hard, but very useless task.
Dr. Andrew has written two strings s and t of lowercase English letters at the blackboard. He reminded Misha that prefix of a string is a string formed by removing several (possibly none) of its last characters, and a concatenation of two strings is a string formed by appending the second string to the right of the first string.
The teacher asked Misha to write down on the blackboard all strings that are the concatenations of some non-empty prefix of s and some non-empty prefix of t. When Misha did it, Dr. Andrew asked him how many distinct strings are there. Misha spent almost the entire lesson doing that and completed the task.
Now he asks you to write a program that would do this task automatically.
Input
The first line contains the string s consisting of lowercase English letters. The second line contains the string t consisting of lowercase English letters.
The lengths of both string do not exceed 105.
Output
Output a single integer — the number of distinct strings that are concatenations of some non-empty prefix of s with some non-empty prefix of t.
Examples
Input
aba
aa
Output
5
Input
aaaaa
aaaa
Output
8
Note
In the first example, the string s has three non-empty prefixes: {a, ab, aba}. The string t has two non-empty prefixes: {a, aa}. In total, Misha has written five distinct strings: {aa, aaa, aba, abaa, abaaa}. The string abaa has been written twice.
In the second example, Misha has written eight distinct strings: {aa, aaa, aaaa, aaaaa, aaaaaa, aaaaaaa, aaaaaaaa, aaaaaaaaa}.
Submitted Solution:
```
n=input()
k=input()
q=set(n)
s=set(k)
w=len(n)
a=len(k)
if q==s:
if len(n)==len(k):
print((len(n)+len(k))-1)
if len(n)>len(k):
print((len(n)+len(k))-(w-a))
if w<a:
print((w+a)-(a-w))
else:
print(w*a)
``` | instruction | 0 | 45,417 | 0 | 90,834 |
No | output | 1 | 45,417 | 0 | 90,835 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3. | instruction | 0 | 45,496 | 0 | 90,992 |
Tags: binary search, combinatorics, dp, strings
Correct Solution:
```
# Problem code: 1238D
length = int(input())
s = input()
substrings = sum(range(length+1))
#print('starting substrings:', substrings)
substrings -= length
#print(length, 'single characters')
transitioned = False
journey = 0
i = 0
current_character = s[i]
journey += 1
i += 1
while i < length:
if s[i] == current_character:
journey += 1
else:
if journey > 1:
if i == journey: # means we're at the beginning or end
substrings -= (journey -1)
#print(journey-1, 'beginning/end')
else:
substrings -= (2*journey - 2)
#print(2*journey-2, 'middle string')
substrings -= 1
#print("1 transition")
transitioned = True
journey = 1
current_character = s[i]
i += 1
if journey > 1 and transitioned:
substrings -= (journey - 1)
#print(journey-1, 'end')
print(substrings)
``` | output | 1 | 45,496 | 0 | 90,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3. | instruction | 0 | 45,497 | 0 | 90,994 |
Tags: binary search, combinatorics, dp, strings
Correct Solution:
```
n=int(input())
s=input()
count=0
prev=s[0]
groups=[1]
for i in range(1,n):
if prev==s[i]:
groups[-1]+=1
else:
prev=s[i]
groups.append(1)
# print (groups)
for i in range(0,len(groups)-1):
count+=(groups[i]+groups[i+1]-1)
print ((n*(n-1)//2)-count)
``` | output | 1 | 45,497 | 0 | 90,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3. | instruction | 0 | 45,498 | 0 | 90,996 |
Tags: binary search, combinatorics, dp, strings
Correct Solution:
```
"""
NTC here
"""
from sys import stdin, setrecursionlimit
setrecursionlimit(10**7)
def iin(): return int(stdin.readline())
def lin(): return list(map(int, stdin.readline().split()))
# range = xrange
# input = raw_input
def main():
n=iin()
s=list(input())
ans=(n*(n-1))//2
for i in range(2):
ch=1
for j in range(1,n):
if s[j]==s[j-1]:
ch+=1
else:
ans-=ch-i
ch=1
s=s[::-1]
print(ans)
main()
``` | output | 1 | 45,498 | 0 | 90,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3. | instruction | 0 | 45,499 | 0 | 90,998 |
Tags: binary search, combinatorics, dp, strings
Correct Solution:
```
n,s=int(input()),input()
r=n*(n-1)//2
for j in range(2):
e=1
for i in range(1,n):
if(s[i-1]==s[i]):e+=1
else:
r-=e-j
e=1
s=s[::-1]
print(r)
``` | output | 1 | 45,499 | 0 | 90,999 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3. | instruction | 0 | 45,500 | 0 | 91,000 |
Tags: binary search, combinatorics, dp, strings
Correct Solution:
```
n=int(input())
a=list(input())
A=B=-1
index=[0]*n
arr=0
is_a=-1
is_b=-1
for i in range(n-1,-1,-1):
if a[i]=='A':
index[i]=A
if A==-1:
is_a=i
A=i
else:
index[i]=B
if B==-1:
is_b=i
B=i
for i in range(n):
if index[i]-1==i:
if a[i]=='A':
if is_b>=i:
arr-=1
else:
if is_a>=i:
arr-=1
if index[i]!=-1:
arr+=n-index[i]
print(arr)
``` | output | 1 | 45,500 | 0 | 91,001 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3. | instruction | 0 | 45,501 | 0 | 91,002 |
Tags: binary search, combinatorics, dp, strings
Correct Solution:
```
n = int(input())
s = input()
prev_b = -1
prev_a = -1
ans = 0
for i in range(n):
if s[i] == "B":
ans += prev_b + 1
if prev_b + 1 == i and prev_a != -1:
ans -= 1
prev_b = i
else:
ans += prev_a + 1
if prev_a + 1 == i and prev_b != -1:
ans -= 1
prev_a = i
print(ans)
``` | output | 1 | 45,501 | 0 | 91,003 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3. | instruction | 0 | 45,502 | 0 | 91,004 |
Tags: binary search, combinatorics, dp, strings
Correct Solution:
```
from sys import stdin
from array import array
input = stdin.readline
n = int(input())
s = input().strip('\n')
ans = (n ** 2 - n) // 2
p = s[0]
k = array('l')
b = 0
for c in s + '_':
if c != p:
k.append(b)
p = c
b = 1
else:
b += 1
for i in range(len(k)):
if i != 0:
ans -= k[i - 1]
if i != len(k) - 1:
ans -= k[i + 1]
ans += len(k) - 1
print(ans)
``` | output | 1 | 45,502 | 0 | 91,005 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3. | instruction | 0 | 45,503 | 0 | 91,006 |
Tags: binary search, combinatorics, dp, strings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 1000000007
INF = float('inf')
from bisect import bisect_left, bisect_right
# ------------------------------
def main():
n = N()
s = input()
sa = deque()
sb = deque()
for i in range(n):
if s[i]=='A':
sa.append(i)
else:
sb.append(i)
res = (n)*(n-1)//2
la = lb = 0
for i in range(1, n):
if s[i-1]=='A': sa.popleft()
else: sb.popleft()
if s[i-1]!=s[i]:
if s[i-1]=='A':
pa = (sa[0] if sa else n) -i
dif = pa+(i-lb)-1
la = i
else:
pb = (sb[0] if sb else n) -i
dif = pb+(i-la)-1
lb = i
res-=dif
# print(dif, pa, pb)
print(res)
if __name__ == "__main__":
main()
``` | output | 1 | 45,503 | 0 | 91,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.
Submitted Solution:
```
def main():
n = int(input())
s = input()
ret = n * (n - 1) // 2
for x in range(2): # 正着来一遍,反着来一遍
cur = 1
for i in range(1, n):
if s[i-1] == s[i]:
cur += 1
else:
ret -= cur - x # AAB (rev)--> BAA 有重复计算
cur = 1
s = s[::-1]
return ret
print(main())
``` | instruction | 0 | 45,504 | 0 | 91,008 |
Yes | output | 1 | 45,504 | 0 | 91,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=-10**6, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(50001)]
pp=[]
def SieveOfEratosthenes(n=50000):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
for i in range(50001):
if prime[i]:
pp.append(i)
#---------------------------------running code------------------------------------------
n=int(input())
s=list(input())
prea=[0]*n
preb=[0]*n
posta=[0]*n
postb=[0]*n
a,b=0,0
for i in range (n):
prea[i]=max(0,a-1)
preb[i]=max(0,b-1)
if s[i]=='A':
a+=1
b=0
else:
b+=1
a=0
a,b=0,0
for i in range (n-1,-1,-1):
posta[i]=a
postb[i]=b
if s[i]=='A':
a+=1
b=0
else:
b+=1
a=0
ct=0
res=(n*(n+1))//2
for i in range (n):
if s[i]=='A':
ct+=preb[i]+postb[i]+1
else:
ct+=prea[i]+posta[i]+1
res-=ct
#print(prea,posta,preb,postb,sep='\n')
print(res)
``` | instruction | 0 | 45,505 | 0 | 91,010 |
Yes | output | 1 | 45,505 | 0 | 91,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.
Submitted Solution:
```
n = int(input())
s = list(input())
tot = (n*(n-1))//2
for x in range(2):
cur = 1
for i in range(1,n):
if s[i] == s[i-1]:
cur+=1
else:
tot-=cur-x
cur = 1
s = s[::-1]
print(tot)
``` | instruction | 0 | 45,506 | 0 | 91,012 |
Yes | output | 1 | 45,506 | 0 | 91,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.
Submitted Solution:
```
N = int(input())
S = list(input())
pre = S[0]
A = []
a = 0
for s in S:
if s == pre:
a += 1
else:
A.append(a)
a = 1
pre = s
A.append(a)
q = 0
for i in range(len(A)-1):
q += A[i] + A[i+1] - 1
ans = N*(N-1)//2 - q
print(ans)
``` | instruction | 0 | 45,507 | 0 | 91,014 |
Yes | output | 1 | 45,507 | 0 | 91,015 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.
Submitted Solution:
```
import sys
import math
from collections import defaultdict
n=int(sys.stdin.readline())
s=list(sys.stdin.readline()[:-1])
count=0
ans=0
for k in range(1):
i=0
#print(ans,'ans')
count=1
while i<n-1:
#print(i,'i')
if s[i]==s[i+1]:
i+=1
count+=1
pass
else:
j=i+1
x=s[j]
z=True
ans+=count
#print(ans,'swap')
while j<n and z:
if s[j]==x:
ans+=1
j+=1
else:
z=False
count=0
if z:
i=j
else:
i=j
#print(i,'i',ans,'ans')
s.reverse()
#print(ans,'ans')
ans+=n
c=n*(n+1)//2-ans
print(c)
``` | instruction | 0 | 45,508 | 0 | 91,016 |
No | output | 1 | 45,508 | 0 | 91,017 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.
Submitted Solution:
```
import os
from itertools import combinations
def count_substring_palindrome(st):
def is_palindrome_string(s):
if len(s) > 1:
# print (s[0] ,s[1] ,s[-1],s[-2])
if s[0] == s[1] and s[-1] == s[-2]:
return True
return False
count = 0
if len(st) >= 2:
for i in range(2, len(st) + 1):
index = 0
while index + i <= len(st):
substring = st[index:index+i]
print (substring)
if is_palindrome_string(substring):
count += 1
index += 1
return count
if __name__ == "__main__":
lenght = input("Lenght: ")
st = input("String value: ")
print(count_substring_palindrome(st))
``` | instruction | 0 | 45,509 | 0 | 91,018 |
No | output | 1 | 45,509 | 0 | 91,019 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.
Submitted Solution:
```
from sys import stdin,stdout
n=int(stdin.readline().strip())
s=stdin.readline().strip()
acumA=[0 for i in range(n+3)]
acumB=[0 for i in range(n+3)]
dictA=[-1 for i in range(n+3)]
dictB=[-1 for i in range(n+3)]
for i in range(n):
if i!=0:
acumA[i]+=acumA[i-1]
acumB[i]+=acumB[i-1]
if s[i]=="A":
acumA[i]+=1
dictA[acumA[i]]=i
if s[i]=="B":
acumB[i]+=1
dictB[acumB[i]]=i
ans=0
for i in range(n-1):
if s[i]=="A":
if(dictA[acumA[i]+1]==-1):
continue
x=dictB[acumB[i-1]+1]
if(x==-1):
x=n
ans+=(x-i-1)
x=dictB[acumB[i-1]+1]
if(x==-1):
continue
ans+=(n-x-1)
else:
if(dictB[acumB[i]+1]==-1):
continue
x=dictA[acumA[i-1]+1]
if(x==-1):
x=n
ans+=(x-i-1)
x=dictA[acumA[i-1]+1]
if(x==-1):
continue
ans+=(n-x-1)
print(ans)
``` | instruction | 0 | 45,510 | 0 | 91,020 |
No | output | 1 | 45,510 | 0 | 91,021 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.
A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.
Here are some examples of good strings:
* t = AABBB (letters t_1, t_2 belong to palindrome t_1 ... t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 ... t_5);
* t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 ... t_3 and letter t_4 belongs to palindrome t_3 ... t_4);
* t = AAAAA (all letters belong to palindrome t_1 ... t_5);
You are given a string s of length n, consisting of only letters A and B.
You have to calculate the number of good substrings of string s.
Input
The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the length of the string s.
The second line contains the string s, consisting of letters A and B.
Output
Print one integer — the number of good substrings of string s.
Examples
Input
5
AABBB
Output
6
Input
3
AAA
Output
3
Input
7
AAABABB
Output
15
Note
In the first test case there are six good substrings: s_1 ... s_2, s_1 ... s_4, s_1 ... s_5, s_3 ... s_4, s_3 ... s_5 and s_4 ... s_5.
In the second test case there are three good substrings: s_1 ... s_2, s_1 ... s_3 and s_2 ... s_3.
Submitted Solution:
```
n = int(input())
ABString = input()
last = ABString[0]
segLen = 1
score = n * (n - 1) // 2
change = False
for letter in ABString[1:]:
if letter == last:
segLen += 1
else:
change = True
score -= segLen
segLen = 1
last = letter
if change: score -= segLen - 1
print(score)
``` | instruction | 0 | 45,511 | 0 | 91,022 |
No | output | 1 | 45,511 | 0 | 91,023 |
Provide a correct Python 3 solution for this coding contest problem.
Given the string S and m queries. The i-th query is given by the two strings xi and yi.
For each query, answer the longest substring of the string S, starting with xi and ending with yi.
For the string S, | S | represents the length of S. Also, the fact that the character string T is a substring of the character string S means that a certain integer i exists and Tj = Si + j is satisfied for 1 ≤ j ≤ | T |. Where Tj represents the jth character of T.
Constraints
* 1 ≤ | S | ≤ 2 x 105
* 1 ≤ m ≤ 105
* 1 ≤ | xi |, | yi |
* $ \ sum ^ m_ {i = 1} $ (| xi | + | yi |) ≤ 2 x 105
* S and xi, yi consist only of half-width lowercase letters.
Input
The input is given in the following format.
S
m
x1 y1
x2 y2
::
xm ym
* The character string S is given on the first line.
* The number of queries m is given in the second line.
* Of the m lines from the 3rd line, the i-th query string xi, yi is given on the i-th line, separated by spaces.
Output
Answer the maximum substring length in the following format.
len1
len2
::
lenm
Output the longest substring length leni that satisfies the condition for the i-th query on the i-th line of the m lines from the first line. If there is no such substring, output 0.
Examples
Input
abracadabra
5
ab a
a a
b c
ac ca
z z
Output
11
11
4
3
0
Input
howistheprogress
4
ist prog
s ss
how is
the progress
Output
9
12
5
11
Input
icpcsummertraining
9
mm m
icpc summer
train ing
summer mm
i c
i i
g g
train i
summer er
Output
2
10
8
0
4
16
1
6
6 | instruction | 0 | 46,133 | 0 | 92,266 |
"Correct Solution:
```
from collections import defaultdict
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
base = 37; MOD = 10**9 + 9
S = readline().strip()
L = len(S)
H = [0]*(L+1)
v = 0
ca = ord('a')
for i in range(L):
H[i+1] = v = (v * base + (ord(S[i]) - ca)) % MOD
M = int(readline())
Q = []
s = defaultdict(set)
for i in range(M):
x, y = readline().split()
v0 = 0
for c in x:
v0 = (v0 * base + (ord(c) - ca)) % MOD
s[len(x)].add(v0)
v1 = 0
for c in y:
v1 = (v1 * base + (ord(c) - ca)) % MOD
s[len(y)].add(v1)
Q.append((len(x), v0, len(y), v1))
fvs = {}; lvs = {}
for l, vs in s.items():
p = pow(base, l, MOD)
fs = {}; ls = {}
for i in range(L-l+1):
v = (H[i+l] - H[i] * p) % MOD
if v not in fs:
fs[v] = i
ls[v] = i
fv = {}; lv = {}
for v in vs:
fv[v] = fs.get(v, L+1)
lv[v] = ls.get(v, -1)
fvs[l] = fv
lvs[l] = lv
for lx, x, ly, y in Q:
p0 = fvs[lx][x]
p1 = lvs[ly][y]
if p0 <= p1 and p0+lx <= p1+ly:
write("%d\n" % (p1+ly-p0))
else:
write("0\n")
solve()
``` | output | 1 | 46,133 | 0 | 92,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given the string S and m queries. The i-th query is given by the two strings xi and yi.
For each query, answer the longest substring of the string S, starting with xi and ending with yi.
For the string S, | S | represents the length of S. Also, the fact that the character string T is a substring of the character string S means that a certain integer i exists and Tj = Si + j is satisfied for 1 ≤ j ≤ | T |. Where Tj represents the jth character of T.
Constraints
* 1 ≤ | S | ≤ 2 x 105
* 1 ≤ m ≤ 105
* 1 ≤ | xi |, | yi |
* $ \ sum ^ m_ {i = 1} $ (| xi | + | yi |) ≤ 2 x 105
* S and xi, yi consist only of half-width lowercase letters.
Input
The input is given in the following format.
S
m
x1 y1
x2 y2
::
xm ym
* The character string S is given on the first line.
* The number of queries m is given in the second line.
* Of the m lines from the 3rd line, the i-th query string xi, yi is given on the i-th line, separated by spaces.
Output
Answer the maximum substring length in the following format.
len1
len2
::
lenm
Output the longest substring length leni that satisfies the condition for the i-th query on the i-th line of the m lines from the first line. If there is no such substring, output 0.
Examples
Input
abracadabra
5
ab a
a a
b c
ac ca
z z
Output
11
11
4
3
0
Input
howistheprogress
4
ist prog
s ss
how is
the progress
Output
9
12
5
11
Input
icpcsummertraining
9
mm m
icpc summer
train ing
summer mm
i c
i i
g g
train i
summer er
Output
2
10
8
0
4
16
1
6
6
Submitted Solution:
```
s=input()
for _ in range(int(input())):
a,b=input().split()
if s.rfind(b)-s.find(a):
if s.find(a)+len(a)+len(b)>s.rfind(b):print(s.rfind(b)-s.find(a)+2)
else:print(s.rfind(b)-s.find(a)+1)
else:print(0)
``` | instruction | 0 | 46,134 | 0 | 92,268 |
No | output | 1 | 46,134 | 0 | 92,269 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given the string S and m queries. The i-th query is given by the two strings xi and yi.
For each query, answer the longest substring of the string S, starting with xi and ending with yi.
For the string S, | S | represents the length of S. Also, the fact that the character string T is a substring of the character string S means that a certain integer i exists and Tj = Si + j is satisfied for 1 ≤ j ≤ | T |. Where Tj represents the jth character of T.
Constraints
* 1 ≤ | S | ≤ 2 x 105
* 1 ≤ m ≤ 105
* 1 ≤ | xi |, | yi |
* $ \ sum ^ m_ {i = 1} $ (| xi | + | yi |) ≤ 2 x 105
* S and xi, yi consist only of half-width lowercase letters.
Input
The input is given in the following format.
S
m
x1 y1
x2 y2
::
xm ym
* The character string S is given on the first line.
* The number of queries m is given in the second line.
* Of the m lines from the 3rd line, the i-th query string xi, yi is given on the i-th line, separated by spaces.
Output
Answer the maximum substring length in the following format.
len1
len2
::
lenm
Output the longest substring length leni that satisfies the condition for the i-th query on the i-th line of the m lines from the first line. If there is no such substring, output 0.
Examples
Input
abracadabra
5
ab a
a a
b c
ac ca
z z
Output
11
11
4
3
0
Input
howistheprogress
4
ist prog
s ss
how is
the progress
Output
9
12
5
11
Input
icpcsummertraining
9
mm m
icpc summer
train ing
summer mm
i c
i i
g g
train i
summer er
Output
2
10
8
0
4
16
1
6
6
Submitted Solution:
```
s=input()
for _ in range(int(input())):
a,b=input().split()
if s.rfind(b)-s.find(a):
c=len(b)
if s.find(a)+len(a)+c>s.rfind(b):print(s.rfind(b)-s.find(a)+c)
else:print(s.rfind(b)-s.find(a)+c)
else:print(0)
``` | instruction | 0 | 46,135 | 0 | 92,270 |
No | output | 1 | 46,135 | 0 | 92,271 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given the string S and m queries. The i-th query is given by the two strings xi and yi.
For each query, answer the longest substring of the string S, starting with xi and ending with yi.
For the string S, | S | represents the length of S. Also, the fact that the character string T is a substring of the character string S means that a certain integer i exists and Tj = Si + j is satisfied for 1 ≤ j ≤ | T |. Where Tj represents the jth character of T.
Constraints
* 1 ≤ | S | ≤ 2 x 105
* 1 ≤ m ≤ 105
* 1 ≤ | xi |, | yi |
* $ \ sum ^ m_ {i = 1} $ (| xi | + | yi |) ≤ 2 x 105
* S and xi, yi consist only of half-width lowercase letters.
Input
The input is given in the following format.
S
m
x1 y1
x2 y2
::
xm ym
* The character string S is given on the first line.
* The number of queries m is given in the second line.
* Of the m lines from the 3rd line, the i-th query string xi, yi is given on the i-th line, separated by spaces.
Output
Answer the maximum substring length in the following format.
len1
len2
::
lenm
Output the longest substring length leni that satisfies the condition for the i-th query on the i-th line of the m lines from the first line. If there is no such substring, output 0.
Examples
Input
abracadabra
5
ab a
a a
b c
ac ca
z z
Output
11
11
4
3
0
Input
howistheprogress
4
ist prog
s ss
how is
the progress
Output
9
12
5
11
Input
icpcsummertraining
9
mm m
icpc summer
train ing
summer mm
i c
i i
g g
train i
summer er
Output
2
10
8
0
4
16
1
6
6
Submitted Solution:
```
s = input()
m = int(input())
for i in range(m):
x,y = map(str,input().split())
ans = s.rfind(y) - s.find(x)
if len(x) <= len(s) and len(y) <= len(s):
if x in s and y in s:
ans += 1
if len(y) > 1:
ans += len(y) - 1
if len(x) > ans:
ans = 0
else:
ans = 0
print(ans)
``` | instruction | 0 | 46,136 | 0 | 92,272 |
No | output | 1 | 46,136 | 0 | 92,273 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given the string S and m queries. The i-th query is given by the two strings xi and yi.
For each query, answer the longest substring of the string S, starting with xi and ending with yi.
For the string S, | S | represents the length of S. Also, the fact that the character string T is a substring of the character string S means that a certain integer i exists and Tj = Si + j is satisfied for 1 ≤ j ≤ | T |. Where Tj represents the jth character of T.
Constraints
* 1 ≤ | S | ≤ 2 x 105
* 1 ≤ m ≤ 105
* 1 ≤ | xi |, | yi |
* $ \ sum ^ m_ {i = 1} $ (| xi | + | yi |) ≤ 2 x 105
* S and xi, yi consist only of half-width lowercase letters.
Input
The input is given in the following format.
S
m
x1 y1
x2 y2
::
xm ym
* The character string S is given on the first line.
* The number of queries m is given in the second line.
* Of the m lines from the 3rd line, the i-th query string xi, yi is given on the i-th line, separated by spaces.
Output
Answer the maximum substring length in the following format.
len1
len2
::
lenm
Output the longest substring length leni that satisfies the condition for the i-th query on the i-th line of the m lines from the first line. If there is no such substring, output 0.
Examples
Input
abracadabra
5
ab a
a a
b c
ac ca
z z
Output
11
11
4
3
0
Input
howistheprogress
4
ist prog
s ss
how is
the progress
Output
9
12
5
11
Input
icpcsummertraining
9
mm m
icpc summer
train ing
summer mm
i c
i i
g g
train i
summer er
Output
2
10
8
0
4
16
1
6
6
Submitted Solution:
```
s = input()
m = int(input())
for i in range(m):
x,y = map(str,input().split())
ans = s.rfind(y) - s.find(x)
if ans != 0:
ans += 1
if len(y) > 1:
ans += len(y) - 1
print(ans)
``` | instruction | 0 | 46,137 | 0 | 92,274 |
No | output | 1 | 46,137 | 0 | 92,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". | instruction | 0 | 46,535 | 0 | 93,070 |
Tags: brute force, hashing, implementation, math, strings
Correct Solution:
```
s1 = input()
s2 = input()
if len(s1) < len(s2):
s3 = s1
s1 = s2
s2 = s3
n1 = len(s1) # smaller string
n2 = len(s2)
divs = list()
for i in range(1, n1+1):
if n1 % i != 0:
continue
grps = n1//i
substring = s1[:i]
if substring*grps == s1:
if n2 % i == 0:
grps2 = n2//i
if substring * grps2 == s2:
divs.append(substring)
print(len(divs))
``` | output | 1 | 46,535 | 0 | 93,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". | instruction | 0 | 46,536 | 0 | 93,072 |
Tags: brute force, hashing, implementation, math, strings
Correct Solution:
```
def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
s1=input()
s2=input()
c=0
g=gcd(len(s1),len(s2))
i=1
while i*i<=g:
if g%i==0:
if s1[:i]==s2[:i]:
if s1[:i]*(len(s1)//i)==s1:
if s2[:i]*(len(s2)//i)==s2:
c+=1
j=g//i
if j!=i:
if s1[:j]==s2[:j]:
if s1[:j]*(len(s1)//j)==s1:
if s2[:j]*(len(s2)//j)==s2:
c+=1
i+=1
print(c)
``` | output | 1 | 46,536 | 0 | 93,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". | instruction | 0 | 46,537 | 0 | 93,074 |
Tags: brute force, hashing, implementation, math, strings
Correct Solution:
```
s1=input()
s2=input()
sub1=set()
p=""
for i in s1:
p+=i
if p*(len(s1)//len(p))==s1:
sub1.add(p)
p=""
sub2=set()
for i in s2:
p+=i
if p*(len(s2)//len(p))==s2:
sub2.add(p)
print(len(sub1 & sub2))
``` | output | 1 | 46,537 | 0 | 93,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". | instruction | 0 | 46,538 | 0 | 93,076 |
Tags: brute force, hashing, implementation, math, strings
Correct Solution:
```
s1=input().strip()
s2=input().strip()
n1=len(s1)
n2=len(s2)
res=0
for i in range(1,min(n1,n2)+1):
if(n1%i==0 and n2%i==0):
check=True
for j in range(i,n1):
if s1[j%i]!=s1[j]:
check=False
break
for j in range(0,n2):
if(s1[j%i]!=s2[j]):
check=False
break
if check:
res+=1
print(res)
``` | output | 1 | 46,538 | 0 | 93,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". | instruction | 0 | 46,539 | 0 | 93,078 |
Tags: brute force, hashing, implementation, math, strings
Correct Solution:
```
str1=input()
str2=input()
set1=set()
set2=set()
m=len(str1)
n=len(str2)
for i in range(1,len(str1)+1):
if(m%len(str1[:i])==0):
k=m//len(str1[:i])
if(str1==k*str1[:i]):
set1.add(str1[:i])
for i in range(1,len(str2)+1):
if(n%len(str2[:i])==0):
k=n//len(str2[:i])
if(str2==k*str2[:i]):
set2.add(str2[:i])
print(len(set2.intersection(set1)))
``` | output | 1 | 46,539 | 0 | 93,079 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". | instruction | 0 | 46,540 | 0 | 93,080 |
Tags: brute force, hashing, implementation, math, strings
Correct Solution:
```
s=input()
r=input()
n,m=len(s),len(r)
if(n>m):
s,r=r,s
n,m=m,n
k=''
c=0
l=0
for i in range(1,n//2+1):
c=c+1
k=s[:i]
x=m//c
y=n//c
if(n%c==0 and m%c==0):
if(k*x==r and k*y==s):
l+=1
if(m%n==0 and s*(m//n)==r):
l+=1
print(l)
``` | output | 1 | 46,540 | 0 | 93,081 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". | instruction | 0 | 46,541 | 0 | 93,082 |
Tags: brute force, hashing, implementation, math, strings
Correct Solution:
```
from sys import stdin,stdout
inpt = lambda: stdin.readline().strip()
prnt = lambda x: stdout.write(str(x))
def no_of_div(s):
n = len(s)
divisors = [s]
for i in range(2,n+1):
d = n//i
if d*i==n and s[0:d]*i==s:
divisors.append(s[0:d])
return divisors
s1 = inpt()
s2 = inpt()
prnt(len(set(no_of_div(s1)).intersection(no_of_div(s2))))
``` | output | 1 | 46,541 | 0 | 93,083 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa". | instruction | 0 | 46,542 | 0 | 93,084 |
Tags: brute force, hashing, implementation, math, strings
Correct Solution:
```
a=input()
b=input()
list1=[]
for x in range(1, len(a)+1):
if len(a)%x==0 and a[:x]*(len(a)//x)==a:
list1.append(a[:x])
ans=0
for x in range(1, len(b)+1):
if len(b)%x==0 and b[:x]*(len(b)//x)==b and b[:x] in list1:
ans+=1
print(ans)
``` | output | 1 | 46,542 | 0 | 93,085 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa".
Submitted Solution:
```
def gcd(a, b):
c = a % b
return gcd(b, c) if c else b
a, b = input(), input()
u, v = len(a), len(b)
if u > v: a, b, u, v = b, a, v, u
if a == a[0] * u: d = 1
else:
for i in range(1, int(u ** 0.5) + 1):
if u % i == 0:
k = u // i
if a == a[: i] * k:
d = i
break
if a == a[: k] * i: d = k
if b == a[: d] * (v // d):
k = gcd(u // d, v // d)
if k == 1: print(1)
else:
s, l = 2, int(k ** 0.5)
for i in range(2, l + 1):
if k % i == 0: s += 2
if k == l * l: s -= 1
print(s)
else: print(0)
``` | instruction | 0 | 46,543 | 0 | 93,086 |
Yes | output | 1 | 46,543 | 0 | 93,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa".
Submitted Solution:
```
s=input()
s1=input()
n=len(s)
m=len(s1)
if(n>m):
a=m
b=n
p=s1
q=s
else:
a=n
b=m
p=s
q=s1
s2=""
d=0
for x in range(0,a):
s2=s2+p[x]
if(a%2!=0 and (x+1)%2==0):
continue
if(a%(x+1)!=0):
continue
if(s2*(a//(x+1))==p and s2*(b//(x+1))==q):
d+=1
print(d)
``` | instruction | 0 | 46,544 | 0 | 93,088 |
Yes | output | 1 | 46,544 | 0 | 93,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Examples
Input
abcdabcd
abcdabcdabcdabcd
Output
2
Input
aaa
aa
Output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa".
Submitted Solution:
```
import sys
input=sys.stdin.readline
import math
s1=[i for i in input() if i !='\n']
s2=[i for i in input() if i!= '\n']
ans=0
s=[]
for i in range(min(len(s1),len(s2))):
s.append(s1[i])
if len(s1)%len(s)==0 and len(s2)%len(s2)==0:
if s*(len(s1)//len(s))==s1:
if s*(len(s2)//len(s))==s2:
ans+=1
print(ans)
``` | instruction | 0 | 46,545 | 0 | 93,090 |
Yes | output | 1 | 46,545 | 0 | 93,091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.