message
stringlengths 2
23.8k
| message_type
stringclasses 2
values | message_id
int64 0
1
| conversation_id
int64 97
109k
| cluster
float64 0
0
| __index_level_0__
int64 194
217k
|
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
* if a_i=1, then remove a letter from the beginning of y and append it to the end of z.
Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.
Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.
Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.
Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.
Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.
Input
The first line contains a string x (1 ≤ |x| ≤ 1000).
The second line contains a string y (1 ≤ |y| ≤ 1000).
Both strings consist only of lowercase Latin letters.
Output
Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.
Examples
Input
aaa
bb
Output
24
Input
code
forces
Output
1574
Input
aaaaa
aaa
Output
0
Input
justamassivetesttocheck
howwellyouhandlemodulooperations
Output
667387032
Note
In the first example there are:
* 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
* 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
* 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
* 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
* 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
* 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";
Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.
|
instruction
| 0
| 108,084
| 0
| 216,168
|
Tags: combinatorics, dp, math, strings
Correct Solution:
```
import sys
input=sys.stdin.buffer.readline
S=list(input())
T=list(input())
N=len(S)-2
M=len(T)-2
S.append(20)
mod=998244353
DP=[[[0]*8 for j in range(M+2)] for i in range(N+2)]
for i in range(N):
for j in range(M):
DP[i][j][0]=1
for i in range(N+1):
for j in range(M+1):
for k in range(8):
if k&4:
if S[i-1]!=S[i]:
DP[i+1][j][k|1]+=DP[i][j][k]
if DP[i+1][j][k|1]>=mod:
DP[i+1][j][k|1]-=mod
if S[i-1]!=T[j]:
DP[i][j+1][(k|2)^4]+=DP[i][j][k]
if DP[i][j+1][(k|2)^4]>=mod:
DP[i][j+1][(k|2)^4]-=mod
else:
if T[j-1]!=S[i] or k==0:
DP[i+1][j][(k|1)^4]+=DP[i][j][k]
if DP[i+1][j][(k|1)^4]>=mod:
DP[i+1][j][(k|1)^4]-=mod
if T[j-1]!=T[j] or k==0:
DP[i][j+1][k|2]+=DP[i][j][k]
if DP[i][j+1][k|2]>=mod:
DP[i][j+1][k|2]-=mod
ANS=0
for i in range(N+1):
for j in range(M+1):
ANS+=DP[i][j][3]+DP[i][j][7]
print(ANS%mod)
```
|
output
| 1
| 108,084
| 0
| 216,169
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
* if a_i=1, then remove a letter from the beginning of y and append it to the end of z.
Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.
Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.
Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.
Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.
Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.
Input
The first line contains a string x (1 ≤ |x| ≤ 1000).
The second line contains a string y (1 ≤ |y| ≤ 1000).
Both strings consist only of lowercase Latin letters.
Output
Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.
Examples
Input
aaa
bb
Output
24
Input
code
forces
Output
1574
Input
aaaaa
aaa
Output
0
Input
justamassivetesttocheck
howwellyouhandlemodulooperations
Output
667387032
Note
In the first example there are:
* 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
* 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
* 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
* 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
* 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
* 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";
Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.
|
instruction
| 0
| 108,085
| 0
| 216,170
|
Tags: combinatorics, dp, math, strings
Correct Solution:
```
import sys
input = sys.stdin.readline
mod = 998244353
tot = 0
x = ' ' + input().strip()
y = ' ' + input().strip()
s = [x,y]
dp = [[[[0]*4 for j in range(2)] for k in range(len(y))] for i in range(len(x))]
for i in range(1,len(x)):
for j in range(1,len(y)):
dp[i][j-1][0][2] = 1
dp[i-1][j][1][1] = 1
for i in range(len(x)):
for j in range(len(y)):
s_idx = [i,j]
tot = (tot + dp[i][j][0][3] + dp[i][j][1][3]) % mod
for c in range(2):
for nex in range(2):
for ney in range(2):
if i < len(x)-1 and s[c][s_idx[c]] != x[i+1]:
dp[i+1][j][0][2+ney] = (dp[i+1][j][0][2+ney] + dp[i][j][c][2*nex+ney]) % mod
if j < len(y)-1 and s[c][s_idx[c]] != y[j+1]:
dp[i][j+1][1][2*nex+1] = (dp[i][j+1][1][2*nex+1] + dp[i][j][c][2*nex+ney]) % mod
print(tot)
```
|
output
| 1
| 108,085
| 0
| 216,171
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
* if a_i=1, then remove a letter from the beginning of y and append it to the end of z.
Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.
Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.
Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.
Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.
Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.
Input
The first line contains a string x (1 ≤ |x| ≤ 1000).
The second line contains a string y (1 ≤ |y| ≤ 1000).
Both strings consist only of lowercase Latin letters.
Output
Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.
Examples
Input
aaa
bb
Output
24
Input
code
forces
Output
1574
Input
aaaaa
aaa
Output
0
Input
justamassivetesttocheck
howwellyouhandlemodulooperations
Output
667387032
Note
In the first example there are:
* 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
* 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
* 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
* 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
* 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
* 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";
Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.
|
instruction
| 0
| 108,086
| 0
| 216,172
|
Tags: combinatorics, dp, math, strings
Correct Solution:
```
import sys
from sys import stdin
x = stdin.readline()[:-1]
xl = len(x)
y = stdin.readline()[:-1]
yl = len(y)
x += "?"
y += "!"
mod = 998244353
dp = [[[0,0] for i in range(yl+1)] for j in range(xl+1)]
dp[-1][-1] = [1,0]
for a in range(-1,xl):
for b in range(-1,yl):
if a == b == -1:
for na in range(xl):
dp[na][-1][0] += 1
for nb in range(yl):
dp[-1][nb][1] += 1
elif a == -1: #put a
for na in range(xl):
if y[b] != x[na]:
dp[na][b][0] += dp[a][b][1]
dp[na][b][0] %= mod
elif b == -1: #put b
for nb in range(yl):
if y[nb] != x[a]:
dp[a][nb][1] += dp[a][b][0]
dp[a][nb][1] %= mod
for f in range(2):
if a != -1: #put after a
if f == 0:
if a+1<xl and x[a+1] != x[a]:
dp[a+1][b][0] += dp[a][b][f]
dp[a+1][b][0] %= mod
else:
if a+1<xl and x[a+1] != y[b]:
dp[a+1][b][0] += dp[a][b][f]
dp[a+1][b][0] %= mod
if b != -1: #put b
if f == 0:
if b+1<yl and y[b+1] != x[a]:
dp[a][b+1][1] += dp[a][b][f]
dp[a][b+1][1] %= mod
else:
if b+1<yl and y[b+1] != y[b]:
dp[a][b+1][1] += dp[a][b][f]
dp[a][b+1][1] %= mod
#print (dp)
ans = 0
for i in range(xl):
for j in range(yl):
ans += sum(dp[i][j])
print (ans % mod)
```
|
output
| 1
| 108,086
| 0
| 216,173
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
* if a_i=1, then remove a letter from the beginning of y and append it to the end of z.
Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.
Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.
Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.
Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.
Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.
Input
The first line contains a string x (1 ≤ |x| ≤ 1000).
The second line contains a string y (1 ≤ |y| ≤ 1000).
Both strings consist only of lowercase Latin letters.
Output
Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.
Examples
Input
aaa
bb
Output
24
Input
code
forces
Output
1574
Input
aaaaa
aaa
Output
0
Input
justamassivetesttocheck
howwellyouhandlemodulooperations
Output
667387032
Note
In the first example there are:
* 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
* 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
* 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
* 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
* 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
* 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";
Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.
|
instruction
| 0
| 108,087
| 0
| 216,174
|
Tags: combinatorics, dp, math, strings
Correct Solution:
```
import sys;input=sys.stdin.buffer.readline;S=list(input());T=list(input());N=len(S)-2;M=len(T)-2;S.append(20);mod=998244353;DP=[[[0]*8 for j in range(M+2)] for i in range(N+2)]
for i in range(N):
for j in range(M): DP[i][j][0]=1
for i in range(N+1):
for j in range(M+1):
for k in range(8):
if k&4:
if S[i-1]!=S[i]:
DP[i+1][j][k|1]+=DP[i][j][k]
if DP[i+1][j][k|1]>=mod: DP[i+1][j][k|1]-=mod
if S[i-1]!=T[j]:
DP[i][j+1][(k|2)^4]+=DP[i][j][k]
if DP[i][j+1][(k|2)^4]>=mod: DP[i][j+1][(k|2)^4]-=mod
else:
if T[j-1]!=S[i] or k==0:
DP[i+1][j][(k|1)^4]+=DP[i][j][k]
if DP[i+1][j][(k|1)^4]>=mod: DP[i+1][j][(k|1)^4]-=mod
if T[j-1]!=T[j] or k==0:
DP[i][j+1][k|2]+=DP[i][j][k]
if DP[i][j+1][k|2]>=mod: DP[i][j+1][k|2]-=mod
print(sum([DP[i][j][3]+DP[i][j][7] for i in range(N+1) for j in range(M+1)])%mod)
```
|
output
| 1
| 108,087
| 0
| 216,175
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
* if a_i=1, then remove a letter from the beginning of y and append it to the end of z.
Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.
Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.
Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.
Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.
Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.
Input
The first line contains a string x (1 ≤ |x| ≤ 1000).
The second line contains a string y (1 ≤ |y| ≤ 1000).
Both strings consist only of lowercase Latin letters.
Output
Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.
Examples
Input
aaa
bb
Output
24
Input
code
forces
Output
1574
Input
aaaaa
aaa
Output
0
Input
justamassivetesttocheck
howwellyouhandlemodulooperations
Output
667387032
Note
In the first example there are:
* 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
* 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
* 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
* 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
* 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
* 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";
Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.
|
instruction
| 0
| 108,088
| 0
| 216,176
|
Tags: combinatorics, dp, math, strings
Correct Solution:
```
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):#排他的論理和の階乗
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n):
self.BIT=[0]*(n+1)
self.num=n
def query(self,idx):
res_sum = 0
while idx > 0:
res_sum += self.BIT[idx]
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
while idx <= self.num:
self.BIT[idx] += x
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class Matrix():
mod=10**9+7
def set_mod(m):
Matrix.mod=m
def __init__(self,L):
self.row=len(L)
self.column=len(L[0])
self._matrix=L
for i in range(self.row):
for j in range(self.column):
self._matrix[i][j]%=Matrix.mod
def __getitem__(self,item):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
return self._matrix[i][j]
def __setitem__(self,item,val):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
self._matrix[i][j]=val
def __add__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matrix[i][j]+other._matrix[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __sub__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matrix[i][j]-other._matrix[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __mul__(self,other):
if type(other)!=int:
if self.column!=other.row:
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(other.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(other.column):
temp=0
for k in range(self.column):
temp+=self._matrix[i][k]*other._matrix[k][j]
res[i][j]=temp%Matrix.mod
return Matrix(res)
else:
n=other
res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)]
return Matrix(res)
def __pow__(self,m):
if self.column!=self.row:
raise MatrixPowError("the size of row must be the same as that of column")
n=self.row
res=Matrix([[int(i==j) for i in range(n)] for j in range(n)])
while m:
if m%2==1:
res=res*self
self=self*self
m//=2
return res
def __str__(self):
res=[]
for i in range(self.row):
for j in range(self.column):
res.append(str(self._matrix[i][j]))
res.append(" ")
res.append("\n")
res=res[:len(res)-1]
return "".join(res)
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import log,gcd
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
mod = 998244353
x = input()
n = len(x)
y = input()
m = len(y)
dp_x = [[1 for j in range(m+1)] for i in range(n+1)]
dp_y = [[1 for j in range(m+1)] for i in range(n+1)]
dp_x[n][m] = 1
dp_y[n][m] = 1
res = 0
for i in range(n,-1,-1):
for j in range(m,-1,-1):
if i!=n:
res += dp_x[i+1][j]
res %= mod
if j!=m:
res += dp_y[i][j+1]
res %= mod
if i!=0:
if i!=n and x[i-1]!=x[i]:
dp_x[i][j] += dp_x[i+1][j]
dp_x[i][j] %= mod
if j!=m and x[i-1]!=y[j]:
dp_x[i][j] += dp_y[i][j+1]
dp_x[i][j] %= mod
if j!=0:
if i!=n and y[j-1]!=x[i]:
dp_y[i][j] += dp_x[i+1][j]
dp_y[i][j] %= mod
if j!=m and y[j-1]!=y[j]:
dp_y[i][j] += dp_y[i][j+1]
dp_y[i][j] %= mod
for i in range(n):
pre = ""
L = 0
for j in range(i,n):
if x[j]!=pre:
L += 1
pre = x[j]
else:
break
res -= L * (m+1)
res %= mod
for i in range(m):
pre = ""
L = 0
for j in range(i,m):
if y[j]!=pre:
L += 1
pre = y[j]
else:
break
res -= L * (n+1)
res %= mod
print(res)
```
|
output
| 1
| 108,088
| 0
| 216,177
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
* if a_i=1, then remove a letter from the beginning of y and append it to the end of z.
Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.
Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.
Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.
Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.
Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.
Input
The first line contains a string x (1 ≤ |x| ≤ 1000).
The second line contains a string y (1 ≤ |y| ≤ 1000).
Both strings consist only of lowercase Latin letters.
Output
Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.
Examples
Input
aaa
bb
Output
24
Input
code
forces
Output
1574
Input
aaaaa
aaa
Output
0
Input
justamassivetesttocheck
howwellyouhandlemodulooperations
Output
667387032
Note
In the first example there are:
* 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
* 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
* 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
* 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
* 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
* 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";
Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.
|
instruction
| 0
| 108,089
| 0
| 216,178
|
Tags: combinatorics, dp, math, strings
Correct Solution:
```
mod = 998244353
eps = 10**-9
def main():
import sys
input = sys.stdin.readline
S = input().rstrip('\n')
T = input().rstrip('\n')
NS = len(S)
NT = len(T)
dp_S = [[0] * (NT+1) for _ in range(NS+1)]
dp_T = [[0] * (NT+1) for _ in range(NS+1)]
for i in range(1, NS+1):
dp_S[i][0] = 1
for j in range(1, NT+1):
dp_T[0][j] = 1
for i in range(NS+1):
for j in range(NT+1):
if i == j == 0:
continue
elif i == 0:
if S[0] != T[j-1]:
dp_S[1][j] = (dp_S[1][j] + dp_T[0][j])%mod
if j+1 <= NT:
if T[j-1] != T[j]:
dp_T[0][j+1] = (dp_T[0][j+1] + dp_T[0][j])%mod
elif j == 0:
if T[0] != S[i-1]:
dp_T[i][1] = (dp_T[i][1] + dp_S[i][0]) % mod
if i + 1 <= NS:
if S[i - 1] != S[i]:
dp_S[i+1][0] = (dp_S[i+1][0] + dp_S[i][0]) % mod
else:
if i+1 <= NS:
if S[i-1] != S[i]:
dp_S[i+1][j] = (dp_S[i+1][j] + dp_S[i][j])%mod
if T[j-1] != S[i]:
dp_S[i+1][j] = (dp_S[i+1][j] + dp_T[i][j] + dp_T[0][j])%mod
if j+1 <= NT:
if T[j-1] != T[j]:
dp_T[i][j+1] = (dp_T[i][j+1] + dp_T[i][j])%mod
if S[i-1] != T[j]:
dp_T[i][j+1] = (dp_T[i][j+1] + dp_S[i][j] + dp_S[i][0])%mod
ans = 0
for i in range(1, NS+1):
for j in range(1, NT+1):
ans = (ans + dp_S[i][j] + dp_T[i][j])%mod
print(ans)
if __name__ == '__main__':
main()
```
|
output
| 1
| 108,089
| 0
| 216,179
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
* if a_i=1, then remove a letter from the beginning of y and append it to the end of z.
Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.
Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.
Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.
Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.
Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.
Input
The first line contains a string x (1 ≤ |x| ≤ 1000).
The second line contains a string y (1 ≤ |y| ≤ 1000).
Both strings consist only of lowercase Latin letters.
Output
Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.
Examples
Input
aaa
bb
Output
24
Input
code
forces
Output
1574
Input
aaaaa
aaa
Output
0
Input
justamassivetesttocheck
howwellyouhandlemodulooperations
Output
667387032
Note
In the first example there are:
* 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
* 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
* 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
* 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
* 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
* 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";
Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.
|
instruction
| 0
| 108,090
| 0
| 216,180
|
Tags: combinatorics, dp, math, strings
Correct Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
'''
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]'''
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return flag
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
seen.add(u)
for v,w in graph[u]:
if v not in d or d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def bell(s,g):#bellman-Ford
dis=AI(n,inf)
dis[s]=0
for i in range(n-1):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change=A(n)
for i in range(n):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change[v]=1
return dis
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j,n,m):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
if len(g[r])==1 and p!=-1:
yield None
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
t=1
for i in range(t):
x=input()
x=list(x)
y=input()
y=list(y)
x=list(map(lambda ch: ord(ch)-97,x))
y=list(map(lambda ch: ord(ch)-97,y))
ans=0
mod=998244353
m,n=len(x),len(y)
v1=[1]*(m+1)
v2=[1]*(n+1)
for i in range(m-2,-1,-1):
if x[i]!=x[i+1]:
v1[i]+=v1[i+1]
for i in range(n-2,-1,-1):
if y[i]!=y[i+1]:
v2[i]+=v2[i+1]
#print(x,y,v1,v2)
dp=[[[0]*27 for j in range(n+1)] for i in range(m+1)]
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
for k in range(27):
if x[i]==k:
if y[j]!=k:
dp[i][j][k]=(dp[i][j+1][y[j]]+v1[i])%mod
elif y[j]==k:
dp[i][j][k]=(dp[i+1][j][x[i]]+v2[j])%mod
else:
#print(i,j,k)
dp[i][j][k]=(dp[i+1][j][x[i]]+dp[i][j+1][y[j]]+(x[i]!=y[j])*(v2[j]+v1[i]))%mod
for i in range(m):
for j in range(n):
ans=(ans+dp[i][j][26])%mod
print(ans)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
```
|
output
| 1
| 108,090
| 0
| 216,181
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
* if a_i=1, then remove a letter from the beginning of y and append it to the end of z.
Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.
Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.
Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.
Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.
Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.
Input
The first line contains a string x (1 ≤ |x| ≤ 1000).
The second line contains a string y (1 ≤ |y| ≤ 1000).
Both strings consist only of lowercase Latin letters.
Output
Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.
Examples
Input
aaa
bb
Output
24
Input
code
forces
Output
1574
Input
aaaaa
aaa
Output
0
Input
justamassivetesttocheck
howwellyouhandlemodulooperations
Output
667387032
Note
In the first example there are:
* 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
* 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
* 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
* 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
* 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
* 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";
Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.
|
instruction
| 0
| 108,091
| 0
| 216,182
|
Tags: combinatorics, dp, math, strings
Correct Solution:
```
# O(16*n^2)
import sys
input = sys.stdin.readline
mod = 998244353
tot = 0
x = ' ' + input().strip()
y = ' ' + input().strip()
s = [x,y]
# the idea is to go from the dp that finds number of chaotic merges of x and y
# given that the substrings merged must begin at the start of x and y (are just prefixes)
# to the dp where the start of the substrings for the merge can be anything
# this is done by adding 1 at dp[i][j-1][0][1][0] and dp[i-1][j][1][0][1]
# (the same way we would start the dp normally if i == 1 and j == 1 (prefixes from above))
# dp[i][j][c][nex][ney] = the number of chaotic merges of a substring of x and y such that
# either substring of x is empty or ends at i and either substring of y is empty or ends at j
# however both substrings cannot be empty
# c = 0 -> last character is from x otherwise from y
# nex -> 1 if substring from x is not empty else 0
# ney -> 1 if substring from y is not empty else 0
# note that instead of an extra dimension for each nex and ney they are merged to reduce memory (or else MLE)
dp = [[[[0]*4 for j in range(2)] for k in range(len(y))] for i in range(len(x))]
# base case
for i in range(1,len(x)):
for j in range(1,len(y)):
# to start the dp of chaotic merges of x[i:] and y[j:]
dp[i][j-1][0][2] = 1
dp[i-1][j][1][1] = 1
# transitions
for i in range(len(x)):
for j in range(len(y)):
s_idx = [i,j]
# add num of chaotic merges of subs that end at i and j to tot
tot = (tot + dp[i][j][0][3] + dp[i][j][1][3]) % mod
# transition
for c in range(2):
for nex in range(2):
for ney in range(2):
# add x[i+1] to the end of the merge and transition
if i < len(x)-1 and s[c][s_idx[c]] != x[i+1]:
dp[i+1][j][0][2+ney] = (dp[i+1][j][0][2+ney] + dp[i][j][c][2*nex+ney]) % mod
# add y[j+1] to the end of the merge and transition
if j < len(y)-1 and s[c][s_idx[c]] != y[j+1]:
dp[i][j+1][1][2*nex+1] = (dp[i][j+1][1][2*nex+1] + dp[i][j][c][2*nex+ney]) % mod
print(tot)
```
|
output
| 1
| 108,091
| 0
| 216,183
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings x and y, both consist only of lowercase Latin letters. Let |s| be the length of string s.
Let's call a sequence a a merging sequence if it consists of exactly |x| zeros and exactly |y| ones in some order.
A merge z is produced from a sequence a by the following rules:
* if a_i=0, then remove a letter from the beginning of x and append it to the end of z;
* if a_i=1, then remove a letter from the beginning of y and append it to the end of z.
Two merging sequences a and b are different if there is some position i such that a_i ≠ b_i.
Let's call a string z chaotic if for all i from 2 to |z| z_{i-1} ≠ z_i.
Let s[l,r] for some 1 ≤ l ≤ r ≤ |s| be a substring of consecutive letters of s, starting from position l and ending at position r inclusive.
Let f(l_1, r_1, l_2, r_2) be the number of different merging sequences of x[l_1,r_1] and y[l_2,r_2] that produce chaotic merges. Note that only non-empty substrings of x and y are considered.
Calculate ∑ _{1 ≤ l_1 ≤ r_1 ≤ |x| \\\ 1 ≤ l_2 ≤ r_2 ≤ |y|} f(l_1, r_1, l_2, r_2). Output the answer modulo 998 244 353.
Input
The first line contains a string x (1 ≤ |x| ≤ 1000).
The second line contains a string y (1 ≤ |y| ≤ 1000).
Both strings consist only of lowercase Latin letters.
Output
Print a single integer — the sum of f(l_1, r_1, l_2, r_2) over 1 ≤ l_1 ≤ r_1 ≤ |x| and 1 ≤ l_2 ≤ r_2 ≤ |y| modulo 998 244 353.
Examples
Input
aaa
bb
Output
24
Input
code
forces
Output
1574
Input
aaaaa
aaa
Output
0
Input
justamassivetesttocheck
howwellyouhandlemodulooperations
Output
667387032
Note
In the first example there are:
* 6 pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";
* 3 pairs of substrings "a" and "bb", each with a valid merging sequence "101";
* 4 pairs of substrings "aa" and "b", each with a valid merging sequence "010";
* 2 pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";
* 2 pairs of substrings "aaa" and "b", each with no valid merging sequences;
* 1 pair of substrings "aaa" and "bb" with a valid merging sequence "01010";
Thus, the answer is 6 ⋅ 2 + 3 ⋅ 1 + 4 ⋅ 1 + 2 ⋅ 2 + 2 ⋅ 0 + 1 ⋅ 1 = 24.
Submitted Solution:
```
S=list(input())
T=list(input())
N=len(S)-2
M=len(T)-2
S.append(20)
mod=998244353
DP=[[[0]*8 for j in range(M+2)] for i in range(N+2)]
for i in range(N):
for j in range(M):
DP[i][j][0]=1
for i in range(N+1):
for j in range(M+1):
for k in range(8):
if k&4:
if S[i-1]!=S[i]:
DP[i+1][j][k|1]+=DP[i][j][k]
if DP[i+1][j][k|1]>=mod:
DP[i+1][j][k|1]-=mod
if S[i-1]!=T[j]:
DP[i][j+1][(k|2)^4]+=DP[i][j][k]
if DP[i][j+1][(k|2)^4]>=mod:
DP[i][j+1][(k|2)^4]-=mod
else:
if T[j-1]!=S[i] or k==0:
DP[i+1][j][(k|1)^4]+=DP[i][j][k]
if DP[i+1][j][(k|1)^4]>=mod:
DP[i+1][j][(k|1)^4]-=mod
if T[j-1]!=T[j] or k==0:
DP[i][j+1][k|2]+=DP[i][j][k]
if DP[i][j+1][k|2]>=mod:
DP[i][j+1][k|2]-=mod
ANS=0
for i in range(N+1):
for j in range(M+1):
ANS+=DP[i][j][3]+DP[i][j][7]
print(ANS%mod)
```
|
instruction
| 0
| 108,092
| 0
| 216,184
|
No
|
output
| 1
| 108,092
| 0
| 216,185
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
|
instruction
| 0
| 108,130
| 0
| 216,260
|
Tags: greedy, strings
Correct Solution:
```
def lms(s):
t=""
if len(s)==1:
return s
else:
while(len(s)>1):
l=0
j=0
for i in range(len(s)):
if ord(s[i])>l:
l=ord(s[i])
j=i
t+= (s.count(s[j]))*s[j]
y = len(s) - 1 - s[::-1].index(s[j])
s=s[y+1:]
if len(set(map(str,s)))==1:
t+=s
break
return t
print(lms(input()))
```
|
output
| 1
| 108,130
| 0
| 216,261
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
|
instruction
| 0
| 108,131
| 0
| 216,262
|
Tags: greedy, strings
Correct Solution:
```
a=m=''
for x in input()[::-1]:
if x>=m: a+=x
m=max(m,x)
print(a[::-1])
```
|
output
| 1
| 108,131
| 0
| 216,263
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
|
instruction
| 0
| 108,132
| 0
| 216,264
|
Tags: greedy, strings
Correct Solution:
```
from sys import stdin, stdout
s = stdin.readline().strip()
maximum = []
mx = 'a'
for f in s[::-1]:
mx = max(f, mx)
maximum.append(mx)
maximum = maximum[::-1]
ans = ''
for i in range(len(s)):
if s[i] == maximum[i]:
ans += s[i]
stdout.write(str(ans))
```
|
output
| 1
| 108,132
| 0
| 216,265
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
|
instruction
| 0
| 108,133
| 0
| 216,266
|
Tags: greedy, strings
Correct Solution:
```
A = input()
letter_to_index = {}
for i, letter in enumerate(A):
if letter in letter_to_index:
letter_to_index[letter] += [i]
else:
letter_to_index[letter] = [i]
pos = 0
letter = 'z'
result = ""
while True:
if letter in letter_to_index:
letter_pos = letter_to_index[letter]
for index in letter_pos:
if index >= pos:
result += letter
pos = index
if letter == 'a':
break
letter = chr(ord(letter) - 1)
print(result)
```
|
output
| 1
| 108,133
| 0
| 216,267
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
|
instruction
| 0
| 108,134
| 0
| 216,268
|
Tags: greedy, strings
Correct Solution:
```
s = input()
l = len(s)
m = 'a'
ans = ""
for i in range(l):
if s[l-i-1] >= m:
ans = s[l-i-1] + ans
m = s[l-i-1]
print(ans)
# Made By Mostafa_Khaled
```
|
output
| 1
| 108,134
| 0
| 216,269
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
|
instruction
| 0
| 108,135
| 0
| 216,270
|
Tags: greedy, strings
Correct Solution:
```
s,l=input(),['']
for i in reversed(s):
if l[-1]<=i: l.append(i)
print(*reversed(l),sep='')
```
|
output
| 1
| 108,135
| 0
| 216,271
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
|
instruction
| 0
| 108,136
| 0
| 216,272
|
Tags: greedy, strings
Correct Solution:
```
string = str(input())
listx = [x for x in string]
listx.reverse()
join = [''.join(listx)]
letts = list(set(listx))
letts.sort()
letts.reverse()
stringx = ''
for i in letts:
if i in string:
for k in range(len(string)):
if string[k] == i:
indx = k
for j in range(indx):
if string[j] == i:
stringx += i
stringx += i
string = string[indx+1:]
print(stringx)
```
|
output
| 1
| 108,136
| 0
| 216,273
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
|
instruction
| 0
| 108,137
| 0
| 216,274
|
Tags: greedy, strings
Correct Solution:
```
from collections import Counter
s = input()
c = Counter(s)
cur_char = 'z'
for ch in s:
while c[cur_char] == 0:
cur_char = chr(ord(cur_char) - 1)
if ch == cur_char:
print(cur_char, end='')
c[ch] -= 1
```
|
output
| 1
| 108,137
| 0
| 216,275
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
Submitted Solution:
```
string = str(input())
listx = [x for x in string]
listx.reverse()
join = [''.join(listx)]
letts = list(set(listx))
letts.sort()
letts.reverse()
stringx = ''
for i in letts:
leng = len(string)
indx = listx.index(i)
for j in range(leng - indx):
if string[j] == i:
stringx += i
string = string[-indx:]
print(stringx)
```
|
instruction
| 0
| 108,138
| 0
| 216,276
|
No
|
output
| 1
| 108,138
| 0
| 216,277
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
Submitted Solution:
```
string = str(input())
listx = [x for x in string]
listx.reverse()
join = [''.join(listx)]
letts = list(set(listx))
letts.sort()
letts.reverse()
stringx = ''
for i in letts:
if i in string:
indx = string.index(i)
for j in range(indx):
if string[j] == i:
stringx += i
stringx += i
string = string[indx+1:]
print(stringx)
```
|
instruction
| 0
| 108,139
| 0
| 216,278
|
No
|
output
| 1
| 108,139
| 0
| 216,279
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
Submitted Solution:
```
def lms(s):
t=""
while(len(s)>1):
l=0
j=0
for i in range(len(s)):
if ord(s[i])>l:
l=ord(s[i])
j=i
t+= (s.count(s[j]))*s[j]
y = len(s) - 1 - s[::-1].index(s[j])
s=s[y+1:]
if len(set(map(str,s)))==1:
t+=s
break
return t
print(lms(input()))
```
|
instruction
| 0
| 108,140
| 0
| 216,280
|
No
|
output
| 1
| 108,140
| 0
| 216,281
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
Submitted Solution:
```
string = str(input())
listx = [x for x in string]
listx.reverse()
join = [''.join(listx)]
letts = list(set(listx))
letts.sort()
letts.reverse()
stringx = ''
for i in letts:
if i in string:
leng = len(string)
indx = string.index(i)
for j in range(leng - indx):
if string[j] == i:
stringx += i
string = string[-indx:]
print(stringx)
```
|
instruction
| 0
| 108,141
| 0
| 216,282
|
No
|
output
| 1
| 108,141
| 0
| 216,283
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).
A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.
Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.
We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].
Input
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≤ li ≤ ri ≤ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.
The input limits for scoring 30 points are (subproblem G1):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 200.
The input limits for scoring 70 points are (subproblems G1+G2):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 2000.
The input limits for scoring 100 points are (subproblems G1+G2+G3):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 50000.
Output
Print a single integer — the number of good substrings of string s.
Examples
Input
aaab
2
aa 0 0
aab 1 1
Output
3
Input
ltntlnen
3
n 0 0
ttlneenl 1 4
lelllt 1 1
Output
2
Input
a
0
Output
1
Note
There are three good substrings in the first sample test: «aab», «ab» and «b».
In the second test only substrings «e» and «t» are good.
|
instruction
| 0
| 108,158
| 0
| 216,316
|
Tags: hashing, strings
Correct Solution:
```
from sys import stdin
import re
def substrings(s):
for i in range(0, len(s)):
for l in range(i, len(s)):
yield s[i:l+1]
test = stdin.readline().rstrip('\n')
ruleCount = int(stdin.readline())
rules = []
for i in range(0, ruleCount):
ruleStr = stdin.readline()
sp = ruleStr.split(' ')
m = {}
for s in substrings(sp[0]):
m[s] = m.get(s, 0) + 1
rules.append((sp[0], int(sp[1]), int(sp[2]), m))
def works(x):
for rule in rules:
if not rule[1] <= rule[3].get(x, 0) <= rule[2]:
return False
return True
print(len([x for x in set(substrings(test)) if works(x)]))
```
|
output
| 1
| 108,158
| 0
| 216,317
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).
A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.
Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.
We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].
Input
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≤ li ≤ ri ≤ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.
The input limits for scoring 30 points are (subproblem G1):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 200.
The input limits for scoring 70 points are (subproblems G1+G2):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 2000.
The input limits for scoring 100 points are (subproblems G1+G2+G3):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 50000.
Output
Print a single integer — the number of good substrings of string s.
Examples
Input
aaab
2
aa 0 0
aab 1 1
Output
3
Input
ltntlnen
3
n 0 0
ttlneenl 1 4
lelllt 1 1
Output
2
Input
a
0
Output
1
Note
There are three good substrings in the first sample test: «aab», «ab» and «b».
In the second test only substrings «e» and «t» are good.
|
instruction
| 0
| 108,159
| 0
| 216,318
|
Tags: hashing, strings
Correct Solution:
```
def count(p, s):
start = 0
c = 0
while True:
try:
pos = s.index(p, start)
c += 1
start = pos + 1
except ValueError:
return c
s = input()
n = int(input())
pravs = []
for i in range(n):
p, l, r = input().split()
l = int(l); r = int(r)
pravs.append((p, l, r))
var = set()
for l in range(len(s)):
for r in range(l+1, len(s)+1):
pods = s[l:r]
for prav in pravs:
if not prav[1] <= count(pods, prav[0]) <= prav[2]:
break
else:
var.add(pods)
print(len(var))
```
|
output
| 1
| 108,159
| 0
| 216,319
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).
A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.
Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.
We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].
Input
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≤ li ≤ ri ≤ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.
The input limits for scoring 30 points are (subproblem G1):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 200.
The input limits for scoring 70 points are (subproblems G1+G2):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 2000.
The input limits for scoring 100 points are (subproblems G1+G2+G3):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 50000.
Output
Print a single integer — the number of good substrings of string s.
Examples
Input
aaab
2
aa 0 0
aab 1 1
Output
3
Input
ltntlnen
3
n 0 0
ttlneenl 1 4
lelllt 1 1
Output
2
Input
a
0
Output
1
Note
There are three good substrings in the first sample test: «aab», «ab» and «b».
In the second test only substrings «e» and «t» are good.
Submitted Solution:
```
s = input()
n = int(input())
rules = []
for i in range(n):
rules.append(input().split())
rules[-1][1]=int(rules[-1][1])
rules[-1][2]=int(rules[-1][2])
used = set()
ans=0
def check(rules,s):
for ru in rules:
if ru[1]<=ru[0].count(s)<=ru[2]:continue
else: return False
return True
for i in range(len(s)):
for j in range(len(s)):
sk=s[i:j+1]
if(sk not in used):
if check(rules,sk):
ans+=1
used.add(sk)
print(ans)
```
|
instruction
| 0
| 108,160
| 0
| 216,320
|
No
|
output
| 1
| 108,160
| 0
| 216,321
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).
A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.
Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.
We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].
Input
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≤ li ≤ ri ≤ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.
The input limits for scoring 30 points are (subproblem G1):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 200.
The input limits for scoring 70 points are (subproblems G1+G2):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 2000.
The input limits for scoring 100 points are (subproblems G1+G2+G3):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 50000.
Output
Print a single integer — the number of good substrings of string s.
Examples
Input
aaab
2
aa 0 0
aab 1 1
Output
3
Input
ltntlnen
3
n 0 0
ttlneenl 1 4
lelllt 1 1
Output
2
Input
a
0
Output
1
Note
There are three good substrings in the first sample test: «aab», «ab» and «b».
In the second test only substrings «e» and «t» are good.
Submitted Solution:
```
s = input()
n = int(input())
rules = []
for i in range(n):
rules.append(input().split())
rules[i][1]=int(rules[i][1])
rules[i][2]=int(rules[i][2])
used = set()
ans=0
def check(rules,s):
for ru in rules:
if ru[1]<=ru[0].count(s)<=ru[2]:continue
else: return False
return True
for i in range(len(s)):
sk = ''
for j in range(i,len(s)):
sk+=s[j]
if(sk not in used):
if check(rules,sk):
ans+=1
used.add(sk)
print(ans)
```
|
instruction
| 0
| 108,161
| 0
| 216,322
|
No
|
output
| 1
| 108,161
| 0
| 216,323
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).
A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.
Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.
We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].
Input
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≤ li ≤ ri ≤ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.
The input limits for scoring 30 points are (subproblem G1):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 200.
The input limits for scoring 70 points are (subproblems G1+G2):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 2000.
The input limits for scoring 100 points are (subproblems G1+G2+G3):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 50000.
Output
Print a single integer — the number of good substrings of string s.
Examples
Input
aaab
2
aa 0 0
aab 1 1
Output
3
Input
ltntlnen
3
n 0 0
ttlneenl 1 4
lelllt 1 1
Output
2
Input
a
0
Output
1
Note
There are three good substrings in the first sample test: «aab», «ab» and «b».
In the second test only substrings «e» and «t» are good.
Submitted Solution:
```
s = input()
n = int(input())
rules = []
def count(a,b):
ans = 0
for i in range(len(a)-len(b)):
if a[i:i+len(b)]==b:
ans+=1
return ans
for i in range(n):
rules.append(input().split())
rules[-1][1]=int(rules[-1][1])
rules[-1][2]=int(rules[-1][2])
used = set()
ans=0
def check(rules,s):
for ru in rules:
if ru[1]<=count(ru[0],s)<=ru[2]:continue
else: return False
return True
for i in range(len(s)):
for j in range(i,len(s)):
sk=s[i:j+1]
if(sk not in used):
if check(rules,sk):
ans+=1
used.add(sk)
print(ans)
```
|
instruction
| 0
| 108,162
| 0
| 216,324
|
No
|
output
| 1
| 108,162
| 0
| 216,325
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).
A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.
Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.
We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].
Input
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≤ li ≤ ri ≤ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.
The input limits for scoring 30 points are (subproblem G1):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 200.
The input limits for scoring 70 points are (subproblems G1+G2):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 2000.
The input limits for scoring 100 points are (subproblems G1+G2+G3):
* 0 ≤ n ≤ 10.
* The length of string s and the maximum length of string p is ≤ 50000.
Output
Print a single integer — the number of good substrings of string s.
Examples
Input
aaab
2
aa 0 0
aab 1 1
Output
3
Input
ltntlnen
3
n 0 0
ttlneenl 1 4
lelllt 1 1
Output
2
Input
a
0
Output
1
Note
There are three good substrings in the first sample test: «aab», «ab» and «b».
In the second test only substrings «e» and «t» are good.
Submitted Solution:
```
s = input()
n = int(input())
sp = []
l = []
r = []
for i in range(n):
tmp = input()
tsp, tl, tr = tmp.split()
sp += [tsp]
l += [int(tl)]
r += [int(tr)]
was = {}
for i in range(len(s)):
for j in range(len(s)):
if (i <= j):
c = s[i:j + 1]
#print(c)
good = True
for q in range(n):
if (sp[q].count(c) < l[q]) or (sp[q].count(c) > r[q]):
#print(c)
#print(q + 1)
good = False
break
if (good) and not (c in was):
was[c] = 1
#print(c)
print(len(was.keys()))
```
|
instruction
| 0
| 108,163
| 0
| 216,326
|
No
|
output
| 1
| 108,163
| 0
| 216,327
|
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
|
instruction
| 0
| 108,271
| 0
| 216,542
|
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
if n > 26:
print(-1)
else:
az = [0 for i in range(26)]
cnt = 0
for i in s:
ind = ord(i)-97
az[ind] += 1
if az[ind] > 1:
cnt += 1
print(cnt)
```
|
output
| 1
| 108,271
| 0
| 216,543
|
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
|
instruction
| 0
| 108,272
| 0
| 216,544
|
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
def different_is_good(mystr):
if len(mystr) > 26:
print(-1)
return
hash_, diff = [0] * 128, 0
for char in mystr:
if hash_[ord(char)] == 1:
diff += 1
else:
hash_[ord(char)] = 1
print(diff)
_ = int(input())
different_is_good(str(input()))
```
|
output
| 1
| 108,272
| 0
| 216,545
|
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
|
instruction
| 0
| 108,273
| 0
| 216,546
|
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n=int(input())
string=input()
if(n>26):
print(-1)
else:
char_dict={}
for i in string:
if i in char_dict.keys():
char_dict[i]=char_dict[i]+1
else:
char_dict[i]=1
characters_to_change=0
for key,value in char_dict.items():
characters_to_change=characters_to_change+value-1
print(characters_to_change)
```
|
output
| 1
| 108,273
| 0
| 216,547
|
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
|
instruction
| 0
| 108,274
| 0
| 216,548
|
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
if n == 1:
print(0)
exit(0)
visited = set()
visited.add(s[0])
ans = 0
d = {}
d[s[0]] = 1
for i in range(1, n):
if s[i] in visited:
d[s[i]] += 1
else:
visited.add(s[i])
d[s[i]] = 1
x = len(visited)
for i in d:
x += d[i] - 1
ans += d[i] - 1
if x > 26:
print(-1)
else:
print(ans)
```
|
output
| 1
| 108,274
| 0
| 216,549
|
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
|
instruction
| 0
| 108,275
| 0
| 216,550
|
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
def check(s1):
if len(s1)==len(set(s1)):
return False
else:
return True
n=int(input())
s=input()
s1=list(s)
res=[]
c=0
if(n>26):
print(-1)
elif(check(s1)==True):
for i in s1:
if i not in res:
res.append(i)
else:
c+=1
print(c)
else:
print(0)
```
|
output
| 1
| 108,275
| 0
| 216,551
|
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
|
instruction
| 0
| 108,276
| 0
| 216,552
|
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n=int(input())
k=len(set(input()))
if n<=26:
print(n-k)
else: print(-1)
```
|
output
| 1
| 108,276
| 0
| 216,553
|
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
|
instruction
| 0
| 108,277
| 0
| 216,554
|
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
word = input()
newWord = ""
LETTERS = "abcdefghijklmnopqrstuvwxyz"
usedChars = {}
moves = 0
if n > 26:
print("-1")
else:
for c in word:
if c not in usedChars:
usedChars[c] = 0
for c in word:
if usedChars[c] > 0:
for l in LETTERS:
if l not in usedChars:
usedChars[l] = 0
newWord = newWord + str(l)
moves = moves + 1
break
else:
usedChars[c] += 1
print(moves)
```
|
output
| 1
| 108,277
| 0
| 216,555
|
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
|
instruction
| 0
| 108,278
| 0
| 216,556
|
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
from collections import Counter
n = int(input().strip())
s = input().strip()
def solve(s):
freq = Counter(s)
l = len(freq.keys())
c = 0
for i in freq.values():
if i > 1:
l += i-1
c += i-1
if l > 26:
return -1
return c
print(solve(s))
```
|
output
| 1
| 108,278
| 0
| 216,557
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
num = int(input())
arr = list(input())
if num > 26:
print(-1)
else:
print(num - len(set(arr)))
```
|
instruction
| 0
| 108,279
| 0
| 216,558
|
Yes
|
output
| 1
| 108,279
| 0
| 216,559
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
p=int(input())
s=input()
z=set(s)
if(p>26):
print('-1')
else:
print(p-len(z))
```
|
instruction
| 0
| 108,280
| 0
| 216,560
|
Yes
|
output
| 1
| 108,280
| 0
| 216,561
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
n = int(input())
st = input()
if(n > 26):
print(-1)
else:
li = [0] * 26
for i in range(n):
ch = ord(st[i]) - 97
li[ch] = li[ch] + 1
total = 0
count = 0
for i in range(26):
if(li[i] == 0):
count = count + 1
else:
total = total + (li[i] - 1)
if(total <= count):
print(total)
else:
print(-1)
```
|
instruction
| 0
| 108,281
| 0
| 216,562
|
Yes
|
output
| 1
| 108,281
| 0
| 216,563
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
from sys import stdin
n = int(input())
str = stdin.readline()
alphabet = "abcdefghijklmnopqrstuvwxyz"
count = [0] * 26
res = 0
if(n > 26):
print("-1")
else:
for ch in range(n):
for i in range(26):
if(str[ch] == alphabet[i]):
if(count[i] == 0):
count[i] = 1
else:
res += 1
print (res)
```
|
instruction
| 0
| 108,282
| 0
| 216,564
|
Yes
|
output
| 1
| 108,282
| 0
| 216,565
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
a=int(input())
t=input()
print(a-len(set(t)))
```
|
instruction
| 0
| 108,283
| 0
| 216,566
|
No
|
output
| 1
| 108,283
| 0
| 216,567
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
# https://codeforces.com/problemset/problem/672/B
n = input()
s = input()
l = []
l.extend(s)
print(len(l) - len(set(l)))
```
|
instruction
| 0
| 108,284
| 0
| 216,568
|
No
|
output
| 1
| 108,284
| 0
| 216,569
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
def check(s1):
if len(s1)==len(set(s1)):
return False
else:
return True
n=int(input())
s=input()
s1=list(s)
res=[]
c=0
if(check(s1)==True):
for i in s1:
if i not in res:
res.append(i)
c+=1
else:
print(0)
print(c)
```
|
instruction
| 0
| 108,285
| 0
| 216,570
|
No
|
output
| 1
| 108,285
| 0
| 216,571
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
n=int(input(""))
str=input("")
cnt=0
for i in range(n-1):
if str[i] in str[i+1:]:
cnt+=1
if cnt==0:
print(-1)
else:
print(cnt)
```
|
instruction
| 0
| 108,286
| 0
| 216,572
|
No
|
output
| 1
| 108,286
| 0
| 216,573
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 ≤ m ≤ 105) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
|
instruction
| 0
| 108,361
| 0
| 216,722
|
Tags: data structures, dp, strings
Correct Solution:
```
n = int(input()); s = input(); m = int(input())
a = [0]*(n+2); b = [0]*(n+2); q = [0]*(n+1);
dp = [(0, 0)]*(n+2)
for i in range(0, n):
b[i] = b[i-2]+(s[i] == 'b')
a[i] = a[i-2]+(s[i] == 'a')
q[i] = q[i-1]+(s[i] == '?')
for i in range(n-1, -1, -1):
if i+m-1 >= n:
continue
dp[i] = dp[i+1]
i_b = 1 if m%2 == 1 else 2
i_a = 1 if m%2 == 0 else 2
if not (b[i+m-i_b]-b[i-2] or a[i+m-i_a]-a[i-1]):
t, r = dp[i+m]
dp[i] = min((t-1, r+q[i+m-1]-q[i-1]), dp[i])
print(dp[0][1])
```
|
output
| 1
| 108,361
| 0
| 216,723
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 ≤ m ≤ 105) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
|
instruction
| 0
| 108,362
| 0
| 216,724
|
Tags: data structures, dp, strings
Correct Solution:
```
n = int(input()); s = input(); m = int(input())
a = [0]*(n+2); b = [0]*(n+2); q = [0]*(n+1);
dp = [(0, 0)]*(n+2)
for i in range(0, n):
b[i] = b[i-2]+(s[i] == 'b')
a[i] = a[i-2]+(s[i] == 'a')
q[i] = q[i-1]+(s[i] == '?')
for i in range(n-m, -1, -1):
dp[i] = dp[i+1]
i_b = 1 if m%2 == 1 else 2
i_a = 1 if m%2 == 0 else 2
if not (b[i+m-i_b]-b[i-2] or a[i+m-i_a]-a[i-1]):
t, r = dp[i+m]
dp[i] = min((t-1, r+q[i+m-1]-q[i-1]), dp[i])
print(dp[0][1])
```
|
output
| 1
| 108,362
| 0
| 216,725
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 ≤ m ≤ 105) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
|
instruction
| 0
| 108,363
| 0
| 216,726
|
Tags: data structures, dp, strings
Correct Solution:
```
match = 0; nonmatch = 0; count = 0
def calc_match(s, t, p):
global match
global nonmatch
global count
if p == len(s)-len(t):
return
if p+len(t) < len(s):
if s[p+len(t)] == '?':
count -= 1
elif s[p+len(t)] == t[-1]:
match -= 1
else:
nonmatch -= 1
match, nonmatch = nonmatch, match
if p+len(t) < len(s):
if s[p] == '?':
count += 1
elif s[p] == 'a':
match += 1
else:
nonmatch += 1
def init_match(s, t):
global match
global nonmatch
global count
p = len(s)-len(t)
for i in range(len(t)):
if s[p+i] == '?':
count += 1
elif s[p+i] == t[i]:
match += 1
else:
nonmatch += 1
n = int(input())
s = input()
m = int(input())
t = ""
for i in range(m):
if i%2==0:
t = t + 'a'
else:
t = t + 'b'
init_match(s,t)
dp = []
for i in range(n+3):
dp.append((0, 0))
p = n-m
while p >= 0:
calc_match(s, t, p)
if nonmatch == 0:
if dp[p+1][0] == dp[p+m][0]+1:
dp[p] = (dp[p+1][0], min(dp[p+1][1], dp[p+m][1]+count))
elif dp[p+1][0] > dp[p+m][0]+1:
dp[p] = dp[p+1]
else:
dp[p] = (dp[p+m][0]+1, dp[p+m][1]+count)
else:
dp[p] = dp[p+1]
p -= 1
print(dp[0][1])
```
|
output
| 1
| 108,363
| 0
| 216,727
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 ≤ m ≤ 105) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
|
instruction
| 0
| 108,364
| 0
| 216,728
|
Tags: data structures, dp, strings
Correct Solution:
```
match = 0
nonmatch = 0
count = 0
def calc_match(s, t, p):
global match
global nonmatch
global count
if p == len(s)-len(t):
return
if p+len(t) < len(s):
if s[p+len(t)] == '?':
count -= 1
elif s[p+len(t)] == t[-1]:
match -= 1
else:
nonmatch -= 1
match, nonmatch = nonmatch, match
if p+len(t) < len(s):
if s[p] == '?':
count += 1
elif s[p] == 'a':
match += 1
else:
nonmatch += 1
def init_match(s, t):
global match
global nonmatch
global count
p = len(s)-len(t)
for i in range(len(t)):
if s[p+i] == '?':
count += 1
elif s[p+i] == t[i]:
match += 1
else:
nonmatch += 1
n = int(input())
s = input()
m = int(input())
t = ""
for i in range(m):
if i%2==0:
t = t + 'a'
else:
t = t + 'b'
init_match(s,t)
dp = []
for i in range(n+3):
dp.append((0, 0))
p = n-m
while p >= 0:
calc_match(s, t, p)
if nonmatch == 0:
if dp[p+1][0] == dp[p+m][0]+1:
dp[p] = (dp[p+1][0], min(dp[p+1][1], dp[p+m][1]+count))
elif dp[p+1][0] > dp[p+m][0]+1:
dp[p] = dp[p+1]
else:
dp[p] = (dp[p+m][0]+1, dp[p+m][1]+count)
else:
dp[p] = dp[p+1]
p -= 1
print(dp[0][1])
```
|
output
| 1
| 108,364
| 0
| 216,729
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 ≤ m ≤ 105) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Submitted Solution:
```
n = int(input())
s = list(input())
t = int(input())
re = s.copy()
kras = 'ab'
kras *= t
kras = kras[:t]
col = s.count('?')
c = 0
v = 0
q = 0
h = 0
for i in range(2 ** col):
shable = bin(i)[2:]
priv = '0' * (col - len(shable))
priv += shable
shable = priv
for el in range(n):
if s[el] == '?':
if shable[q] == '1':
if el % 2 == 0:
s[el] = 'a'
else:
s[el] = 'b'
q += 1
new = ''.join(s).count(kras)
if new > c:
v = shable.count('1')
c = new
s = re.copy()
q = 0
h = 0
for i in range(2 ** col):
shable = bin(i)[2:]
priv = '0' * (col - len(shable))
priv += shable
shable = priv
for el in range(n):
if s[el] == '?':
if shable[q] == '1':
if el % 2 == 0:
s[el] = 'b'
else:
s[el] = 'a'
q += 1
new = ''.join(s).count(kras)
if new > c:
v = shable.count('1')
c = new
s = re.copy()
q = 0
h = 0
print(v)
```
|
instruction
| 0
| 108,365
| 0
| 216,730
|
No
|
output
| 1
| 108,365
| 0
| 216,731
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 ≤ m ≤ 105) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Submitted Solution:
```
match = 0
nonmatch = 0
count = 0
def calc_match(s, t, p):
global match
global nonmatch
global count
if p+len(t) < len(s):
if s[p+len(t)] == '?':
count -= 1
elif s[p+len(t)] == t[-1]:
match -= 1
else:
nonmatch -= 1
match, nonmatch = nonmatch, match
if p+len(t) < len(s):
if s[p] == '?':
count += 1
elif s[p] == 'a':
match += 1
else:
nonmatch += 1
def init_match(s, t):
global match
global nonmatch
global count
p = len(s)-len(t)
for i in range(len(t)):
if s[p+i] == '?':
count += 1
elif s[p+i] == t[i]:
match += 1
else:
nonmatch += 1
n = int(input())
s = input()
m = int(input())
t = ""
for i in range(m):
if i%2==0:
t = t + 'a'
else:
t = t + 'b'
init_match(s,t)
dp = []
for i in range(n+3):
dp.append((0, 0))
p = n-m
while p >= 0:
calc_match(s, t, p)
if nonmatch == 0:
if dp[p+1][0] == dp[p+m][0]+1:
dp[p] = (dp[p+1][0], min(dp[p+1][1], dp[p+m][1]+count))
elif dp[p+1][0] > dp[p+m][0]+1:
dp[p] = dp[p+1]
else:
dp[p] = (dp[p+m][0]+1, dp[p+m][1]+count)
else:
dp[p] = dp[p+1]
p -= 1
print(dp[0][1])
```
|
instruction
| 0
| 108,366
| 0
| 216,732
|
No
|
output
| 1
| 108,366
| 0
| 216,733
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≤ i ≤ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 ≤ m ≤ 105) — the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer — the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Submitted Solution:
```
n = int(input())
s = list(input())
t = int(input())
re = s.copy()
kras = 'ab'
kras *= t
kras = kras[:t]
col = s.count('?')
c = 0
v = 0
q = 0
h = 0
for i in range(2 ** col):
shable = bin(i)[2:]
priv = '0' * (col - len(shable))
priv += shable
shable = priv
for el in range(n):
if s[el] == '?':
if shable[q] == '1':
h += 1
if el % 2 == 0:
s[el] = 'a'
else:
s[el] = 'b'
q += 1
new = ''.join(s).count(kras)
if new > c:
v = h
c = new
s = re.copy()
q = 0
h = 0
print(v)
```
|
instruction
| 0
| 108,367
| 0
| 216,734
|
No
|
output
| 1
| 108,367
| 0
| 216,735
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.