text stringlengths 594 23.8k | conversation_id int64 97 109k | embedding list | cluster int64 0 0 |
|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.
Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ n^2) — the length of the string and the number of moves you can perform.
The second line of the test case contains one string consisting of n characters '0' and '1'.
It is guaranteed that the sum of n over all test cases does not exceed 10^6 (∑ n ≤ 10^6).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than k moves.
Example
Input
3
8 5
11011010
7 9
1111100
7 11
1111100
Output
01011110
0101111
0011111
Note
In the first example, you can change the string as follows: 1\underline{10}11010 → \underline{10}111010 → 0111\underline{10}10 → 011\underline{10}110 → 01\underline{10}1110 → 01011110.
In the third example, there are enough operations to make the string sorted.
Submitted Solution:
```
q = int(input())
for _ in range(q):
n, k = map(int, input().split())
s = list(input())
c = k
try:
pzero = s.index('1')
except ValueError:
print("".join(s))
continue
pone = 0
while c > 0:
try:
pzero = s.index('0', pzero)
pone = s.index('1', max(pone, pzero - c))
except ValueError:
break
s[pzero] = '1'
s[pone] = '0'
c -= pzero - pone
print("".join(s))
```
Yes
| 43,061 | [
0.450439453125,
0.002857208251953125,
-0.0989990234375,
0.261474609375,
-0.732421875,
-0.4912109375,
0.04510498046875,
0.42431640625,
-0.006198883056640625,
0.86474609375,
0.9111328125,
-0.25830078125,
-0.051971435546875,
-0.873046875,
-0.75927734375,
0.1529541015625,
-0.5908203125,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.
Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ n^2) — the length of the string and the number of moves you can perform.
The second line of the test case contains one string consisting of n characters '0' and '1'.
It is guaranteed that the sum of n over all test cases does not exceed 10^6 (∑ n ≤ 10^6).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than k moves.
Example
Input
3
8 5
11011010
7 9
1111100
7 11
1111100
Output
01011110
0101111
0011111
Note
In the first example, you can change the string as follows: 1\underline{10}11010 → \underline{10}111010 → 0111\underline{10}10 → 011\underline{10}110 → 01\underline{10}1110 → 01011110.
In the third example, there are enough operations to make the string sorted.
Submitted Solution:
```
for _ in range(int(input())):
n, k = map(int, input().split())
s = input()
s = [x for x in s]
ch = 0
t = 0
j = True
for i in range(len(s)):
if s[i] == '0':
if ch + i - t > k:
s[i] = '1'
s[i - k + ch] = '0'
break
else:
s[i] = '1'
s[t] = '0'
ch += i - t
t += 1
print(''.join(s))
```
Yes
| 43,062 | [
0.419921875,
0.07025146484375,
-0.095458984375,
0.254150390625,
-0.71044921875,
-0.469482421875,
0.06927490234375,
0.3408203125,
0.01267242431640625,
0.85205078125,
0.95556640625,
-0.25341796875,
-0.1483154296875,
-0.96728515625,
-0.818359375,
0.17431640625,
-0.59716796875,
-0.6181... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.
Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ n^2) — the length of the string and the number of moves you can perform.
The second line of the test case contains one string consisting of n characters '0' and '1'.
It is guaranteed that the sum of n over all test cases does not exceed 10^6 (∑ n ≤ 10^6).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than k moves.
Example
Input
3
8 5
11011010
7 9
1111100
7 11
1111100
Output
01011110
0101111
0011111
Note
In the first example, you can change the string as follows: 1\underline{10}11010 → \underline{10}111010 → 0111\underline{10}10 → 011\underline{10}110 → 01\underline{10}1110 → 01011110.
In the third example, there are enough operations to make the string sorted.
Submitted Solution:
```
m = int(input())
for j in range(m):
n, k = map(int, input().split())
a = input()
b = []
t = 0
c = list(a)
s = 0
for i in range(n):
if a[i] == '0':
if i - s <= k:
c[s] = '0'
k -= i - s
else:
if k > 0:
c[i - k] = '0'
c[i] = '1'
break
s += 1
if i != t:
c[i] = '1'
t += 1
print(''.join(c))
```
Yes
| 43,063 | [
0.416748046875,
0.0640869140625,
-0.08428955078125,
0.2249755859375,
-0.72900390625,
-0.4736328125,
0.04083251953125,
0.36962890625,
0.0244598388671875,
0.86181640625,
0.91552734375,
-0.21240234375,
-0.13818359375,
-0.947265625,
-0.810546875,
0.1707763671875,
-0.59375,
-0.615722656... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.
Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ n^2) — the length of the string and the number of moves you can perform.
The second line of the test case contains one string consisting of n characters '0' and '1'.
It is guaranteed that the sum of n over all test cases does not exceed 10^6 (∑ n ≤ 10^6).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than k moves.
Example
Input
3
8 5
11011010
7 9
1111100
7 11
1111100
Output
01011110
0101111
0011111
Note
In the first example, you can change the string as follows: 1\underline{10}11010 → \underline{10}111010 → 0111\underline{10}10 → 011\underline{10}110 → 01\underline{10}1110 → 01011110.
In the third example, there are enough operations to make the string sorted.
Submitted Solution:
```
def BinaryStringMinimizing(n,k,text):
i=0
cnt=0
result=''
i0=0
while i0<n and k>0:
i0 = FindZeroAfterIndex(text, i0)
if i0==-1:
break
cnt = i0-i
if cnt<=k:
text[i0] = '1'
text[i] = '0'
k-=cnt
else:
text[i0] = '1'
text[i0-k] = '0'
k=0
i0+=1
i+=1
result="".join(text)
return result
def FindZeroAfterIndex(text, index):
i=index
while i<n:
if int(text[i])==0:
return i
i+=1
return -1
q=int(input())
result=''
while q>0:
n,k = [int(x) for x in input().split()]
text =[x for x in input()]
result+=BinaryStringMinimizing(n,k,text)
if q>1:
result+='\n'
q-=1
print(result)
```
Yes
| 43,064 | [
0.497802734375,
-0.015655517578125,
-0.0262908935546875,
0.2054443359375,
-0.64013671875,
-0.493896484375,
-0.04010009765625,
0.369384765625,
-0.017303466796875,
0.79150390625,
0.93798828125,
-0.40283203125,
-0.05145263671875,
-0.818359375,
-0.7421875,
0.1724853515625,
-0.6162109375,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.
Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ n^2) — the length of the string and the number of moves you can perform.
The second line of the test case contains one string consisting of n characters '0' and '1'.
It is guaranteed that the sum of n over all test cases does not exceed 10^6 (∑ n ≤ 10^6).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than k moves.
Example
Input
3
8 5
11011010
7 9
1111100
7 11
1111100
Output
01011110
0101111
0011111
Note
In the first example, you can change the string as follows: 1\underline{10}11010 → \underline{10}111010 → 0111\underline{10}10 → 011\underline{10}110 → 01\underline{10}1110 → 01011110.
In the third example, there are enough operations to make the string sorted.
Submitted Solution:
```
def count_zeros(string):
cnt = 0
for c in string:
if c == '0':
cnt += 1
return cnt
q = int(input())
for _ in range(q):
n, k = map(int, input().split())
s = input()
m = count_zeros(s)
if m == 0 or m == 1:
print(s)
continue
positions = [0] * m
first, j = -1, 0
for i in range(n):
if s[i] == '1':
if first < 0:
first = 0
else:
shift = min(k, i - first)
if shift < k:
first += 1
k -= shift
positions[j] = i - shift
j += 1
res = ['0'] * n
for i in range(m - 1):
for k in range(positions[i] + 1, positions[i + 1]):
res[k] = '1'
for k in range(positions[m - 1] + 1, n):
res[k] = '1'
print(''.join(res))
```
No
| 43,065 | [
0.439453125,
0.0533447265625,
-0.10675048828125,
0.18994140625,
-0.67919921875,
-0.513671875,
0.058868408203125,
0.38671875,
-0.04095458984375,
0.90869140625,
0.87255859375,
-0.19580078125,
-0.12286376953125,
-0.9150390625,
-0.76806640625,
0.1812744140625,
-0.5625,
-0.61572265625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.
Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ n^2) — the length of the string and the number of moves you can perform.
The second line of the test case contains one string consisting of n characters '0' and '1'.
It is guaranteed that the sum of n over all test cases does not exceed 10^6 (∑ n ≤ 10^6).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than k moves.
Example
Input
3
8 5
11011010
7 9
1111100
7 11
1111100
Output
01011110
0101111
0011111
Note
In the first example, you can change the string as follows: 1\underline{10}11010 → \underline{10}111010 → 0111\underline{10}10 → 011\underline{10}110 → 01\underline{10}1110 → 01011110.
In the third example, there are enough operations to make the string sorted.
Submitted Solution:
```
def find_zero_start_from(start_pos, li):
for i in range(start_pos, len(li)):
if li[i] == '0':
return i
return -1
def minimize_binary(n, k, s):
moves_done = 0
res = list(s)
start_pos = 0
while moves_done < k:
first_zero_ind = find_zero_start_from(start_pos, res)
if first_zero_ind == -1:
break
if first_zero_ind < k - moves_done:
res[first_zero_ind] = '1'
res[start_pos] = '0'
moves_done += first_zero_ind - start_pos
start_pos = start_pos + 1
else:
new_idx = first_zero_ind - (k - moves_done)
res[first_zero_ind] = '1'
res[max(new_idx, start_pos)] = '0'
moves_done = k
return "".join(res)
def solve():
q = int(input())
for _ in range(q):
n, k = map(int, input().split())
s = input()
print(minimize_binary(n, k, s))
if __name__ == "__main__":
solve()
```
No
| 43,066 | [
0.449462890625,
0.085693359375,
-0.072509765625,
0.233154296875,
-0.7392578125,
-0.49755859375,
-0.0205841064453125,
0.36767578125,
0.0030193328857421875,
0.80615234375,
0.95703125,
-0.29345703125,
-0.1312255859375,
-0.85302734375,
-0.78369140625,
0.1695556640625,
-0.5703125,
-0.52... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.
Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ n^2) — the length of the string and the number of moves you can perform.
The second line of the test case contains one string consisting of n characters '0' and '1'.
It is guaranteed that the sum of n over all test cases does not exceed 10^6 (∑ n ≤ 10^6).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than k moves.
Example
Input
3
8 5
11011010
7 9
1111100
7 11
1111100
Output
01011110
0101111
0011111
Note
In the first example, you can change the string as follows: 1\underline{10}11010 → \underline{10}111010 → 0111\underline{10}10 → 011\underline{10}110 → 01\underline{10}1110 → 01011110.
In the third example, there are enough operations to make the string sorted.
Submitted Solution:
```
def minlex(n,k,st):
noz=st.count('0');
j,count=1,0;
first,last=0,n;
while j<=noz:
pos=st.find('0',first,last);
if pos==-1:
break;
if count+pos-first>k:
diff=k-count;
if pos-diff!= pos:
st=st[0:pos-diff]+st[pos]+st[pos-diff+1:pos]+st[pos-diff]+st[pos+1:len(st)];
break;
else:
count=count+pos-first;
st=st[0:first]+st[pos]+st[first+1:pos]+st[first]+st[pos+1:len(st)]
j+=1;
first+=1;
return st;
q=int(input());
answers=[""]*q
for i in range(0,q):
line=input().split();
s=input();
answers[i]=minlex(int(line[0]),int(line[1]),s);
for i in answers:
print(i);
```
No
| 43,067 | [
0.42041015625,
0.07904052734375,
-0.05364990234375,
0.25146484375,
-0.77099609375,
-0.55908203125,
-0.024139404296875,
0.38232421875,
0.0009937286376953125,
0.85302734375,
0.93115234375,
-0.2626953125,
-0.162109375,
-0.91064453125,
-0.7978515625,
0.1971435546875,
-0.52880859375,
-0... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a binary string of length n (i. e. a string consisting of n characters '0' and '1').
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k moves? It is possible that you do not perform any moves at all.
Note that you can swap the same pair of adjacent characters with indices i and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases.
The first line of the test case contains two integers n and k (1 ≤ n ≤ 10^6, 1 ≤ k ≤ n^2) — the length of the string and the number of moves you can perform.
The second line of the test case contains one string consisting of n characters '0' and '1'.
It is guaranteed that the sum of n over all test cases does not exceed 10^6 (∑ n ≤ 10^6).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than k moves.
Example
Input
3
8 5
11011010
7 9
1111100
7 11
1111100
Output
01011110
0101111
0011111
Note
In the first example, you can change the string as follows: 1\underline{10}11010 → \underline{10}111010 → 0111\underline{10}10 → 011\underline{10}110 → 01\underline{10}1110 → 01011110.
In the third example, there are enough operations to make the string sorted.
Submitted Solution:
```
t = int(input())
for _ in range(t):
n, k = [int(p) for p in input().split()]
s = list(input())
curr = []
j = 0
for i in range(n):
if s[i] == '1':
curr.append(i)
elif s[i] == '0' and j < len(curr):
if k >= i-curr[j]:
s[i] = '1'
s[curr[j]] = '0'
k -= i-curr[j]
else:
s[i] = '1'
s[i-k] = '0'
break
j += 1
print(''.join(s))
```
No
| 43,068 | [
0.42822265625,
0.059783935546875,
-0.07525634765625,
0.239013671875,
-0.73974609375,
-0.467041015625,
0.0389404296875,
0.352294921875,
0.020111083984375,
0.83447265625,
0.9150390625,
-0.230224609375,
-0.1536865234375,
-0.927734375,
-0.8212890625,
0.1668701171875,
-0.57666015625,
-0... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Tags: binary search, dp, hashing, string suffix structures, strings
Correct Solution:
```
from typing import Tuple
def comp_z(s: str) -> Tuple[int]:
"""Computes the z-array for a given string s.
z[i] := the length of the longest substring of s, starting at index i, which is also a prefix of s.
0 <= i < len(s); z[0] = len(s).
"""
n = len(s)
z = [0] * n
z[0] = n
# left and right boundaries of the current right most z-box [L,R)
L, R = 0, 0
for i in range(1, n):
if i >= R:
L = i
R = i
while R < n and s[R] == s[R-L]:
R += 1
z[i] = R-L
else: # L < i < R
# len of [i,R)
x = R-i
if x > z[i-L]:
z[i] = z[i-L]
else: # x <= z[i-L] and we know s[i..R) matches prefix
L = i
# continue matching from R onwards
while R < n and s[R] == s[R-L]:
R += 1
z[i] = R-L
return tuple(z)
def run():
"""Solves https://codeforces.com/contest/126/problem/B."""
s = input()
n = len(s)
z = comp_z(s)
maxz = 0
res = 0
for i in range(1, n):
if z[i] == n-i and maxz >= n-i:
res = n-i
# break as we already found the longest one;
# as i increases, the length decreases
break
maxz = max(maxz, z[i])
if res == 0:
print('Just a legend')
else:
print(s[:res])
if __name__ == "__main__":
run()
```
| 43,072 | [
0.364501953125,
-0.08966064453125,
0.26806640625,
0.03863525390625,
-0.228759765625,
-0.255859375,
-0.10980224609375,
0.08349609375,
0.10418701171875,
0.7060546875,
0.55224609375,
0.2291259765625,
0.050994873046875,
-0.94091796875,
-0.90185546875,
0.33154296875,
-0.359375,
-0.50976... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Submitted Solution:
```
s=input()
def kmp_fail(p):
m=len(p)
fail=m*[0]
k=0
j=1
while j<m:
if p[j]==p[k]:
fail[j]=k+1
j+=1
k+=1
elif k>0:
k=fail[k-1]
else:
j+=1
return fail
l=[-1]+kmp_fail(s)
le=l[-1]
if l.count(le)<2:
le=l[le]
print(s[:le] if le>0 else 'Just a legend')
```
Yes
| 43,077 | [
0.46142578125,
0.053619384765625,
0.07965087890625,
0.017333984375,
-0.29052734375,
-0.1915283203125,
-0.09173583984375,
0.12548828125,
0.09381103515625,
0.6533203125,
0.57177734375,
0.1614990234375,
-0.085205078125,
-1.0244140625,
-0.921875,
0.338623046875,
-0.424560546875,
-0.554... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Submitted Solution:
```
def z_func(s):
l = 0
r = 0
n = len(s)
z = [0]*n
z[0] = n
for i in range(1, n):
if i <= r:
z[i] = min(r-i+1, z[i-l])
while (i+z[i] < n) and (s[z[i]] == s[i+z[i]]):
z[i] += 1
if i+z[i]-1 > r:
l = i
r = i+z[i]-1
return z
string = input()
n = len(string)
z = z_func(string)
l = 0
for i in range(1,n):
if z[i]==n-i:
for j in range(1,i):
if z[j]>=z[i]:
l = z[i]
break
if l>0:
break
if l>0:
print(string[0:l])
else:
print('Just a legend')
```
Yes
| 43,078 | [
0.427978515625,
0.032257080078125,
0.1063232421875,
-0.0071868896484375,
-0.32421875,
-0.15380859375,
-0.14599609375,
0.16162109375,
0.08709716796875,
0.611328125,
0.57666015625,
0.1929931640625,
-0.1591796875,
-0.98046875,
-0.89453125,
0.284423828125,
-0.447265625,
-0.56640625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Submitted Solution:
```
s=input()
M=len(s)
lps=[0]*M
len=0
i=1
while i < M:
if s[i]== s[len]:
len += 1
lps[i] = len
i += 1
else:
if len != 0:
len = lps[len-1]
else:
lps[i] = 0
i += 1
t=lps[-1]
flag=1
while t:
for i in range(1,M-1):
if lps[i]==t:
flag=0
break
else:
flag=1
if flag==0:
break
t=lps[t-1]
print(s[:t]) if flag==0 else print('Just a legend')
```
Yes
| 43,079 | [
0.431640625,
0.0096893310546875,
0.10577392578125,
0.01532745361328125,
-0.32763671875,
-0.1522216796875,
-0.11492919921875,
0.1588134765625,
0.1265869140625,
0.6484375,
0.57861328125,
0.194091796875,
-0.1663818359375,
-1.0048828125,
-0.91064453125,
0.245361328125,
-0.45849609375,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Submitted Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 12/25/19
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
from functools import lru_cache
# TLE at the 91th test case, 97 cases in total
def solve_hash(s):
MOD = 10**9+7
N = len(s)
ha, hb = 0, 0
possible = []
x, oa = 1, ord('a')
w = [ord(v)-oa for v in s]
for i, v in enumerate(w):
ha = (ha * 26 + v) % MOD
hb = (w[N-i-1] * x + hb) % MOD
x = (x * 26) % MOD
if ha == hb:
possible.append((i+1))
def check(m):
l = possible[m]
t = s.find(s[:l], 1)
return t > 0 and t != N-l
lo, hi = 0, len(possible)
while lo <= hi:
m = (lo + hi) // 2
if check(m):
lo = m + 1
else:
hi = m - 1
return s[:possible[hi]] if hi >= 0 else 'Just a legend'
def solve_zscore(s):
"""
https://cp-algorithms.com/string/z-function.html
In z-function, z[i] means from i, the maximum number of chars is prefix of s.
when i + z[i] == len(s), mean s[i:] == s[:z[i]], if there is another index j < i and z[j] >= z[i] means s[:z[i]]
are prefix, suffix and another substring
"""
z, maxl = [0] * len(s), 0
i, l, r, n = 1, 0, 0, len(s)
while i < n:
if i <= r:
z[i] = min(r-i+1, z[i-l])
while i + z[i] < n and s[z[i]] == s[z[i] + i]:
z[i] += 1
if i + z[i] - 1 > r:
l, r = i, i + z[i] - 1
if i + z[i] == n:
if z[i] <= maxl:
return s[:z[i]]
maxl = max(maxl, z[i])
i += 1
return 'Just a legend'
def solve_prefix(s):
"""
https://cp-algorithms.com/string/prefix-function.html
The prefix function for this string is defined as an array π of length n,
where π[i] is the length of the longest proper prefix of the substring s[0…i]
which is also a suffix of this substring.
A proper prefix of a string is a prefix that is not equal to the string itself. By definition, π[0]=0.
"""
n, pi = len(s), [0] * len(s)
for i in range(1, n):
j = pi[i-1]
while j > 0 and s[i] != s[j]:
j = pi[j-1]
if s[i] == s[j]:
j += 1
pi[i] = j
if pi[-1] > 0:
if any([pi[i] >= pi[-1] for i in range(n - 1)]):
return s[:pi[-1]]
else:
p = pi[pi[-1] - 1]
if p > 0:
return s[:p]
return 'Just a legend'
s = input()
# solve_zscore(s)
print(solve_prefix(s))
```
Yes
| 43,080 | [
0.41064453125,
-0.00965118408203125,
0.043060302734375,
0.0019102096557617188,
-0.328369140625,
-0.1217041015625,
-0.10931396484375,
0.181396484375,
0.12353515625,
0.6123046875,
0.5537109375,
0.1678466796875,
-0.13427734375,
-0.9990234375,
-0.890625,
0.2314453125,
-0.4013671875,
-0... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Submitted Solution:
```
def getZarr(string, z):
n = len(string)
# [L,R] make a window which matches
# with prefix of s
l, r, k = 0, 0, 0
for i in range(1, n):
# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i
# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:
# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l
# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]
# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:
# else start from R and check manually
l = i
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
s = input()
h=[0]*len(s)
getZarr(s,h)
# print(h)
getZarr(s[::-1],h)
# print(h)
getZarr(s[ int(len(s)/4):int(len(s)*3/4) ],h)
max = 0;
imax=-1
for i in range(len(s)):
if h[i]>max :
max = h[i]
imax=i
print(s[imax:imax+max])
```
No
| 43,081 | [
0.39404296875,
-0.001956939697265625,
0.13525390625,
0.004047393798828125,
-0.292724609375,
-0.1861572265625,
-0.11004638671875,
0.118408203125,
0.102783203125,
0.63623046875,
0.56005859375,
0.1402587890625,
-0.09954833984375,
-1.0361328125,
-0.8828125,
0.2685546875,
-0.43310546875,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Submitted Solution:
```
def kmpfailureFunc(P) :
lP=len(P)
kmptable=[0,0] #the "position" here is where the first dismatch occurs
k=0
i=1
while i<lP :
if P[i]==P[k] :
kmptable.append(k+1)
i+=1
k+=1
elif k>0 :
k=kmptable[k-1]
else :
kmptable.append(0)
i+=1
return kmptable
s=input()
L=len(s)
l=L-2
kmpfailFunc=kmpfailureFunc(s)
longest=kmpfailFunc[-1]
if l>0 :
ind=0
while longest>0:
i=3
while i<L :
if longest==kmpfailFunc[i] :
ind=1
break
i+=1
if ind :
print(s[:longest])
break
else :
longest=kmpfailFunc[longest]
if not ind :
print("Just a legend")
else :
print("Just a legend")
```
No
| 43,082 | [
0.456787109375,
-0.0222015380859375,
0.0090789794921875,
0.16015625,
-0.2763671875,
-0.151123046875,
-0.10479736328125,
0.171875,
0.00449371337890625,
0.6669921875,
0.55908203125,
0.09326171875,
-0.1385498046875,
-1.0146484375,
-0.96484375,
0.37646484375,
-0.389892578125,
-0.626464... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Submitted Solution:
```
lst1 = list(input())
lenlst1 = len(lst1)
lst2 = []
for i in range(lenlst1):
lst2.append(lst1[i])
out = []
del lst2[0]
del lst2[-1]
for i in range(lenlst1):
sub1 = ("".join(lst1[0:i+1]))
sub2 = ("".join(lst1[-i-1::]))
if sub1 == sub2 and i != lenlst1 - 1:
if sub1 in ("".join(lst2)):
out = sub1
break
if out == []:
print("Just a legend")
else:
print("".join(out))
```
No
| 43,083 | [
0.435546875,
0.0276336669921875,
0.1546630859375,
-0.0540771484375,
-0.354736328125,
-0.149658203125,
-0.0877685546875,
0.1651611328125,
0.1275634765625,
0.65869140625,
0.55126953125,
0.167724609375,
-0.1663818359375,
-1.017578125,
-0.93798828125,
0.2242431640625,
-0.445556640625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.
Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.
Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened.
You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
Input
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
Output
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
Examples
Input
fixprefixsuffix
Output
fix
Input
abcdabc
Output
Just a legend
Submitted Solution:
```
s=input()
t=''
rs=s[::-1]
n=len(s)
newt=''
for i in range(n-1):
if(s[0]==rs[i]):
for j in range(i+1):
if s[j]==rs[i-j]:
t+=s[j]
else:
break
if(len(newt)<len(t) and t in s[1:n-1] and t[-1]==rs[0]):
newt=t
t=''
if((len(set(s))!=1)&(newt in s[1:n-1])&(len(newt)>1)):
print(newt)
elif(len(set(s))==1 and len(s)>2):
print(s[1:n-1])
else:
print('Just a legend')
```
No
| 43,084 | [
0.43701171875,
0.01824951171875,
0.09588623046875,
-0.035614013671875,
-0.309326171875,
-0.158447265625,
-0.09210205078125,
0.1629638671875,
0.12060546875,
0.63623046875,
0.60693359375,
0.182861328125,
-0.1502685546875,
-1.0234375,
-0.90185546875,
0.224365234375,
-0.44921875,
-0.60... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
"Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
MOD = 998244353
INF = 2 * 10**18
in_n = lambda: int(input())
in_nn = lambda: map(int, input().split())
in_s = lambda: input().rstrip().decode('utf-8')
in_map = lambda: [s == ord('.') for s in input() if s != ord('\n')]
# ----- seg tree設定 ----- #
e = 0
id = -1
MASK = 32
def op(a, b):
a1, a2 = divmod(a, 1 << MASK)
b1, b2 = divmod(b, 1 << MASK)
c1 = (a1 + b1) % MOD
c2 = (a2 + b2) % MOD
return (c1 << MASK) + c2
def mapping(x, a):
if x == -1:
return a
a1, a2 = divmod(a, 1 << MASK)
c1 = (x * a2) % MOD
c2 = a2
return (c1 << MASK) + c2
def composition(x, y):
if x == -1:
return y
return x
# ----- seg tree設定 ここまで ----- #
class LazySegTree:
def __init__(self, op, e, mapping, composition, id, n: int = -1, v: list = []):
assert (len(v) > 0) | (n > 0)
if(len(v) == 0):
v = [e] * n
self.__n = len(v)
self.__log = (self.__n - 1).bit_length()
self.__size = 1 << self.__log
self.__d = [e] * (2 * self.__size)
self.__lz = [id] * self.__size
self.__op = op
self.__e = e
self.__mapping = mapping
self.__composition = composition
self.__id = id
for i in range(self.__n):
self.__d[self.__size + i] = v[i]
for i in range(self.__size - 1, 0, -1):
self.__update(i)
def __update(self, k: int):
self.__d[k] = self.__op(self.__d[2 * k], self.__d[2 * k + 1])
def __all_apply(self, k: int, f):
self.__d[k] = self.__mapping(f, self.__d[k])
if(k < self.__size):
self.__lz[k] = self.__composition(f, self.__lz[k])
def __push(self, k: int):
self.__all_apply(2 * k, self.__lz[k])
self.__all_apply(2 * k + 1, self.__lz[k])
self.__lz[k] = self.__id
def set(self, p: int, x):
assert (0 <= p) & (p < self.__n)
p += self.__size
for i in range(self.__log, 0, -1):
self.__push(p >> i)
self.__d[p] = x
for i in range(1, self.__log + 1):
self.__update(p >> i)
def get(self, p: int):
assert (0 <= p) & (p < self.__n)
p += self.__size
for i in range(self.__log, 0, -1):
self.__push(p >> i)
return self.__d[p]
def prod(self, l: int, r: int):
assert (0 <= l) & (l <= r) & (r <= self.__n)
if(l == r):
return self.__e
l += self.__size
r += self.__size
for i in range(self.__log, 0, -1):
if((l >> i) << i) != l:
self.__push(l >> i)
if((r >> i) << i) != r:
self.__push(r >> i)
sml = self.__e
smr = self.__e
while(l < r):
if(l & 1):
sml = self.__op(sml, self.__d[l])
l += 1
if(r & 1):
r -= 1
smr = self.__op(self.__d[r], smr)
l //= 2
r //= 2
return self.__op(sml, smr)
def all_prod(self):
return self.__d[1]
def apply(self, p: int, f):
assert (0 <= p) & (p < self.__n)
p += self.__size
for i in range(self.__log, 0, -1):
self.__push(p >> i)
self.__d[p] = self.__mapping(f, self.__d[p])
for i in range(1, self.__log + 1):
self.__update(p >> i)
def apply_range(self, l: int, r: int, f):
assert (0 <= l) & (l <= r) & (r <= self.__n)
if(l == r):
return
l += self.__size
r += self.__size
for i in range(self.__log, 0, -1):
if((l >> i) << i) != l:
self.__push(l >> i)
if((r >> i) << i) != r:
self.__push((r - 1) >> i)
l2, r2 = l, r
while(l < r):
if(l & 1):
self.__all_apply(l, f)
l += 1
if(r & 1):
r -= 1
self.__all_apply(r, f)
l //= 2
r //= 2
l, r = l2, r2
for i in range(1, self.__log + 1):
if((l >> i) << i) != l:
self.__update(l >> i)
if((r >> i) << i) != r:
self.__update((r - 1) >> i)
def max_right(self, l: int, g):
assert (0 <= l) & (l <= self.__n)
assert g(self.__e)
if(l == self.__n):
return self.__n
l += self.__size
for i in range(self.__log, 0, -1):
self.__push(l >> i)
sm = self.__e
while(True):
while(l % 2 == 0):
l //= 2
if(not g(self.__op(sm, self.__d[l]))):
while(l < self.__size):
self.__push(l)
l *= 2
if(g(self.__op(sm, self.__d[l]))):
sm = self.__op(sm, self.__d[l])
l += 1
return l - self.__size
sm = self.__op(sm, self.__d[l])
l += 1
if(l & -l) == l:
break
return self.__n
def min_left(self, r: int, g):
assert (0 <= r) & (r <= self.__n)
assert g(self.__e)
if(r == 0):
return 0
r += self.__size
for i in range(self.__log, 0, -1):
self.__push((r - 1) >> i)
sm = self.__e
while(True):
r -= 1
while(r > 1) & (r % 2):
r //= 2
if(not g(self.__op(self.__d[r], sm))):
while(r < self.__size):
self.__push(r)
r = 2 * r + 1
if(g(self.__op(self.__d[r], sm))):
sm = self.__op(self.__d[r], sm)
r -= 1
return r + 1 - self.__size
sm = self.__op(self.__d[r], sm)
if(r & -r) == r:
break
return 0
def all_push(self):
for i in range(1, self.__size):
self.__push(i)
def get_all(self):
self.all_push()
return self.__d[self.__size:self.__size + self.__n]
def print(self):
print(list(map(lambda x: divmod(x, (1 << 30)), self.__d)))
print(self.__lz)
print('------------------')
def main():
N, Q = in_nn()
A = [0] * N
tmp = 1
for i in range(N - 1, -1, -1):
A[i] = (tmp << MASK) + tmp
tmp *= 10
tmp %= MOD
seg = LazySegTree(op, e, mapping, composition, id, v=A)
ans = [0] * Q
for i in range(Q):
l, r, d = in_nn()
l -= 1
seg.apply_range(l, r, d)
ans[i] = seg.all_prod() >> MASK
print('\n'.join(map(str, ans)))
if __name__ == '__main__':
main()
```
| 43,544 | [
0.2020263671875,
-0.07464599609375,
0.030517578125,
0.0703125,
-0.67724609375,
-0.2283935546875,
0.2188720703125,
-0.0295867919921875,
0.310546875,
0.82666015625,
0.50244140625,
-0.216064453125,
0.05523681640625,
-0.73876953125,
-0.63330078125,
0.2132568359375,
-0.357666015625,
-0.... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
"Correct Solution:
```
#!/usr/bin/env python3
import sys
def input(): return sys.stdin.readline().rstrip()
# ライブラリ参照https://atcoder.jp/contests/practice2/submissions/16579094
class LazySegmentTree():
def __init__(self, init, unitX, unitA, f, g, h):
self.f = f # (X, X) -> X
self.g = g # (X, A, size) -> X
self.h = h # (A, A) -> A
self.unitX = unitX
self.unitA = unitA
self.f = f
if type(init) == int:
self.n = init
# self.n = 1 << (self.n - 1).bit_length()
self.X = [unitX] * (self.n * 2)
self.size = [1] * (self.n * 2)
else:
self.n = len(init)
# self.n = 1 << (self.n - 1).bit_length()
self.X = [unitX] * self.n + init + [unitX] * (self.n - len(init))
self.size = [0] * self.n + [1] * \
len(init) + [0] * (self.n - len(init))
for i in range(self.n-1, 0, -1):
self.X[i] = self.f(self.X[i*2], self.X[i*2 | 1])
for i in range(self.n - 1, 0, -1):
self.size[i] = self.size[i*2] + self.size[i*2 | 1]
self.A = [unitA] * (self.n * 2)
def update(self, i, x):
i += self.n
self.X[i] = x
i >>= 1
while i:
self.X[i] = self.f(self.X[i*2], self.X[i*2 | 1])
i >>= 1
def calc(self, i):
return self.g(self.X[i], self.A[i], self.size[i])
def calc_above(self, i):
i >>= 1
while i:
self.X[i] = self.f(self.calc(i*2), self.calc(i*2 | 1))
i >>= 1
def propagate(self, i):
self.X[i] = self.g(self.X[i], self.A[i], self.size[i])
self.A[i*2] = self.h(self.A[i*2], self.A[i])
self.A[i*2 | 1] = self.h(self.A[i*2 | 1], self.A[i])
self.A[i] = self.unitA
def propagate_above(self, i):
H = i.bit_length()
for h in range(H, 0, -1):
self.propagate(i >> h)
def propagate_all(self):
for i in range(1, self.n):
self.propagate(i)
def getrange(self, l, r):
l += self.n
r += self.n
l0, r0 = l // (l & -l), r // (r & -r) - 1
self.propagate_above(l0)
self.propagate_above(r0)
al = self.unitX
ar = self.unitX
while l < r:
if l & 1:
al = self.f(al, self.calc(l))
l += 1
if r & 1:
r -= 1
ar = self.f(self.calc(r), ar)
l >>= 1
r >>= 1
return self.f(al, ar)
def getvalue(self, i):
i += self.n
self.propagate_above(i)
return self.calc(i)
def operate_range(self, l, r, a):
l += self.n
r += self.n
l0, r0 = l // (l & -l), r // (r & -r) - 1
self.propagate_above(l0)
self.propagate_above(r0)
while l < r:
if l & 1:
self.A[l] = self.h(self.A[l], a)
l += 1
if r & 1:
r -= 1
self.A[r] = self.h(self.A[r], a)
l >>= 1
r >>= 1
self.calc_above(l0)
self.calc_above(r0)
# Find r s.t. calc(l, ..., r-1) = True and calc(l, ..., r) = False
def max_right(self, l, z):
if l >= self.n:
return self.n
l += self.n
s = self.unitX
while 1:
while l % 2 == 0:
l >>= 1
if not z(self.f(s, self.calc(l))):
while l < self.n:
l *= 2
if z(self.f(s, self.calc(l))):
s = self.f(s, self.calc(l))
l += 1
return l - self.n
s = self.f(s, self.calc(l))
l += 1
if l & -l == l:
break
return self.n
# Find l s.t. calc(l, ..., r-1) = True and calc(l-1, ..., r-1) = False
def min_left(self, r, z):
if r <= 0:
return 0
r += self.n
s = self.unitX
while 1:
r -= 1
while r > 1 and r % 2:
r >>= 1
if not z(self.f(self.calc(r), s)):
while r < self.n:
r = r * 2 + 1
if z(self.f(self.calc(r), s)):
s = self.f(self.calc(r), s)
r -= 1
return r + 1 - self.n
s = self.f(self.calc(r), s)
if r & -r == r:
break
return 0
def main():
P = 998244353
def f(x, y): return ((x[0] + y[0]) % P, x[1]+y[1])
def g(x, a, s): return ((x[1]*a) % P, x[1]) if a != 10**10 else x
def h(a, b): return b if b != 10**10 else a
unitX = (0, 0)
unitA = 10**10
N, Q = map(int, input().split())
A = [(1, 1)]
for _ in range(N-1):
now = A[-1][0]
A.append(((now*10) % P, (now*10) % P))
st = LazySegmentTree(A[::-1], unitX, unitA, f, g, h)
#print(st.getrange(0, N))
for _ in range(Q):
l, r, d = map(int, input().split())
st.operate_range(l-1, r, d)
print(st.getrange(0, N)[0])
if __name__ == '__main__':
main()
```
| 43,545 | [
0.1729736328125,
-0.1749267578125,
0.1053466796875,
-0.07830810546875,
-0.66455078125,
-0.166015625,
0.2320556640625,
-0.2030029296875,
0.3369140625,
0.744140625,
0.505859375,
-0.27099609375,
0.1376953125,
-0.69091796875,
-0.61572265625,
0.11480712890625,
-0.50146484375,
-0.7919921... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
"Correct Solution:
```
MOD = 998244353
class LazySegmentTree: # from https://atcoder.jp/contests/practice2/submissions/16598122
__slots__ = ["n", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"]
def __init__(self, monoid_data, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator,
func_operator_operator):
self.me = monoid_identity
self.oe = operator_identity
self.fmm = func_monoid_monoid
self.fmo = func_monoid_operator
self.foo = func_operator_operator
self.n = len(monoid_data)
self.data = monoid_data*2
for i in range(self.n-1, 0, -1):
self.data[i] = self.fmm(self.data[2*i], self.data[2*i+1])
self.lazy = [self.oe]*(self.n*2)
def replace(self, index, value):
index += self.n
# propagation
for shift in range(index.bit_length()-1, 0, -1):
i = index>>shift
self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i])
self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i])
self.data[i] = self.fmo(self.data[i], self.lazy[i])
self.lazy[i] = self.oe
# update
self.data[index] = value
self.lazy[index] = self.oe
# recalculation
i = index
while i > 1:
i //= 2
self.data[i] = self.fmm(self.fmo(self.data[2*i], self.lazy[2*i]),
self.fmo(self.data[2*i+1], self.lazy[2*i+1]))
self.lazy[i] = self.oe
def effect(self, l, r, operator):
l += self.n
r += self.n
# preparing indices
indices = []
l0 = (l//(l&-l)) >> 1
r0 = (r//(r&-r)-1) >> 1
while r0 > l0:
indices.append(r0)
r0 >>= 1
while l0 > r0:
indices.append(l0)
l0 >>= 1
while l0 and l0 != r0:
indices.append(r0)
r0 >>= 1
if l0 == r0:
break
indices.append(l0)
l0 >>= 1
while r0:
indices.append(r0)
r0 >>= 1
# propagation
for i in reversed(indices):
self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i])
self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i])
self.data[i] = self.fmo(self.data[i], self.lazy[i])
self.lazy[i] = self.oe
# effect
while l < r:
if l&1:
self.lazy[l] = self.foo(self.lazy[l], operator)
l += 1
if r&1:
r -= 1
self.lazy[r] = self.foo(self.lazy[r], operator)
l >>= 1
r >>= 1
# recalculation
for i in indices:
self.data[i] = self.fmm(self.fmo(self.data[2*i], self.lazy[2*i]),
self.fmo(self.data[2*i+1], self.lazy[2*i+1]))
self.lazy[i] = self.oe
def folded(self, l, r):
l += self.n
r += self.n
# preparing indices
indices = []
l0 = (l//(l&-l))//2
r0 = (r//(r&-r)-1)//2
while r0 > l0:
indices.append(r0)
r0 >>= 1
while l0 > r0:
indices.append(l0)
l0 >>= 1
while l0 and l0 != r0:
indices.append(r0)
r0 >>= 1
if l0 == r0:
break
indices.append(l0)
l0 >>= 1
while r0:
indices.append(r0)
r0 >>= 1
# propagation
for i in reversed(indices):
self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i])
self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i])
self.data[i] = self.fmo(self.data[i], self.lazy[i])
self.lazy[i] = self.oe
# fold
left_folded = self.me
right_folded = self.me
while l < r:
if l&1:
left_folded = self.fmm(left_folded, self.fmo(self.data[l], self.lazy[l]))
l += 1
if r&1:
r -= 1
right_folded = self.fmm(self.fmo(self.data[r], self.lazy[r]), right_folded)
l >>= 1
r >>= 1
return self.fmm(left_folded, right_folded)
class ModInt:
def __init__(self, x):
self.x = x.x if isinstance(x, ModInt) else x % MOD
__str__ = lambda self:str(self.x)
__repr__ = __str__
__int__ = lambda self: self.x
__index__ = __int__
__add__ = lambda self, other: ModInt(self.x + ModInt(other).x)
__sub__ = lambda self, other: ModInt(self.x - ModInt(other).x)
__mul__ = lambda self, other: ModInt(self.x * ModInt(other).x)
__pow__ = lambda self, other: ModInt(pow(self.x, ModInt(other).x, MOD))
__truediv__ = lambda self, other: ModInt(self.x * pow(ModInt(other).x, MOD - 2, MOD))
__floordiv__ = lambda self, other: ModInt(self.x // ModInt(other).x)
__radd__ = lambda self, other: ModInt(other + self.x)
__rsub__ = lambda self, other: ModInt(other - self.x)
__rpow__ = lambda self, other: ModInt(pow(other, self.x, MOD))
__rmul__ = lambda self, other: ModInt(other * self.x)
__rtruediv__ = lambda self, other: ModInt(other * pow(self.x, MOD - 2, MOD))
__rfloordiv__ = lambda self, other: ModInt(other // self.x)
__lt__ = lambda self, other: self.x < ModInt(other).x
__gt__ = lambda self, other: self.x > ModInt(other).x
__le__ = lambda self, other: self.x <= ModInt(other).x
__ge__ = lambda self, other: self.x >= ModInt(other).x
__eq__ = lambda self, other: self.x == ModInt(other).x
__ne__ = lambda self, other: self.x != ModInt(other).x
def main():
import sys
sys.setrecursionlimit(311111)
# import numpy as np
ikimasu = sys.stdin.buffer.readline
ini = lambda: int(ins())
ina = lambda: list(map(int, ikimasu().split()))
ins = lambda: ikimasu().strip()
n,q = ina()
tmp = [(1,1) for i in range(0,n)]
tmpx = 1
tmpx1 = 1
ten = []
one = []
for i in range(311111):
ten.append(tmpx)
one.append(tmpx1)
tmpx1*=10
tmpx1+=1
tmpx*=10
tmpx1%=MOD
tmpx%=MOD
# print(ten)
def op(x1,x2):
val1,size1 = x1
val2,size2 = x2
size = size1+size2
val = (val1*ten[size2])+val2
return val%MOD,size
e = (0,0)
def maptmp(s,f):
if(f == -1):
return s
else:
return f*one[s[1]-1]%MOD,s[1]
def comp(g,f):
return f if f!=-1 else g
ident = -1
tmptree = LazySegmentTree(tmp,e,ident,op,maptmp,comp)
for _ in range(q):
l,r,x = ina()
tmptree.effect(l-1,r,x)
print(tmptree.folded(0,n)[0])
if __name__ == "__main__":
main()
```
| 43,546 | [
0.201904296875,
-0.33984375,
-0.192626953125,
0.0931396484375,
-0.451171875,
-0.267333984375,
0.18017578125,
-0.0017843246459960938,
0.354248046875,
0.55322265625,
0.58056640625,
-0.050201416015625,
-0.053375244140625,
-0.74658203125,
-0.646484375,
-0.1263427734375,
-0.33935546875,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
"Correct Solution:
```
class LazySegmentTree():
def __init__(self, n, f, g, h, ef, eh):
"""
:param n: 配列の要素数
:param f: 取得半群の元同士の積を定義
:param g: 更新半群の元 xh が配列上の実際の値にどのように作用するかを定義
:param h: 更新半群の元同士の積を定義 (更新半群の元を xh と表記)
:param x: 配列の各要素の値。treeの葉以外は xf(x1,x2,...)
"""
self.n = n
self.f = f
self.g = lambda xh, x: g(xh, x) if xh != eh else x
self.h = h
self.ef = ef
self.eh = eh
l = (self.n - 1).bit_length()
self.size = 1 << l
self.tree = [self.ef] * (self.size << 1)
self.lazy = [self.eh] * ((self.size << 1) + 1)
self.plt_cnt = 0
def built(self, array):
"""
arrayを初期値とするセグメント木を構築
"""
for i in range(self.n):
self.tree[self.size + i] = array[i]
for i in range(self.size - 1, 0, -1):
self.tree[i] = self.f(self.tree[i<<1], self.tree[(i<<1)|1])
def update(self, i, x):
"""
i 番目の要素を x に更新する
"""
i += self.size
self.propagate_lazy(i)
self.tree[i] = x
self.lazy[i] = self.eh
self.propagate_tree(i)
def get(self, i):
"""
i 番目の値を取得( 0-indexed ) ( O(logN) )
"""
i += self.size
self.propagate_lazy(i)
return self.g(self.lazy[i], self.tree[i])
def update_range(self, l, r, x):
"""
半開区間 [l, r) の各々の要素 a に op(x, a)を作用させる ( 0-indexed ) ( O(logN) )
"""
if l >= r:
return
l += self.size
r += self.size
l0 = l//(l&-l)
r0 = r//(r&-r)
self.propagate_lazy(l0)
self.propagate_lazy(r0-1)
while l < r:
if r&1:
r -= 1 # 半開区間なので先に引いてる
self.lazy[r] = self.h(x, self.lazy[r])
if l&1:
self.lazy[l] = self.h(x, self.lazy[l])
l += 1
l >>= 1
r >>= 1
self.propagate_tree(l0)
self.propagate_tree(r0-1)
def get_range(self, l, r):
"""
[l, r)への作用の結果を返す (0-indexed)
"""
l += self.size
r += self.size
self.propagate_lazy(l//(l&-l))
self.propagate_lazy((r//(r&-r))-1)
res_l = self.ef
res_r = self.ef
while l < r:
if l & 1:
res_l = self.f(res_l, self.g(self.lazy[l], self.tree[l]))
l += 1
if r & 1:
r -= 1
res_r = self.f(self.g(self.lazy[r], self.tree[r]), res_r)
l >>= 1
r >>= 1
return self.f(res_l, res_r)
def max_right(self, l, z):
"""
以下の条件を両方満たす r を(いずれか一つ)返す
・r = l or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
・r = n or f(op(a[l], a[l + 1], ..., a[r])) = false
"""
if l >= self.n: return self.n
l += self.size
s = self.ef
while 1:
while l % 2 == 0:
l >>= 1
if not z(self.f(s, self.g(self.lazy[l], self.tree[l]))):
while l < self.size:
l *= 2
if z(self.f(s, self.g(self.lazy[l], self.tree[l]))):
s = self.f(s, self.g(self.lazy[l], self.tree[l]))
l += 1
return l - self.size
s = self.f(s, self.g(self.lazy[l], self.tree[l]))
l += 1
if l & -l == l: break
return self.n
def min_left(self, r, z):
"""
以下の条件を両方満たす l を(いずれか一つ)返す
・l = r or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
・l = 0 or f(op(a[l - 1], a[l], ..., a[r - 1])) = false
"""
if r <= 0: return 0
r += self.size
s = self.ef
while 1:
r -= 1
while r > 1 and r % 2:
r >>= 1
if not z(self.f(self.g(self.lazy[r], self.tree[r]), s)):
while r < self.size:
r = r * 2 + 1
if z(self.f(self.g(self.lazy[r], self.tree[r]), s)):
s = self.f(self.g(self.lazy[r], self.tree[r]), s)
r -= 1
return r + 1 - self.size
s = self.f(self.g(self.lazy[r], self.tree[r]), s)
if r & -r == r: break
return 0
def propagate_lazy(self, i):
"""
lazy の値をトップダウンで更新する ( O(logN) )
"""
for k in range(i.bit_length()-1,0,-1):
x = i>>k
if self.lazy[x] == self.eh:
continue
laz = self.lazy[x]
self.lazy[(x<<1)|1] = self.h(laz, self.lazy[(x<<1)|1])
self.lazy[x<<1] = self.h(laz, self.lazy[x<<1])
self.tree[x] = self.g(laz, self.tree[x]) # get_range ではボトムアップの伝搬を行わないため、この処理をしないと tree が更新されない
self.lazy[x] = self.eh
def propagate_tree(self, i):
"""
tree の値をボトムアップで更新する ( O(logN) )
"""
while i>1:
i>>=1
self.tree[i] = self.f(self.g(self.lazy[i<<1], self.tree[i<<1]), self.g(self.lazy[(i<<1)|1], self.tree[(i<<1)|1]))
def __getitem__(self, i):
return self.get(i)
def __iter__(self):
for x in range(1, self.size):
if self.lazy[x] == self.eh:
continue
self.lazy[(x<<1)|1] = self.h(self.lazy[x], self.lazy[(x<<1)|1])
self.lazy[x<<1] = self.h(self.lazy[x], self.lazy[x<<1])
self.tree[x] = self.g(self.lazy[x], self.tree[x])
self.lazy[x] = self.eh
for xh, x in zip(self.lazy[self.size:self.size+self.n], self.tree[self.size:self.size+self.n]):
yield self.g(xh,x)
def __str__(self):
return str(list(self))
#########################################################################################################
from itertools import accumulate
import sys
input = sys.stdin.readline
MOD = 998244353
off = 22
mask = 1<<22
N, Q = map(int, input().split())
P = [pow(10,p,MOD) for p in range(N+1)]
SP = [0]
for p in P:
SP.append((SP[-1]+p)%MOD)
# クエリ関数
ef = 0
def f(x, y):
x0, x1 = divmod(x,1<<off)
y0, y1 = divmod(y,1<<off)
res = x0*P[y1]+y0
res %= MOD
return (res<<off) + x1+y1
# merge関数
eh = -1
def h(a,b):
return a if a != eh else b
# 更新関数(g が局所的か要確認
def g(a, x):
x1 = x%mask
return a*(SP[x1]<<off) + x1
st = LazySegmentTree(N, f, g, h, ef, eh)
st.built([(1<<off) + 1]*N)
res = [""]*Q
for i in range(Q):
L, R, D = map(int, input().split())
st.update_range(L-1, R, D)
res[i] = str((st.get_range(0,N)>>off)%MOD)
print("\n".join(res))
```
| 43,547 | [
0.1494140625,
-0.1224365234375,
0.0123291015625,
0.1513671875,
-0.4853515625,
-0.1728515625,
0.248291015625,
-0.0239410400390625,
0.427978515625,
0.68994140625,
0.654296875,
-0.31640625,
0.08746337890625,
-0.6767578125,
-0.6123046875,
0.2015380859375,
-0.6376953125,
-0.720703125,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
"Correct Solution:
```
import sys
input = sys.stdin.readline
class LazySegmentTree():
def __init__(self, n, op, e, mapping, composition, id):
self.n = n
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.id = id
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.d = [e] * (2 * self.size)
self.lz = [id] * (self.size)
def update(self, k):
self.d[k] = self.op(self.d[2 * k], self.d[2 * k + 1])
def all_apply(self, k, f):
self.d[k] = self.mapping(f, self.d[k])
if k < self.size:
self.lz[k] = self.composition(f, self.lz[k])
def push(self, k):
self.all_apply(2 * k, self.lz[k])
self.all_apply(2 * k + 1, self.lz[k])
self.lz[k] = self.id
def build(self, arr):
#assert len(arr) == self.n
for i, a in enumerate(arr):
self.d[self.size + i] = a
for i in range(1, self.size)[::-1]:
self.update(i)
def set(self, p, x):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(p >> i)
self.d[p] = x
for i in range(1, self.log + 1):
self.update(p >> i)
def get(self, p):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1):
self.push(p >> i)
return self.d[p]
def prod(self, l, r):
#assert 0 <= l <= r <= self.n
if l == r: return self.e
l += self.size
r += self.size
for i in range(1, self.log + 1)[::-1]:
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push(r >> i)
sml = smr = self.e
while l < r:
if l & 1:
sml = self.op(sml, self.d[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.d[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.d[1]
def apply(self, p, f):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(p >> i)
self.d[p] = self.mapping(f, self.d[p])
for i in range(1, self.log + 1):
self.update(p >> i)
def range_apply(self, l, r, f):
#assert 0 <= l <= r <= self.n
if l == r: return
l += self.size
r += self.size
for i in range(1, self.log + 1)[::-1]:
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
self.all_apply(l, f)
l += 1
if r & 1:
r -= 1
self.all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.update(l >> i)
if ((r >> i) << i) != r: self.update((r - 1) >> i)
def max_right(self, l, g):
#assert 0 <= l <= self.n
#assert g(self.e)
if l == self.n: return self.n
l += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(l >> i)
sm = self.e
while True:
while l % 2 == 0: l >>= 1
if not g(self.op(sm, self.d[l])):
while l < self.size:
self.push(l)
l = 2 * l
if g(self.op(sm, self.d[l])):
sm = self.op(sm, self.d[l])
l += 1
return l - self.size
sm = self.op(sm, self.d[l])
l += 1
if (l & -l) == l: return self.n
def min_left(self, r, g):
#assert 0 <= r <= self.n
#assert g(self.e)
if r == 0: return 0
r += self.size
for i in range(1, self.log + 1)[::-1]:
self.push((r - 1) >> i)
sm = self.e
while True:
r -= 1
while r > 1 and r % 2: r >>= 1
if not g(self.op(self.d[r], sm)):
while r < self.size:
self.push(r)
r = 2 * r + 1
if g(self.op(self.d[r], sm)):
sm = self.op(self.d[r], sm)
r -= 1
return r + 1 - self.size
sm = self.op(self.d[r], sm)
if (r & -r) == r: return 0
mod = 998244353
def op(x, y):
xv, xr = divmod(x,1<<31)
yv, yr = divmod(y,1<<31)
return ((xv + yv)%mod << 31) + (xr + yr)%mod
def mapping(p, x):
xv, xr = divmod(x,1<<31)
if p != -1:
return ((p*xr%mod) << 31) + xr
else:
return x
composition = lambda p,q : q if p == -1 else p
n,q = map(int,input().split())
res = [0]*n
LST = LazySegmentTree(n,op,0,mapping,composition,-1)
v = 0
ten = 1
for i in range(n):
res[i] = (ten<<31) + ten
ten = ten*10%mod
#print(res)
LST.build(res[::-1])
#print(LST.all_prod()>>31)
for _ in range(q):
l,r,D = map(int,input().split())
LST.range_apply(l-1,r,D)
print((LST.all_prod()>>31)%mod)
```
| 43,548 | [
0.1705322265625,
-0.076171875,
-0.0011911392211914062,
0.0872802734375,
-0.6376953125,
-0.162109375,
0.049102783203125,
-0.04388427734375,
0.43505859375,
0.712890625,
0.56689453125,
-0.2125244140625,
0.195556640625,
-0.72119140625,
-0.56298828125,
0.2403564453125,
-0.6396484375,
-0... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
"Correct Solution:
```
class LazySegmentTree():
def __init__(self, array, f, g, h, ti, ei):
self.f = f
self.g = g
self.h = h
self.ti = ti
self.ei = ei
self.height = height = len(array).bit_length()
self.n = n = 2**height
self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
self.laz = [ei] * (2 * n)
for i in range(n - 1, 0, -1): # build
dat[i] = f(dat[i << 1], dat[i << 1 | 1])
def reflect(self, k):
# 遅延配列の値から真のノードの値を求める
dat = self.dat
ei = self.ei
laz = self.laz
g = self.g
return self.dat[k] if laz[k] is ei else g(dat[k], laz[k])
def evaluate(self, k):
# 遅延配列を子ノードに伝播させる
laz = self.laz
ei = self.ei
reflect = self.reflect
dat = self.dat
h = self.h
if laz[k] is ei:
return
laz[(k << 1) | 0] = h(laz[(k << 1) | 0], laz[k])
laz[(k << 1) | 1] = h(laz[(k << 1) | 1], laz[k])
dat[k] = reflect(k)
laz[k] = ei
def thrust(self, k):
height = self.height
evaluate = self.evaluate
for i in range(height, 0, -1):
evaluate(k >> i)
def recalc(self, k):
dat = self.dat
reflect = self.reflect
f = self.f
while k:
k >>= 1
dat[k] = f(reflect((k << 1) | 0), reflect((k << 1) | 1))
def update(self, a, b, x):
# 半開区間[a,b)の遅延配列の値をxに書き換える
thrust = self.thrust
n = self.n
h = self.h
laz = self.laz
recalc = self.recalc
a += n
b += n - 1
l = a
r = b + 1
thrust(a)
thrust(b)
while l < r:
if l & 1:
laz[l] = h(laz[l], x)
l += 1
if r & 1:
r -= 1
laz[r] = h(laz[r], x)
l >>= 1
r >>= 1
recalc(a)
recalc(b)
def set_val(self, a, x):
# aの値を変更する
n = self.n
thrust = self.thrust
dat = self.dat
laz = self.laz
recalc = self.recalc
ei = self.ei
a += n
thrust(a)
dat[a] = x
laz[a] = ei
recalc(a)
def query(self, a, b):
# 半開区間[a,b)に対するクエリに答える
f = self.f
ti = self.ti
n = self.n
thrust = self.thrust
reflect = self.reflect
a += n
b += n - 1
thrust(a)
thrust(b)
l = a
r = b + 1
vl = vr = ti
while l < r:
if l & 1:
vl = f(vl, reflect(l))
l += 1
if r & 1:
r -= 1
vr = f(reflect(r), vr)
l >>= 1
r >>= 1
return f(vl, vr)
def pow_k(x,n,p=10**9+7):
if n==0:
return 1
K=1
while n>1:
if n%2!=0:
K=(K*x)%p
x=(x*x)%p
n//=2
return (K*x)%p
import sys
input = sys.stdin.readline
MI=lambda:map(int,input().split())
N,Q=MI()
H=10**9+7
mod=998244353
tenmod=[pow_k(10,i,mod) for i in range(N+1)]
inv9=pow_k(9,mod-2,mod)
def f(a, b):
an,ah=divmod(a,H)
bn,bh=divmod(b,H)
return ((an*tenmod[bh]+bn)%mod)*H + ah+bh
def g(a, b):
ah=a%H
return (((tenmod[ah]-1)*inv9)%mod*b)*H + ah
h = lambda a, b: b
ti = 0
ei = 0
lst=LazySegmentTree([1*H+1]*N,f=f,g=g,h=h,ti=ti,ei=ei)
for _ in [0]*Q:
l,r,d=MI()
lst.update(l-1,r,d)
print(lst.query(0,N)//H)
```
| 43,549 | [
0.076904296875,
-0.03411865234375,
0.19384765625,
0.0189208984375,
-0.53466796875,
-0.419921875,
0.270263671875,
0.0019330978393554688,
0.476318359375,
0.77197265625,
0.3330078125,
-0.251708984375,
0.166259765625,
-0.7373046875,
-0.65283203125,
0.10540771484375,
-0.497802734375,
-0... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
"Correct Solution:
```
class LazySegmentTree():
__slots__ = ["merge","merge_unit","operate","merge_operate","operate_unit","n","data","lazy"]
def __init__(self,n,init,merge,merge_unit,operate,merge_operate,operate_unit):
self.merge=merge
self.merge_unit=merge_unit
self.operate=operate
self.merge_operate=merge_operate
self.operate_unit=operate_unit
self.n=(n-1).bit_length()
self.data=[merge_unit for i in range(1<<(self.n+1))]
self.lazy=[operate_unit for i in range(1<<(self.n+1))]
if init:
for i in range(n):
self.data[2**self.n+i]=init[i]
for i in range(2**self.n-1,0,-1):
self.data[i]=self.merge(self.data[2*i],self.data[2*i+1])
def propagate(self,v):
ope = self.lazy[v]
if ope == self.operate_unit:
return
self.lazy[v]=self.operate_unit
self.data[(v<<1)]=self.operate(self.data[(v<<1)],ope)
self.data[(v<<1)+1]=self.operate(self.data[(v<<1)+1],ope)
self.lazy[v<<1]=self.merge_operate(self.lazy[(v<<1)],ope)
self.lazy[(v<<1)+1]=self.merge_operate(self.lazy[(v<<1)+1],ope)
def propagate_above(self,i):
m=i.bit_length()-1
for bit in range(m,0,-1):
v=i>>bit
self.propagate(v)
def remerge_above(self,i):
while i:
c = self.merge(self.data[i],self.data[i^1])
i>>=1
self.data[i]=self.operate(c,self.lazy[i])
def update(self,l,r,x):
l+=1<<self.n
r+=1<<self.n
l0=l//(l&-l)
r0=r//(r&-r)-1
self.propagate_above(l0)
self.propagate_above(r0)
while l<r:
if l&1:
self.data[l]=self.operate(self.data[l],x)
self.lazy[l]=self.merge_operate(self.lazy[l],x)
l+=1
if r&1:
self.data[r-1]=self.operate(self.data[r-1],x)
self.lazy[r-1]=self.merge_operate(self.lazy[r-1],x)
l>>=1
r>>=1
self.remerge_above(l0)
self.remerge_above(r0)
def query(self,l,r):
l+=1<<self.n
r+=1<<self.n
l0=l//(l&-l)
r0=r//(r&-r)-1
self.propagate_above(l0)
self.propagate_above(r0)
res=self.merge_unit
while l<r:
if l&1:
res=self.merge(res,self.data[l])
l+=1
if r&1:
res=self.merge(res,self.data[r-1])
l>>=1
r>>=1
return res
def bisect_l(self,l,r,x):
l += 1<<self.n
r += 1<<self.n
l0=l//(l&-l)
r0=r//(r&-r)-1
self.propagate_above(l0)
self.propagate_above(r0)
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.data[l][0] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.data[r-1][0] <=x:
Rmin = r-1
l >>= 1
r >>= 1
res = -1
if Lmin != -1:
pos = Lmin
while pos<self.num:
self.propagate(pos)
if self.data[2 * pos][0] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
res = pos-self.num
if Rmin != -1:
pos = Rmin
while pos<self.num:
self.propagate(pos)
if self.data[2 * pos][0] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
if res==-1:
res = pos-self.num
else:
res = min(res,pos-self.num)
return res
mod = 998244353
mask = (2**32)-1
def merge(x,y):
val_x,base_x = x>>32,x&mask
val_y,base_y = y>>32,y&mask
res_val = (val_x+val_y) % mod
res_base = (base_x+base_y) % mod
res = (res_val<<32) + res_base
return res
merge_unit = 0
def operate(x,y):
if y==0:
return x
val,base = x>>32,x&mask
val = (base*y) % mod
x = (val<<32)+base
return x
def merge_operate(x,y):
return y
operate_unit = 0
import sys
input = sys.stdin.readline
N,Q = map(int,input().split())
init = [(pow(10,N-1-i,mod)<<32)+pow(10,N-1-i,mod) for i in range(N)]
LST = LazySegmentTree(N,init,merge,merge_unit,operate,merge_operate,operate_unit)
for i in range(Q):
l,r,d = map(int,input().split())
LST.update(l-1,r,d)
print(LST.query(0,N)>>32)
```
| 43,550 | [
0.0694580078125,
-0.39404296875,
0.0906982421875,
0.22119140625,
-0.6943359375,
-0.251708984375,
0.37060546875,
-0.1507568359375,
0.50732421875,
0.7041015625,
0.5,
-0.1312255859375,
0.05572509765625,
-0.78857421875,
-0.69189453125,
0.00525665283203125,
-0.50732421875,
-0.7309570312... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
"Correct Solution:
```
import sys
input = sys.stdin.readline
N,Q = map(int,input().split())
LRD = [tuple(map(int,input().split())) for i in range(Q)]
MOD = 998244353
class LazySegTree:
def __init__(self, op, e, mapping, composition, _id, arr=[]):
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.id = _id
self.n = len(arr)
self.log = self._ceil_pow2(self.n)
self.size = 1 << self.log
self.d = [e()] * (2*self.size)
self.lz = [_id()] * self.size
for i in range(self.n):
self.d[self.size + i] = arr[i]
for i in range(self.size-1, 0, -1):
self._update(i)
def _ceil_pow2(self, n):
assert n >= 0
x = 0
while (1<<x) < n:
x += 1
return x
def set(self, p, x):
assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self._push(p >> i)
self.d[p] = x
for i in range(1, self.log+1):
self._update(p >> i)
def get(self, p):
assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self._push(p >> i)
return self.d[p]
def prod(self, l, r):
assert 0 <= l <= r <= self.n
if l==r: return self.e()
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self._push(l >> i)
if ((r >> i) << i) != r: self._push(r >> i)
sml = smr = self.e()
while l < r:
if l&1:
sml = self.op(sml, self.d[l])
l += 1
if r&1:
r -= 1
smr = self.op(self.d[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.d[1]
def apply(self, p, f):
assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self._push(p >> i)
self.d[p] = self.mapping(f, self.d[p])
for i in range(1, self.log+1):
self._update(p >> i)
def apply_lr(self, l, r, f):
assert 0 <= l <= r <= self.n
if l==r: return
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self._push(l >> i)
if ((r >> i) << i) != r: self._push((r-1) >> i)
l2,r2 = l,r
while l < r:
if l&1:
self._all_apply(l, f)
l += 1
if r&1:
r -= 1
self._all_apply(r, f)
l >>= 1
r >>= 1
l,r = l2,r2
for i in range(1, self.log+1):
if ((l >> i) << i) != l: self._update(l >> i)
if ((r >> i) << i) != r: self._update((r-1) >> i)
def _update(self, k):
self.d[k] = self.op(self.d[2*k], self.d[2*k+1])
def _all_apply(self, k, f):
self.d[k] = self.mapping(f, self.d[k])
if k < self.size:
self.lz[k] = self.composition(f, self.lz[k])
def _push(self, k):
self._all_apply(2*k, self.lz[k])
self._all_apply(2*k+1, self.lz[k])
self.lz[k] = self.id()
inv9 = pow(9,MOD-2,MOD)
def op(l,r):
lx,lw = l
rx,rw = r
return ((lx*rw + rx)%MOD, (lw*rw)%MOD)
def e():
return (0,1)
def mapping(l,r):
if l==0: return r
rx,rw = r
return (((rw-1)*inv9*l)%MOD, rw)
def composition(l,r):
return r if l==0 else l
def _id():
return 0
segt = LazySegTree(op, e, mapping, composition, _id, [(1,10) for i in range(N)])
ans = []
for l,r,d in LRD:
l -= 1
segt.apply_lr(l,r,d)
ans.append(segt.all_prod()[0])
print(*ans, sep='\n')
```
| 43,551 | [
0.2391357421875,
-0.08111572265625,
0.03948974609375,
0.07244873046875,
-0.73291015625,
-0.1063232421875,
0.07476806640625,
-0.0919189453125,
0.418701171875,
0.8408203125,
0.59033203125,
-0.16357421875,
0.2073974609375,
-0.78076171875,
-0.5361328125,
0.1669921875,
-0.5751953125,
-0... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
Submitted Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 998244353
def set_depth(depth):
global DEPTH, SEGTREE_SIZE, NONLEAF_SIZE
DEPTH = depth
SEGTREE_SIZE = 1 << DEPTH
NONLEAF_SIZE = 1 << (DEPTH - 1)
def set_width(width):
set_depth((width - 1).bit_length() + 1)
def get_size(pos):
ret = pos.bit_length()
return (1 << (DEPTH - ret))
def up(pos):
pos += SEGTREE_SIZE // 2
return pos // (pos & -pos)
def up_propagate(table, pos, binop):
while pos > 1:
pos >>= 1
size = get_size(pos) // 2
table[pos] = binop(
table[pos * 2],
table[pos * 2 + 1],
size
)
def full_up(table, binop):
for pos in range(NONLEAF_SIZE - 1, 0, -1):
size = get_size(pos) // 2
table[pos] = binop(
table[2 * pos],
table[2 * pos + 1],
size)
def force_down_propagate(
action_table, value_table, pos,
action_composite, action_force, action_unity
):
max_level = pos.bit_length() - 1
size = NONLEAF_SIZE
for level in range(max_level):
size //= 2
i = pos >> (max_level - level)
action = action_table[i]
if action != action_unity:
action_table[i * 2] = action_composite(
action, action_table[i * 2])
action_table[i * 2 + 1] = action_composite(
action, action_table[i * 2 + 1])
# old_action = action_table[i * 2]
# if old_action == action_unity:
# action_table[i * 2] = action
# else:
# b1, c1 = old_action
# b2, c2 = action
# action_table[i * 2] = (b1 * b2, b2 * c1 + c2)
# old_action = action_table[i * 2 + 1]
# if old_action == action_unity:
# action_table[i * 2 + 1] = action
# else:
# b1, c1 = old_action
# b2, c2 = action
# action_table[i * 2 + 1] = (b1 * b2, b2 * c1 + c2)
action_table[i] = action_unity
value_table[i * 2] = action_force(
action, value_table[i * 2], size)
value_table[i * 2 + 1] = action_force(
action, value_table[i * 2 + 1], size)
# b, c = action
# value = value_table[i * 2]
# value_table[i * 2] = (value * b + c * size) % MOD
# value = value_table[i * 2 + 1]
# value_table[i * 2 + 1] = (value * b + c * size) % MOD
def force_range_update(
value_table, action_table, left, right,
action, action_force, action_composite, action_unity
):
"""
action_force: action, value, cell_size => new_value
action_composite: new_action, old_action => composite_action
"""
left += NONLEAF_SIZE
right += NONLEAF_SIZE
while left < right:
if left & 1:
value_table[left] = action_force(
action, value_table[left], get_size(left))
action_table[left] = action_composite(action, action_table[left])
left += 1
if right & 1:
right -= 1
value_table[right] = action_force(
action, value_table[right], get_size(right))
action_table[right] = action_composite(action, action_table[right])
left //= 2
right //= 2
def range_reduce(table, left, right, binop, unity):
ret_left = unity
ret_right = unity
left += NONLEAF_SIZE
right += NONLEAF_SIZE
right_size = 0
while left < right:
if left & 1:
size = get_size(left)
ret_left = binop(ret_left, table[left], size)
# debug("size, ret_left", size, ret_left)
left += 1
if right & 1:
right -= 1
ret_right = binop(table[right], ret_right, right_size)
right_size += get_size(right)
# debug("right_size, ret_right", right_size, ret_right)
left //= 2
right //= 2
return binop(ret_left, ret_right, right_size)
def lazy_range_update(
action_table, value_table, start, end,
action, action_composite, action_force, action_unity, value_binop):
"update [start, end)"
L = up(start)
R = up(end)
force_down_propagate(
action_table, value_table, L,
action_composite, action_force, action_unity)
force_down_propagate(
action_table, value_table, R,
action_composite, action_force, action_unity)
force_range_update(
value_table, action_table, start, end,
action, action_force, action_composite, action_unity)
up_propagate(value_table, L, value_binop)
up_propagate(value_table, R, value_binop)
def lazy_range_reduce(
action_table, value_table, start, end,
action_composite, action_force, action_unity,
value_binop, value_unity
):
"reduce [start, end)"
force_down_propagate(
action_table, value_table, up(start),
action_composite, action_force, action_unity)
force_down_propagate(
action_table, value_table, up(end),
action_composite, action_force, action_unity)
return range_reduce(value_table, start, end, value_binop, value_unity)
def debug(*x):
print(*x, file=sys.stderr)
def main():
# parse input
N, Q = map(int, input().split())
set_width(N + 1)
value_unity = 0
value_table = [value_unity] * SEGTREE_SIZE
value_table[NONLEAF_SIZE:NONLEAF_SIZE + N] = [1] * N
action_unity = None
action_table = [action_unity] * SEGTREE_SIZE
cache11 = {}
i = 1
p = 1
step = 10
while i <= N:
cache11[i] = p
p = (p * step + p) % MOD
step = (step * step) % MOD
i *= 2
cache10 = {0: 1}
i = 1
p = 10
while i <= N:
cache10[i] = p
p = (p * 10) % MOD
i += 1
def action_force(action, value, size):
if action == action_unity:
return value
# return int(str(action) * size)
return (cache11[size] * action) % MOD
def action_composite(new_action, old_action):
if new_action == action_unity:
return old_action
return new_action
def value_binop(a, b, size):
# debug("a, b, size", a, b, size)
# return (a * (10 ** size) + b) % MOD
return (a * cache10[size] + b) % MOD
full_up(value_table, value_binop)
ret = lazy_range_reduce(
action_table, value_table, 0, N, action_composite, action_force, action_unity,
value_binop, value_unity)
for _q in range(Q):
l, r, d = map(int, input().split())
lazy_range_update(
action_table, value_table, l - 1, r, d,
action_composite, action_force, action_unity, value_binop)
ret = lazy_range_reduce(
action_table, value_table, 0, N, action_composite, action_force, action_unity,
value_binop, value_unity)
print(ret)
# tests
T1 = """
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
11222211
77772211
77333333
72333333
72311333
"""
T2 = """
200000 1
123 456 7
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
641437905
"""
T3 = """
4 4
1 1 2
1 2 3
1 3 4
1 4 5
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
2111
3311
4441
5555
"""
T4 = """
4 4
4 4 2
3 4 3
2 4 4
1 4 5
1112
1133
1444
5555
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
1112
1133
1444
5555
"""
T5 = """
9 3
1 9 1
1 9 5
1 9 9
"""
TEST_T5 = """
>>> as_input(T5)
>>> main()
111111111
555555555
1755646
"""
def _test():
import doctest
doctest.testmod()
g = globals()
for k in sorted(g):
if k.startswith("TEST_"):
doctest.run_docstring_examples(g[k], g, name=k)
def as_input(s):
"use in test, use given string as input file"
import io
f = io.StringIO(s.strip())
g = globals()
g["input"] = lambda: bytes(f.readline(), "ascii")
g["read"] = lambda: bytes(f.read(), "ascii")
input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
if sys.argv[-1] == "-t":
print("testing")
_test()
sys.exit()
main()
```
Yes
| 43,552 | [
0.51123046875,
-0.2176513671875,
0.09893798828125,
-0.1251220703125,
-0.64013671875,
-0.0282745361328125,
0.341552734375,
0.133056640625,
0.347900390625,
0.77099609375,
0.517578125,
-0.197265625,
-0.032684326171875,
-0.64599609375,
-0.408935546875,
0.521484375,
-0.26171875,
-0.6455... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
Submitted Solution:
```
class LazySegmentTree():
def __init__(self, n, op, e, mapping, composition, id):
self.n = n
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.id = id
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.d = [e] * (2 * self.size)
self.lz = [id] * (self.size)
def update(self, k):
self.d[k] = self.op(self.d[2 * k], self.d[2 * k + 1])
def all_apply(self, k, f):
self.d[k] = self.mapping(f, self.d[k])
if k < self.size:
self.lz[k] = self.composition(f, self.lz[k])
def push(self, k):
self.all_apply(2 * k, self.lz[k])
self.all_apply(2 * k + 1, self.lz[k])
self.lz[k] = self.id
def build(self, arr):
#assert len(arr) == self.n
for i, a in enumerate(arr):
self.d[self.size + i] = a
for i in range(1, self.size)[::-1]:
self.update(i)
def set(self, p, x):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(p >> i)
self.d[p] = x
for i in range(1, self.log + 1):
self.update(p >> i)
def get(self, p):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1):
self.push(p >> i)
return self.d[p]
def prod(self, l, r):
#assert 0 <= l <= r <= self.n
if l == r: return self.e
l += self.size
r += self.size
for i in range(1, self.log + 1)[::-1]:
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push(r >> i)
sml = smr = self.e
while l < r:
if l & 1:
sml = self.op(sml, self.d[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.d[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.d[1]
def apply(self, p, f):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(p >> i)
self.d[p] = self.mapping(f, self.d[p])
for i in range(1, self.log + 1):
self.update(p >> i)
def range_apply(self, l, r, f):
#assert 0 <= l <= r <= self.n
if l == r: return
l += self.size
r += self.size
for i in range(1, self.log + 1)[::-1]:
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
self.all_apply(l, f)
l += 1
if r & 1:
r -= 1
self.all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.update(l >> i)
if ((r >> i) << i) != r: self.update((r - 1) >> i)
def max_right(self, l, g):
#assert 0 <= l <= self.n
#assert g(self.e)
if l == self.n: return self.n
l += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(l >> i)
sm = self.e
while True:
while l % 2 == 0: l >>= 1
if not g(self.op(sm, self.d[l])):
while l < self.size:
self.push(l)
l = 2 * l
if g(self.op(sm, self.d[l])):
sm = self.op(sm, self.d[l])
l += 1
return l - self.size
sm = self.op(sm, self.d[l])
l += 1
if (l & -l) == l: return self.n
def min_left(self, r, g):
#assert 0 <= r <= self.n
#assert g(self.e)
if r == 0: return 0
r += self.size
for i in range(1, self.log + 1)[::-1]:
self.push((r - 1) >> i)
sm = self.e
while True:
r -= 1
while r > 1 and r % 2: r >>= 1
if not g(self.op(self.d[r], sm)):
while r < self.size:
self.push(r)
r = 2 * r + 1
if g(self.op(self.d[r], sm)):
sm = self.op(self.d[r], sm)
r -= 1
return r + 1 - self.size
sm = self.op(self.d[r], sm)
if (r & -r) == r: return 0
import sys
input = sys.stdin.buffer.readline
INF = 10**18
MOD = 998244353
N, Q = map(int, input().split())
def op(x, y):
xv, xr = x >> 32, x % (1 << 32)
yv, yr = y >> 32, y % (1 << 32)
return ((xv + yv) % MOD << 32) + (xr + yr) % MOD
def mapping(p, x):
xv, xr = x >> 32, x % (1 << 32)
if p != INF:
return ((p * xr % MOD) << 32) + xr
else:
return x
def composition(p, q):
if p != INF:
return p
else:
return q
def build_exp(n, b):
res = [0] * (n + 1)
res[0] = 1
for i in range(n):
res[i + 1] = res[i] * b % MOD
return res
exp = build_exp(N - 1, 10)
arr = [(e << 32) + e for e in exp[::-1]]
e = 0
id = INF
lst = LazySegmentTree(N, op, e, mapping, composition, id)
lst.build(arr)
res = list()
for _ in range(Q):
l, r, d = map(int, input().split())
lst.range_apply(l - 1, r, d)
v = lst.all_prod()
res.append(v >> 32)
print('\n'.join(map(str, res)))
```
Yes
| 43,554 | [
0.1944580078125,
-0.106689453125,
-0.0323486328125,
0.10260009765625,
-0.4814453125,
-0.09136962890625,
0.08709716796875,
-0.004055023193359375,
0.415283203125,
0.7490234375,
0.49365234375,
-0.1044921875,
0.1162109375,
-0.62451171875,
-0.483154296875,
0.1541748046875,
-0.59423828125,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
Submitted Solution:
```
class lazySegTree:
#遅延評価セグメント木
def __init__(s, op, e, mapping, composition, id, v):
if type(v) is int: v = [e()] * v
s._n = len(v)
s.log = s.ceil_pow2(s._n)
s.size = 1 << s.log
s.d = [e()] * (2 * s.size)
s.lz = [id()] * s.size
s.e = e
s.op = op
s.mapping = mapping
s.composition = composition
s.id = id
for i in range(s._n): s.d[s.size + i] = v[i]
for i in range(s.size - 1, 0, -1): s.update(i)
# 1点更新
def set(s, p, x):
p += s.size
for i in range(s.log, 0, -1): s.push(p >> i)
s.d[p] = x
for i in range(1, s.log + 1): s.update(p >> i)
# 1点取得
def get(s, p):
p += s.size
for i in range(s.log, 0, -1): s.push(p >> i)
return s.d[p]
# 区間演算
def prod(s, l, r):
if l == r: return s.e()
l += s.size
r += s.size
for i in range(s.log, 0, -1):
if (((l >> i) << i) != l): s.push(l >> i)
if (((r >> i) << i) != r): s.push(r >> i)
sml, smr = s.e(), s.e()
while (l < r):
if l & 1:
sml = s.op(sml, s.d[l])
l += 1
if r & 1:
r -= 1
smr = s.op(s.d[r], smr)
l >>= 1
r >>= 1
return s.op(sml, smr)
# 全体演算
def all_prod(s): return s.d[1]
# 1点写像
def apply(s, p, f):
p += s.size
for i in range(s.log, 0, -1): s.push(p >> i)
s.d[p] = s.mapping(f, s.d[p])
for i in range(1, s.log + 1): s.update(p >> i)
# 区間写像
def apply(s, l, r, f):
if l == r: return
l += s.size
r += s.size
for i in range(s.log, 0, -1):
if (((l >> i) << i) != l): s.push(l >> i)
if (((r >> i) << i) != r): s.push((r - 1) >> i)
l2, r2 = l, r
while l < r:
if l & 1:
sml = s.all_apply(l, f)
l += 1
if r & 1:
r -= 1
smr = s.all_apply(r, f)
l >>= 1
r >>= 1
l, r = l2, r2
for i in range(1, s.log + 1):
if (((l >> i) << i) != l): s.update(l >> i)
if (((r >> i) << i) != r): s.update((r - 1) >> i)
# L固定時の最長区間のR
def max_right(s, l, g):
if l == s._n: return s._n
l += s.size
for i in range(s.log, 0, -1): s.push(l >> i)
sm = s.e()
while True:
while (l % 2 == 0): l >>= 1
if not g(s.op(sm, s.d[l])):
while l < s.size:
s.push(l)
l = 2 * l
if g(s.op(sm, s.d[l])):
sm = s.op(sm, s.d[l])
l += 1
return l - s.size
sm = s.op(sm, s.d[l])
l += 1
if (l & -l) == l: break
return s._n
# R固定時の最長区間のL
def min_left(s, r, g):
if r == 0: return 0
r += s.size
for i in range(s.log, 0, -1): s.push((r - 1) >> i)
sm = s.e()
while True:
r -= 1
while r > 1 and (r % 2): r >>= 1
if not g(s.op(s.d[r], sm)):
while r < s.size:
s.push(r)
r = 2 * r + 1
if g(s.op(s.d[r], sm)):
sm = s.op(s.d[r], sm)
r -= 1
return r + 1 - s.size
sm = s.op(s.d[r], sm)
if (r & - r) == r: break
return 0
def update(s, k): s.d[k] = s.op(s.d[2 * k], s.d[2 * k + 1])
def all_apply(s, k, f):
s.d[k] = s.mapping(f, s.d[k])
if k < s.size: s.lz[k] = s.composition(f, s.lz[k])
def push(s, k):
s.all_apply(2 * k, s.lz[k])
s.all_apply(2 * k + 1, s.lz[k])
s.lz[k] = s.id()
def ceil_pow2(s, n):
x = 0
while (1 << x) < n: x += 1
return x
# return a・e = a となる e
def e():
return 0
# return a・b
def op(a, b):
a0, a1 = a >> 18, a & ((1 << 18) - 1)
b0, b1 = b >> 18, b & ((1 << 18) - 1)
return (((a0 * pow(10, b1, MOD) + b0) % MOD) << 18) + a1 + b1
# return f(a)
def mapping(f, a):
if f == 0: return a
a0, a1 = a >> 18, a & ((1 << 18) - 1)
return (D[f][a1] << 18) + a1
# return f・g
# gを写像した後にfを写像した結果
def composition(f, g):
if f == 0: return g
return f
# return f(id) = id となる id
def id():
return 0
N, Q = list(map(int, input().split()))
LRD = [list(map(int, input().split())) for _ in range(Q)]
MOD = 998244353
D = [[0]]
for i in range(1, 10):
D.append([0])
for j in range(N):
D[i].append((D[i][-1] * 10 + i) % MOD)
a = [(1 << 18) + 1 for _ in range(N)]
seg = lazySegTree(op, e, mapping, composition, id, a)
for l, r, d in LRD:
seg.apply(l - 1, r, d)
ans = seg.all_prod()
print(ans >> 18)
```
Yes
| 43,555 | [
0.17138671875,
-0.03265380859375,
0.009521484375,
-0.01209259033203125,
-0.55078125,
-0.015594482421875,
0.11151123046875,
0.042327880859375,
0.5234375,
0.77099609375,
0.62353515625,
-0.03778076171875,
0.005123138427734375,
-0.701171875,
-0.6103515625,
0.1474609375,
-0.479248046875,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
Submitted Solution:
```
import numpy as np
N, Q = map(int, input().split())
S = np.ones(N)
mod = 998244353
for i in range(Q):
L, R, D = map(int, input().split())
S[L-1:R] = D
print(''.join((S%mod).astype(np.int).astype(str).tolist()))
```
No
| 43,557 | [
0.28271484375,
-0.1407470703125,
-0.12213134765625,
-0.118896484375,
-0.66015625,
-0.1900634765625,
0.25537109375,
-0.125,
0.372802734375,
0.974609375,
0.53271484375,
-0.12109375,
0.057708740234375,
-0.61767578125,
-0.51708984375,
0.2041015625,
-0.360107421875,
-0.80908203125,
-0... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
Submitted Solution:
```
n,q=map(int,input().split())
s=('1')*n
for i in range(0,q):
r=''
l,k,m=map(int,input().split())
y=k-l+1
m=str(m)
r=(m)*y
s=s[0:l-1]+r+s[k:]
s=int(s)
s=str(s%998244353)
print(s)
```
No
| 43,558 | [
0.278564453125,
-0.07440185546875,
-0.11541748046875,
0.0167236328125,
-0.59228515625,
-0.09271240234375,
0.2301025390625,
-0.1011962890625,
0.32080078125,
0.884765625,
0.568359375,
-0.147705078125,
0.05908203125,
-0.66845703125,
-0.53076171875,
0.1810302734375,
-0.463623046875,
-0... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string S of length N. Initially, all characters in S are `1`s.
You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.
After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.
Constraints
* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q
Output
Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.
Examples
Input
8 5
3 6 2
1 4 7
3 8 3
2 2 2
4 5 1
Output
11222211
77772211
77333333
72333333
72311333
Input
200000 1
123 456 7
Output
641437905
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 1 << 60
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def ep(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
ep(e - s, 'sec')
return ret
return wrap
class LazySegmentTree():
def __init__(self, op, e, mapping, composition, im, init_array):
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.im = im
l = len(init_array)
def ceil_pow2(n):
x = 0
while (1 << x) < n:
x += 1
return x
self.log = ceil_pow2(l)
self.size = 1 << self.log
self.d = [e() for _ in range(2*self.size)]
self.lz = [im() for _ in range(self.size)]
for i, a in enumerate(init_array):
self.d[i+self.size] = a
for i in range(self.size-1, 0, -1):
self.__update(i)
def set(self, p, x):
p += self.size
for i in range(self.log, 0, -1):
self.__push(p >> i)
self.d[p] = x
for i in range(1, self.log+1):
self.__update(p >> i)
def __getitem__(self, p):
p += self.size
for i in range(self.log, 0, -1):
self.__push(p >> i)
return self.d[p]
def prod(self, l, r):
if l == r:
return self.e()
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l:
self.__push(l >> i)
if ((r >> i) << i) != r:
self.__push(r >> i)
sml = self.e()
smr = self.e()
while l < r:
if l & 1:
sml = self.op(sml, self.d[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.d[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def apply(self, l, r, f):
if l == r:
return
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l:
self.__push(l >> i)
if ((r >> i) << i) != r:
self.__push((r-1) >> i)
l2, r2 = l, r
while l < r:
if l & 1:
self.__all_apply(l, f)
l += 1
if r & 1:
r -= 1
self.__all_apply(r, f)
l >>= 1
r >>= 1
l, r = l2, r2
for i in range(1, self.log+1):
if ((l >> i) << i) != l:
self.__update(l >> i)
if ((r >> i) << i) != r:
self.__update((r-1) >> i)
def __update(self, k):
self.d[k] = self.op(self.d[2*k], self.d[2*k+1])
def __all_apply(self, k, f):
self.d[k] = self.mapping(f, self.d[k])
if k < self.size:
self.lz[k] = self.composition(f, self.lz[k])
def __push(self, k):
self.__all_apply(2*k, self.lz[k])
self.__all_apply(2*k+1, self.lz[k])
self.lz[k] = self.im()
M = 998244353
def e():
# (v, b)
return (0, 0)
def op(sl, sr):
# print(sl, sr)
return ((sl[0] + sr[0]) % M, (sl[1] + sr[1]) % M)
def mapping(fl, sr):
if fl[0] == 0:
return sr
return ((sr[1]*fl[0]) % M, sr[1])
def composition(fl, fr):
if fl[1] > fr[1]:
return fl
return fr
def im():
return (0, -1)
@mt
def slv(N, Q, LRQ):
A = [(pow(10, N-i-1, M), pow(10, N-i-1, M)) for i in range(N)]
st = LazySegmentTree(op, e, mapping, composition, im, A)
ans = []
for i, (l, r, d) in enumerate(LRQ, start=1):
l -= 1
st.apply(l, r, (d, i))
ans.append(st.prod(0, N)[0])
return ans
def main():
N, Q = read_int_n()
LRQ = [read_int_n() for _ in range(Q)]
print(*slv(N, Q, LRQ), sep='\n')
if __name__ == '__main__':
main()
```
No
| 43,559 | [
0.1890869140625,
-0.051910400390625,
0.0809326171875,
-0.11065673828125,
-0.7431640625,
-0.12054443359375,
0.330322265625,
-0.11968994140625,
0.3359375,
0.9970703125,
0.41455078125,
-0.096435546875,
0.09088134765625,
-0.53759765625,
-0.5419921875,
0.048248291015625,
-0.424072265625,
... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Tags: hashing, string suffix structures, strings
Correct Solution:
```
import sys
input = sys.stdin.readline
t = int(input())
for testcase in range(t):
s = list(input())
n = len(s)-1
c = [0]*(n+1)
for i in range(n):
for j in range(min(n-i,i+1)):
if s[i-j] != s[i+j]:
break
if c[i-j] < 1+j*2 and i < n//2:
c[i-j] = 1+j*2
if c[i+j] < 1+j*2 and i >= n//2:
c[i+j] = 1+j*2
for i in range(n-1):
for j in range(min(i+1,n-i-1)):
if s[i-j] != s[i+j+1]:
break
if c[i-j] < (j+1)*2 and i < n//2:
c[i-j] = (j+1)*2
if c[i+j+1] < (j+1)*2 and i >= n//2:
c[i+j+1] = (j+1)*2
res = c[0]
ma_pos = -1
for i in range(n//2):
if s[i] != s[n-1-i]:
break
if i == n//2-1:
print("".join(s[:n]))
ma_pos = -2
elif res < (i+1)*2 + max(c[i+1],c[n-2-i]):
res = (i+1)*2 + max(c[i+1],c[n-2-i])
ma_pos = i
#print(c,res,ma_pos)
if ma_pos == -2:
ma_pos = -2
elif res < c[n-1]:
print("".join(s[n-c[n-1]:]))
elif ma_pos == -1:
print("".join(s[:c[0]]))
else:
ans1 = s[:ma_pos+1]
if c[ma_pos+1] < c[n-2-ma_pos]:
ans2 = s[n-1-ma_pos-c[n-2-ma_pos]:n-1-ma_pos]
else:
ans2 = s[ma_pos+1:ma_pos+1+c[ma_pos+1]]
print("".join(ans1) + "".join(ans2) + "".join(ans1[::-1]))
```
| 43,978 | [
0.1669921875,
-0.25,
0.1578369140625,
0.492431640625,
-0.411376953125,
-0.33154296875,
0.07427978515625,
-0.283935546875,
0.16748046875,
0.63818359375,
0.49658203125,
0.0892333984375,
0.33837890625,
-1.23828125,
-0.7958984375,
-0.281005859375,
-0.407470703125,
-0.407470703125,
-0... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Tags: hashing, string suffix structures, strings
Correct Solution:
```
for _ in range(int(input())):
s = input()
n = len(s)
i = 0
a = ""
b = ""
while s[i] == s[n - 1 - i] and i < n - i - 1:
a += s[i]
b = s[i] + b
i += 1
ans1 = a + b
ans2 = a + b
c = a
for k in range(i, n - i):
a += s[k]
string = a + b
if string == string[::-1]: ans1 = string
for k in range(n - i - 1,i - 1,-1):
b = s[k] + b
string = c + b
if string == string[::-1]: ans2 = string
if len(ans1) > len(ans2): print(ans1)
else: print(ans2)
```
| 43,979 | [
0.1666259765625,
-0.2425537109375,
0.12384033203125,
0.478759765625,
-0.34375,
-0.35205078125,
0.14404296875,
-0.265869140625,
0.181640625,
0.61962890625,
0.52001953125,
0.12548828125,
0.343994140625,
-1.2734375,
-0.810546875,
-0.2420654296875,
-0.434814453125,
-0.4169921875,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Tags: hashing, string suffix structures, strings
Correct Solution:
```
t=int(input())
for query in range(t):
s=list(input())
n=len(s)
c=0
while s[c]==s[n-c-1] and n/2>c+1:
c=c+1
e=1
f=1
for b in range (c,n-c):
for d in range(c,b+1):
if s[d]!=s[b-d+c]:
e=0
if e:
f=b-c+1
e=1
g=1
h=1
for b in range (n-c-1,c-1,-1):
for d in range(n-c-1,b-1,-1):
if s[d]!=s[b-d+n-c-1]:
g=0
if g:
h=n-c-b
g=1
for i in range(c):
print(s[i],end="")
if f>h:
for j in range(c,c+f):
print(s[j],end="")
else:
for k in range(n-c-h,n-c):
print(s[k],end="")
for l in range(n-c,n):
print(s[l],end="")
print("")
```
| 43,980 | [
0.1519775390625,
-0.2169189453125,
0.10296630859375,
0.476318359375,
-0.398193359375,
-0.33544921875,
0.125732421875,
-0.25439453125,
0.2005615234375,
0.642578125,
0.52294921875,
0.15478515625,
0.365966796875,
-1.2744140625,
-0.83251953125,
-0.2427978515625,
-0.4296875,
-0.41137695... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Tags: hashing, string suffix structures, strings
Correct Solution:
```
def isPalindrome(s):
for i in range(len(s)//2):
if s[i]!=s[-i-1]:
return 0
return 1
for _ in range(int(input())):
s=input()
k1=-1
k2=len(s)-1
for i in range(len(s)//2):
if s[i]!=s[-i-1]:
k1=i
k2=len(s)-i-1
break
if k1==-1:
print(s)
else:
s1=s[k1:k2+1]
s2=s1[::-1]
maxl=1
maxl1=1
for k in range(1,len(s1)):
if isPalindrome(s1[:-k]):
maxl=len(s1)-k
break
for k in range(1,len(s2)):
if isPalindrome(s2[:-k]):
maxl1=len(s2)-k
break
if maxl>maxl1:
print(s[:k1+maxl]+s[k2+1:])
else:
print(s[:k1]+s2[:maxl1]+s[k2+1:])
```
| 43,981 | [
0.10662841796875,
-0.2310791015625,
0.0693359375,
0.46923828125,
-0.370849609375,
-0.358642578125,
0.1451416015625,
-0.2491455078125,
0.1748046875,
0.59765625,
0.5185546875,
0.1396484375,
0.359130859375,
-1.2568359375,
-0.8330078125,
-0.239990234375,
-0.448974609375,
-0.43627929687... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Tags: hashing, string suffix structures, strings
Correct Solution:
```
''' Prefix-Suffix Palindrome (Easy version)
'''
def checkpalindrome(string):
strlen = len(string)
half = ((strlen) + 1) // 2
palindrome = True
for n in range(half):
if string[n] != string[strlen - 1 - n]:
palindrome = False
break
return palindrome
''' routine '''
T = int(input())
for test in range(T):
S = input()
strlen = len(S)
pre, suf = 0, 0
while pre + suf < strlen - 1 and S[pre] == S[strlen - 1 - suf]:
pre += 1
suf += 1
baselen = pre + suf
maxlen = pre + suf
opti = (pre, suf)
for i in range(1, strlen - maxlen + 1):
palpre = S[pre:pre + i]
palsuf = S[strlen - suf - i:strlen - suf]
if checkpalindrome(palpre):
maxlen = baselen + i
opti = (baselen // 2 + i, baselen // 2)
if checkpalindrome(palsuf):
maxlen = baselen + i
opti = (baselen // 2, baselen // 2 + i)
maxpalindrome = S[:opti[0]] + S[strlen-opti[1]:strlen]
print(maxpalindrome)
```
| 43,982 | [
0.039825439453125,
-0.240478515625,
0.088623046875,
0.392822265625,
-0.363525390625,
-0.322021484375,
0.1524658203125,
-0.2457275390625,
0.1229248046875,
0.6064453125,
0.58642578125,
0.118408203125,
0.335693359375,
-1.2158203125,
-0.86669921875,
-0.15478515625,
-0.448486328125,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Tags: hashing, string suffix structures, strings
Correct Solution:
```
tc = int(input())
mod = 10 ** 9 + 7
cur_p = 1
p = [cur_p]
for i in range(10 ** 5):
cur_p *= 26
cur_p %= mod
p.append(cur_p)
def get_hashes(s):
hl = [0] * len(s)
h = 0
for i, ch in enumerate(s):
h += ch * p[len(s) - i - 1]
hl[i] = h
return hl
def manacher(text):
N = len(text)
if N == 0:
return
N = 2*N+1
L = [0] * N
L[0] = 0
L[1] = 1
C = 1
R = 2
i = 0
iMirror = 0
maxLPSLength = 0
diff = -1
for i in range(2,N):
iMirror = 2*C-i
L[i] = 0
diff = R - i
if diff > 0:
L[i] = min(L[iMirror], diff)
try:
while ((i + L[i]) < N and (i - L[i]) > 0) and \
(((i + L[i] + 1) % 2 == 0) or \
(text[(i + L[i] + 1) // 2] == text[(i - L[i] - 1) // 2])):
L[i]+=1
except Exception:
# print(e)
pass
if L[i] > maxLPSLength:
maxLPSLength = L[i]
if i + L[i] > R:
C = i
R = i + L[i]
return L
for _ in range(tc):
s = input()
sl = [ord(ch) for ch in s]
sr = sl[::-1]
h = 0
hl = get_hashes(sl)
hr = get_hashes(sr)
man = manacher(sl)
i = -1
best_res = 0, 0, 0, 0
best_l = 0
while i == -1 or i < len(sl) // 2 and hl[i] == hr[i]:
j = len(sl) - 1 - i
for r in range(len(man)):
ii = (r - man[r]) // 2
jj = ii + man[r] - 1
if (ii == i + 1 and jj < j or jj == j - 1 and ii > i):
l = (i + 1) * 2 + (jj - ii) + 1
if l > best_l:
best_res = i, j, ii, jj
best_l = l
i += 1
i, j, ii, jj = best_res
if best_l == 0:
print(s[0])
else:
print(s[:i + 1] + s[ii: jj + 1] + s[j:])
```
| 43,983 | [
0.162109375,
-0.2493896484375,
0.098876953125,
0.484375,
-0.380615234375,
-0.35009765625,
0.11761474609375,
-0.268798828125,
0.196533203125,
0.63525390625,
0.52880859375,
0.157470703125,
0.354736328125,
-1.2666015625,
-0.80712890625,
-0.243896484375,
-0.4228515625,
-0.431640625,
... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Tags: hashing, string suffix structures, strings
Correct Solution:
```
from sys import stdin
input=stdin.readline
def calc(a):
p=a+"#"+a[::-1]
pi=[0]*len(p)
j=0
for i in range(1,len(p)):
while j!=0 and p[j]!=p[i]:
j=pi[j-1]
if p[i]==p[j]:
j+=1
pi[i]=j
return a[:j]
t=int(input())
for _ in range(t):
s=input().rstrip()
n=len(s)
k=0
while k<n//2 and s[k]==s[n-1-k]:
k+=1
prefix=calc(s[k:n-k])
suffix=calc(s[k:n-k][::-1])
s1=s[:k]+prefix+s[n-k:]
s2=s[:k]+suffix+s[n-k:]
if len(s1)>=len(s2):
print(s1)
else:
print(s2)
```
| 43,984 | [
0.1485595703125,
-0.20556640625,
0.159423828125,
0.445068359375,
-0.384521484375,
-0.3369140625,
0.07501220703125,
-0.27099609375,
0.1776123046875,
0.62646484375,
0.53076171875,
0.11334228515625,
0.354248046875,
-1.23046875,
-0.80419921875,
-0.2646484375,
-0.435546875,
-0.402832031... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Tags: hashing, string suffix structures, strings
Correct Solution:
```
t = int(input())
while t:
t += -1
s = input()
ln = len(s)
i = 0
j = ln - 1
a = ""
aa = ""
while 1:
if i >= j: break
if s[i] == s[j]: a += s[i]
else: break
i -= -1
j += -1
if i <= j:
temp = j - i + 1
for k in range(1, temp + 1):
s1 = s[i: i + k - 1]
s2 = s1[: : -1]
if s1 == s2: aa = s1
for k in range(temp):
s1 = s[i + k: j + 1]
s2 = s1[: : -1]
if s1 == s2:
if len(s1) > len(aa): aa = s1
break
a1 = a[: : -1]
print(a, aa, a1, sep = "")
```
| 43,985 | [
0.1783447265625,
-0.20947265625,
0.1002197265625,
0.46044921875,
-0.3515625,
-0.342529296875,
0.1451416015625,
-0.27392578125,
0.1807861328125,
0.6162109375,
0.5185546875,
0.129150390625,
0.33837890625,
-1.2548828125,
-0.82373046875,
-0.2607421875,
-0.435302734375,
-0.421142578125,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Submitted Solution:
```
def reverse(s):
return s[::-1]
def isPalindrome(s):
# Calling reverse function
rev = reverse(s)
# Checking if both string are equal or not
if (s == rev):
return True
return False
def SubStr(S,s,e):
res=""
for i in range(s,e):
res+=S[i]
return res
def ProcessInputs():
S=input()
T=""
for i in range(0,len(S)):
if(i>=len(S)-i-1):
break
if(S[i]!=S[len(S)-i-1]):
break
else:
T+=S[i]
newS=SubStr(S,i,len(S)-i)
newS1=newS[::-1]
L1=1
for i in range(1,len(newS)):
string=newS[:i+1]
if isPalindrome(string):
L1=len(string)
L2=1
for i in range(1,len(newS1)):
string=newS1[:i+1]
if isPalindrome(string):
L2=len(string)
if(L2>L1):
res=newS1[:L2]
else:
res=newS[:L1]
print(T+res+T[::-1])
T=int(input())
for _ in range(T):
ProcessInputs()
```
Yes
| 43,986 | [
0.2237548828125,
-0.1796875,
0.04180908203125,
0.3984375,
-0.37060546875,
-0.272216796875,
0.05706787109375,
-0.177490234375,
0.0640869140625,
0.65625,
0.49853515625,
0.10797119140625,
0.17138671875,
-1.09765625,
-0.73193359375,
-0.349853515625,
-0.465087890625,
-0.4228515625,
-0... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Submitted Solution:
```
"""
Author: guiferviz
Time: 2020-03-19 15:35:01
"""
def longest_prefix(s, sr):
"""
p = s + '#' + sr
pi = [0] * len(p)
j = 0
for i in range(1, len(p)):
while j > 0 and p[j] != p[i]:
j = pi[j - 1]
if p[j] == p[i]:
j += 1
pi[i] = j
print("#", s[:j])
print(pi[len(s)+1:])
"""
assert len(s) == len(sr)
n = len(s)
p = [0] * n
j = 0
for i in range(1, n):
while j > 0 and s[j] != s[i]:
j = p[j - 1]
if s[i] == s[j]:
j += 1
p[i] = j
pj = p
p = [0] * n
j = 0
for i in range(0, n):
while j > 0 and s[j] != sr[i]:
j = pj[j - 1]
if sr[i] == s[j]:
j += 1
p[i] = j
"""
print("-", s[:j])
print(p)
"""
return s[:j]
def solve(s):
a, b = "", ""
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
break
i+=1; j-=1
a = s[:i]
b = s[j+1:]
if i + j < len(s):
# Find longest palindrome starting from s[i]
sub = s[i:j+1]
subr = sub[::-1]
p1 = longest_prefix(sub, subr)
p2 = longest_prefix(subr, sub)
a += p1 if len(p1) >= len(p2) else p2
# Build output and return.
return a + b
def main():
t = int(input())
for i in range(t):
s = input()
t = solve(s)
print(t)
if __name__ == "__main__":
main()
```
Yes
| 43,987 | [
0.2406005859375,
-0.1612548828125,
0.0953369140625,
0.466064453125,
-0.40576171875,
-0.2646484375,
0.10455322265625,
-0.1934814453125,
0.159912109375,
0.58544921875,
0.509765625,
0.1156005859375,
0.25341796875,
-1.177734375,
-0.80712890625,
-0.34130859375,
-0.42919921875,
-0.392578... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Submitted Solution:
```
test = int(input())
for _ in range(test) :
s = input()
limit = len(s)
if s == s[::-1] :
print(s)
continue
res = ""
mid1 = ""
mid2 = ""
l = len(s)-1
index =0
while index < l :
if s[index] == s[l] :
res+=s[index]
else :
break
index+=1
l-=1
p1 = index
p2 = l
cur = len(res)
while p1 <= l :
j = res + s[index:p1+1] + res[::-1]
if j == j[::-1] :
if len(j) > limit :
break
mid1 = j
p1+=1
while p2 >= index :
j = res + s[p2:l+1] + res[::-1]
if j == j[::-1] :
if len(j) > limit :
break
mid2 = j
p2-=1
if len(mid1) > len(mid2) :
print(mid1)
else :
print(mid2)
```
Yes
| 43,988 | [
0.267333984375,
-0.1280517578125,
0.14404296875,
0.463623046875,
-0.41748046875,
-0.252197265625,
0.11419677734375,
-0.1807861328125,
0.1461181640625,
0.59521484375,
0.474853515625,
0.078369140625,
0.2010498046875,
-1.1640625,
-0.73583984375,
-0.3271484375,
-0.43408203125,
-0.40429... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Submitted Solution:
```
def find_pal_prefix(s):
if not s:
return s
res = s[0]
for i in range(1, len(s)):
s1 = s[:i]
s2 = s1[::-1]
if s1 == s2:
res = s1
return res
def solve():
s1 = input().strip()
s2 = s1[::-1]
a = ""
b = ""
p = 0
for p in range(len(s1) // 2):
next_a = s1[p]
next_b = s2[p]
if next_a == next_b:
a += next_a
b += next_b
else:
break
else:
if len(s1) % 2 == 1:
a += s1[len(s1) // 2]
s = s1
if len(b) == 0:
s = s[len(a):]
else:
s = s[len(a):-len(b)]
a_plus = find_pal_prefix(s)
b_plus = find_pal_prefix(s[::-1])
if len(a_plus) > len(b_plus):
a += a_plus
else:
b += b_plus
two_sided_pal = a + b[::-1]
return two_sided_pal
def main():
t = int(input())
for _ in range(t):
print(solve())
if __name__ == "__main__":
main()
```
Yes
| 43,989 | [
0.290283203125,
-0.1458740234375,
0.1021728515625,
0.5029296875,
-0.411376953125,
-0.2978515625,
0.1324462890625,
-0.1986083984375,
0.1795654296875,
0.60595703125,
0.48583984375,
0.062744140625,
0.171630859375,
-1.1875,
-0.7265625,
-0.277099609375,
-0.302978515625,
-0.34033203125,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Submitted Solution:
```
import threading
def main():
for i in range(int(input())):
s = input()
be, en = -1, len(s)
if s == s[::-1]:
print(s)
else:
for j in range(len(s)):
if s[j] == s[-1 - j]:
be += 1
en -= 1
else:
break
ma, p1, tem = '', be + 1, en - 1
for j in range(en - 1, be, -1):
if s[j] == s[p1]:
p1 += 1
if tem == -1:
tem = j
else:
p1 = be + 1
if s[j] == s[p1]:
p1 += 1
tem = j
else:
tem = -1
if j < p1:
break
if tem != -1:
ma = s[be + 1:tem + 1]
tem, ma2, p1 = be + 1, '', en - 1
for j in range(be + 1, en):
if s[j] == s[p1]:
p1 -= 1
if tem == -1:
tem = j
else:
p1 = en - 1
if s[j] == s[p1]:
p1 += 1
tem = j
else:
tem = -1
if j > p1:
break
if tem != -1:
ma2 = s[tem:en]
if len(ma) >= len(ma2):
ans.append(s[:be + 1] + ma + s[en:])
else:
ans.append(s[:be + 1] + ma2 + s[en:])
print('\n'.join(ans))
if __name__ == '__main__':
ans = []
threading.stack_size(102400000)
thread = threading.Thread(target=main)
thread.start()
```
No
| 43,990 | [
0.25341796875,
-0.1483154296875,
0.09326171875,
0.39990234375,
-0.3984375,
-0.213134765625,
0.043975830078125,
-0.278564453125,
0.15478515625,
0.591796875,
0.471435546875,
0.07269287109375,
0.1776123046875,
-1.19921875,
-0.671875,
-0.363037109375,
-0.476806640625,
-0.478759765625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Submitted Solution:
```
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def main():
q = II()
for _ in range(q):
s = SI()
n = len(s)
ans = ""
mx = 0
for i in range(n):
if i>n-1-i or s[i]!=s[n-1-i]:break
if i >= n - 1 - i:
print(s)
continue
pre=s[:i]
t=s[i:n-i]
tn=n-i-i
for w in range(tn,1,-1):
if len(pre)*2+w<=mx:break
w2=w//2
if t[:w2]==t[w-w2:w][::-1]:
mx=len(pre)*2+w
ans=pre+t[:w]+pre[::-1]
break
if t[tn-w:tn-w+w2]==t[tn-w2:tn][::-1]:
mx=len(pre)*2+w
ans=pre+t[tn-w:tn]+pre[::-1]
break
if ans=="":ans=s[0]
print(ans)
main()
```
No
| 43,991 | [
0.250244140625,
-0.11334228515625,
0.199951171875,
0.50634765625,
-0.419921875,
-0.1978759765625,
0.06048583984375,
-0.222412109375,
0.1375732421875,
0.59130859375,
0.490478515625,
0.05084228515625,
0.19482421875,
-1.142578125,
-0.76611328125,
-0.294921875,
-0.431640625,
-0.4189453... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Submitted Solution:
```
for _ in range(int(input())):
s = input()
ans = [1, s[0]]
l, r = 0, len(s)-1
while l < r:
if s[l] == s[r]:
l +=1
r -=1
else:
hehe = r
while hehe!=l-1:
cay = s[:hehe] + s[r+1:]
if cay == cay[::-1]:
ans = [len(cay), cay]
break
hehe -=1
hehe = l+1
while hehe != r+1:
cay = s[:l] + s[hehe:]
if len(cay) > ans[0] and cay == cay[::-1]:
ans = [len(cay), cay]
break
hehe +=1
break
print(ans[1])
```
No
| 43,992 | [
0.264404296875,
-0.1527099609375,
0.1463623046875,
0.428466796875,
-0.41748046875,
-0.26123046875,
0.1046142578125,
-0.1868896484375,
0.12066650390625,
0.60107421875,
0.483642578125,
0.0726318359375,
0.2008056640625,
-1.171875,
-0.74951171875,
-0.34375,
-0.43408203125,
-0.397216796... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
Submitted Solution:
```
import sys
import math
input=sys.stdin.readline
n=int(input())
def check(s):
i=-1
j=len(s)
while((i+1)<=(j-1)):
if(s[i+1]==s[j-1]):
i+=1
j-=1
else:
i=-1
j-=1
# print(i,j)
if(i==j):
x=s[:i+1]
return x+s[j+1:j+1+len(x)-1]
else:
# print("lol")
x=s[:i+1]
return x+s[j:j+len(x)]
def fun(s):
z1=check(s)
z2=check(s[::-1])
# print(s,z1,z2,"hhhhhhh")
if(len(z1)>=len(z2)):
return z1
else:
return z2
for t1 in range(n):
t=input()
t=t.strip()
i=0
j=len(t)-1
# print(len(t))
# print(i,j)
if(t[i]==t[j]):
while(i<=j and t[i]==t[j]):
i+=1
j-=1
# print(i,j,"lol")
i-=1
j+=1
m=""
print(i,j)
if(i+1<=j-1):
s=t[i+1:j]
# print(s,"lol")
ans=fun(s)
m=ans
# print(m,"mmmm")
if(i==j):
print(t[:i+1]+m+t[j+1:])
else:
print(t[:i+1]+m+t[j:])
else:
if(i==j):
print(t[:i+1]+t[j+1:])
else:
print(t[:i+1]+t[j:])
else:
m=fun(t)
print(m)
```
No
| 43,993 | [
0.265380859375,
-0.133544921875,
0.1597900390625,
0.393310546875,
-0.4208984375,
-0.2381591796875,
0.065185546875,
-0.1864013671875,
0.1343994140625,
0.623046875,
0.4853515625,
0.06878662109375,
0.20947265625,
-1.1279296875,
-0.724609375,
-0.35986328125,
-0.445556640625,
-0.3889160... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Tags: bitmasks, data structures, dfs and similar, graphs, hashing, sortings, strings
Correct Solution:
```
import sys
I=sys.stdin.readlines()
N,M,K=map(int,I[0].split())
S=[I[i+1][:-1] for i in range(N)]
D=dict()
for i in range(N):
D[S[i]]=i
T=[I[i+N+1].split() for i in range(M)]
for i in range(M):
T[i][1]=int(T[i][1])-1
G=[[] for i in range(N)]
C=[0]*N
for i in range(M):
for j in range(K):
if S[T[i][1]][j]!='_' and S[T[i][1]][j]!=T[i][0][j]:
print('NO')
exit()
for j in range(1<<K):
t=''.join(['_' if j&(1<<k) else T[i][0][k] for k in range(K)])
x=D.get(t,-1)
if x!=-1 and x!=T[i][1]:
G[T[i][1]].append(x)
C[x]+=1
P=[]
Q=[]
F=[1]*N
for i in range(N):
if C[i]==0 and F[i]:
Q.append(i)
while len(Q):
v=Q.pop()
F[v]=0
P.append(v+1)
for i in range(len(G[v])):
C[G[v][i]]-=1
if C[G[v][i]]==0:
Q.append(G[v][i])
if len(P)==N:
print('YES')
print(*P)
else:
print('NO')
```
| 44,051 | [
0.296875,
0.023345947265625,
-0.0440673828125,
0.0161895751953125,
-0.353515625,
-0.32568359375,
-0.2303466796875,
-0.14404296875,
0.7451171875,
1.359375,
0.69970703125,
-0.16357421875,
0.039215087890625,
-0.95849609375,
-0.65673828125,
0.28857421875,
-0.822265625,
-1.140625,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Tags: bitmasks, data structures, dfs and similar, graphs, hashing, sortings, strings
Correct Solution:
```
import sys
from enum import Enum
class flag(Enum):
UNVISITED = -1
EXPLORED = -2
VISITED = -3
def match(p, s):
for i in range(len(p)):
if p[i] != "_" and p[i] != s[i]:
return False
return True
def cycleCheck(u):
global AL
global dfs_num
global dfs_parent
global sol
dfs_num[u] = flag.EXPLORED.value
for v in AL[u]:
if dfs_num[v] == flag.UNVISITED.value:
dfs_parent[v] = u
cycleCheck(v)
elif dfs_num[v] == flag.EXPLORED.value:
sol = False
dfs_num[u] = flag.VISITED.value
def toposort(u):
global AL
global dfs_num
global ts
dfs_num[u] = flag.VISITED.value
for v in AL[u]:
if dfs_num[v] == flag.UNVISITED.value:
toposort(v)
ts.append(u)
sol = True
n, m, k = map(int, sys.stdin.readline().strip().split())
pd = {}
ps = set()
pa = []
for i in range(n):
p = sys.stdin.readline().strip()
pd[p] = i + 1
ps.add(p)
pa.append(p)
AL = [[] for _ in range(n)]
for _ in range(m):
s, fn = sys.stdin.readline().strip().split()
fn = int(fn)
if not match(pa[fn-1], s):
sol = False
mm = [""]
for i in s:
mm = list(map(lambda x: x + "_", mm)) + list(map(lambda x: x + i, mm))
for i in mm:
if i in ps:
if pd[i] != fn:
AL[fn-1].append(pd[i]-1)
try:
if not sol:
print("NO")
else:
dfs_num = [flag.UNVISITED.value] * n
dfs_parent = [-1] * n
for u in range(n):
if dfs_num[u] == flag.UNVISITED.value:
cycleCheck(u)
if not sol:
print("NO")
else:
dfs_num = [flag.UNVISITED.value] * n
ts = []
for u in range(n):
if dfs_num[u] == flag.UNVISITED.value:
toposort(u)
ts = ts[::-1]
print("YES")
print(' '.join(map(lambda x: str(x+1), ts)))
except:
print("NO")
```
| 44,052 | [
0.296875,
0.023345947265625,
-0.0440673828125,
0.0161895751953125,
-0.353515625,
-0.32568359375,
-0.2303466796875,
-0.14404296875,
0.7451171875,
1.359375,
0.69970703125,
-0.16357421875,
0.039215087890625,
-0.95849609375,
-0.65673828125,
0.28857421875,
-0.822265625,
-1.140625,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Tags: bitmasks, data structures, dfs and similar, graphs, hashing, sortings, strings
Correct Solution:
```
from collections import defaultdict
from itertools import accumulate
import sys
input = sys.stdin.readline
'''
for CASES in range(int(input())):
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
sys.stdout.write(" ".join(map(str,ANS))+"\n")
'''
inf = 100000000000000000 # 1e17
mod = 998244353
n, m ,k= map(int, input().split())
M=[]
S=[]
F=[]
for i in range(n):
M.append(input().strip())
for i in range(m):
tmp1, tmp2 = input().split()
S.append(tmp1)
F.append(int(tmp2)-1)
TRAN_dict=defaultdict(int)
TRAN_dict['_']=0
for i in range(97,97+26):
TRAN_dict[chr(i)]=i-96;
def cal(X):
base=1
number=0
for x in X:
number=number*base+TRAN_dict[x]
base*=27
return number
STONE=defaultdict(int)
for i in range(n):
STONE[cal(list(M[i]))]=i
def check(X,result):
number=cal(X)
if number in STONE.keys():
result.append(STONE[number])
bian=[[] for i in range(n)]
du=[0]*n
for i in range(m):
gain=[]
for digit in range(1<<k):
now=list(S[i])
tmp=bin(digit)
tmp=tmp[2:]
tmp='0'*(k-len(tmp))+tmp
for j in range(k):
if tmp[j]=='1':
now[j]='_'
check(now,gain)
if F[i] not in gain:
print("NO")
sys.exit(0)
for x in gain:
if x!=F[i]:
bian[F[i]].append(x)
du[x]+=1
from collections import deque
QUE=deque()
for i in range(n):
if du[i]==0:
QUE.append(i)
TOP_SORT=[]
while QUE:
now=QUE.pop()
TOP_SORT.append(now)
for to in bian[now]:
du[to]-=1
if du[to]==0:
QUE.append(to)
if len(TOP_SORT)==n:
print("YES")
print(*[i+1 for i in TOP_SORT])
else:
print("NO")
```
| 44,053 | [
0.296875,
0.023345947265625,
-0.0440673828125,
0.0161895751953125,
-0.353515625,
-0.32568359375,
-0.2303466796875,
-0.14404296875,
0.7451171875,
1.359375,
0.69970703125,
-0.16357421875,
0.039215087890625,
-0.95849609375,
-0.65673828125,
0.28857421875,
-0.822265625,
-1.140625,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Tags: bitmasks, data structures, dfs and similar, graphs, hashing, sortings, strings
Correct Solution:
```
import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.buffer.readline())
def MI(): return map(int, sys.stdin.buffer.readline().split())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def BI(): return sys.stdin.buffer.readline().rstrip()
def SI(): return sys.stdin.buffer.readline().rstrip().decode()
inf = 10**16
md = 10**9+7
# md = 998244353
trie = [{}]
def push(s, val):
now = 0
for c in s:
if c not in trie[now]:
trie[now][c] = len(trie)
trie.append({})
now = trie[now][c]
trie[now]["end"] = val
def match(s):
res = []
stack = [(0, 0)]
while stack:
u, i = stack.pop()
if i == k:
res.append(trie[u]["end"])
continue
if s[i] in trie[u]:
stack.append((trie[u][s[i]], i+1))
if "_" in trie[u]:
stack.append((trie[u]["_"], i+1))
return res
n, m, k = MI()
for i in range(n):
push(SI(), i)
# print(trie)
to = [[] for _ in range(n)]
for _ in range(m):
s, u = SI().split()
u = int(u)-1
vv = match(s)
notmatch = True
for v in vv:
if u == v: notmatch = False
else: to[u].append(v)
if notmatch:
print("NO")
exit()
vis=[-1]*n
topo=[]
for u in range(n):
if vis[u]==1:continue
stack=[u]
while stack:
u=stack.pop()
if vis[u]==-1:
vis[u]=0
stack.append(u)
for v in to[u]:
if vis[v]==0:
print("NO")
exit()
if vis[v]==-1:
stack.append(v)
elif vis[u]==0:
topo.append(u+1)
vis[u]=1
print("YES")
print(*topo[::-1])
```
| 44,054 | [
0.296875,
0.023345947265625,
-0.0440673828125,
0.0161895751953125,
-0.353515625,
-0.32568359375,
-0.2303466796875,
-0.14404296875,
0.7451171875,
1.359375,
0.69970703125,
-0.16357421875,
0.039215087890625,
-0.95849609375,
-0.65673828125,
0.28857421875,
-0.822265625,
-1.140625,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Tags: bitmasks, data structures, dfs and similar, graphs, hashing, sortings, strings
Correct Solution:
```
from sys import stdin, gettrace
if gettrace():
def inputi():
return input()
else:
def input():
return next(stdin)[:-1]
def inputi():
return stdin.buffer.readline()
def patterns(s):
if len(s) == 1:
return [s, '_']
else:
tp = patterns(s[1:])
return [s[0] + t for t in tp] + ['_' + t for t in tp]
def main():
n,m,k = map(int, input().split())
pp = (input() for _ in range(n))
ppm = {}
for i, p in enumerate(pp):
ppm[p] = i
pre = [0]*n
suc = [[] for _ in range(n)]
for _ in range(m):
s, ml = input().split()
ml = int(ml) - 1
ps = patterns(s)
found = False
for p in ps:
if p in ppm:
if ppm[p] == ml:
found = True
else:
pre[ppm[p]] += 1
suc[ml].append(ppm[p])
if not found:
print("NO")
return
znodes = [i for i in range(n) if pre[i]==0]
res = []
while znodes:
i = znodes.pop()
res.append(i+1)
for j in suc[i]:
pre[j] -= 1
if pre[j] == 0:
znodes.append(j)
if len(res) == n:
print("YES")
print(' '.join(map(str, res)))
else:
print("NO")
if __name__ == "__main__":
main()
```
| 44,055 | [
0.296875,
0.023345947265625,
-0.0440673828125,
0.0161895751953125,
-0.353515625,
-0.32568359375,
-0.2303466796875,
-0.14404296875,
0.7451171875,
1.359375,
0.69970703125,
-0.16357421875,
0.039215087890625,
-0.95849609375,
-0.65673828125,
0.28857421875,
-0.822265625,
-1.140625,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Tags: bitmasks, data structures, dfs and similar, graphs, hashing, sortings, strings
Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
n,m,k = map(int,input().split())
p = [input().rstrip() for i in range(n)]
idx = {s:i for i,s in enumerate(p)}
def match(s):
res = []
for i in range(2**k):
tmp = []
for j in range(k):
if i>>j & 1:
tmp.append(s[j])
else:
tmp.append("_")
res.append("".join(tmp))
return set(res)
edge = [[] for i in range(n)]
deg = [0]*n
for i in range(m):
s,mt = input().rstrip().split()
mt = int(mt)-1
t = p[mt]
M = match(s)
if t in M:
for nv in M:
if nv!=t and nv in idx:
nv = idx[nv]
edge[mt].append(nv)
deg[nv] += 1
else:
exit(print("NO"))
deq = deque([v for v in range(n) if deg[v]==0])
res = []
while deq:
v = deq.popleft()
res.append(v+1)
for nv in edge[v]:
deg[nv] -= 1
if deg[nv]==0:
deq.append(nv)
if len(res)!=n:
exit(print("NO"))
print("YES")
print(*res)
```
| 44,056 | [
0.296875,
0.023345947265625,
-0.0440673828125,
0.0161895751953125,
-0.353515625,
-0.32568359375,
-0.2303466796875,
-0.14404296875,
0.7451171875,
1.359375,
0.69970703125,
-0.16357421875,
0.039215087890625,
-0.95849609375,
-0.65673828125,
0.28857421875,
-0.822265625,
-1.140625,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Tags: bitmasks, data structures, dfs and similar, graphs, hashing, sortings, strings
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
#CF-E-00
from collections import deque, defaultdict
def topological_sort(In, Out):
dq, L = deque(), []
for i, I in enumerate(In):
if not I:
dq.append(i)
while dq:
v = dq.popleft()
L.append(v)
for w in Out[v]:
In[w].remove(v)
if not In[w]:
dq.append(w)
if len(L) < len(In):
return False
return L
def main():
n, m, k = map(int,input().split()) #k: length of following inputs
def edges(s):
Ans = set()
for i in range(2**k):
ans = ''
for j in range(k):
if i>>j&1:
ans = ''.join([ans, s[j]])
else:
ans = ''.join([ans, '_'])
Ans.add(ans)
return Ans
D = defaultdict(lambda : -1)
for i in range(n):
D[input()] = i
flag = 1
In, Out = [set() for _ in range(n)], [set() for _ in range(n)]
for _ in range(m):
S, t = input().split()
t = int(t)
for e in edges(S):
if D[e]+1:
Out[t-1].add(D[e])
In[D[e]].add(t-1)
if t-1 not in Out[t-1]:
flag = 0
break
else:
Out[t-1].remove(t-1)
In[t-1].remove(t-1)
T = topological_sort(In, Out)
if flag == 0 or not T:
print('NO')
else:
print('YES')
print(*[t+1 for t in T], sep = ' ')
main()
```
| 44,057 | [
0.296875,
0.023345947265625,
-0.0440673828125,
0.0161895751953125,
-0.353515625,
-0.32568359375,
-0.2303466796875,
-0.14404296875,
0.7451171875,
1.359375,
0.69970703125,
-0.16357421875,
0.039215087890625,
-0.95849609375,
-0.65673828125,
0.28857421875,
-0.822265625,
-1.140625,
-0.... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Tags: bitmasks, data structures, dfs and similar, graphs, hashing, sortings, strings
Correct Solution:
```
import math,sys,bisect,heapq,os
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
def input(): return sys.stdin.readline().rstrip('\r\n')
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
def solve():
G = defaultdict(list)
def addEdge(a,b):
G[a].append(b)
def Kahn(N):
in_degree = [0]*(N+1)
for i in G.keys():
for j in G[i]:
in_degree[j] += 1
queue = deque()
for i in range(1,N+1):
if in_degree[i] == 0:
queue.append(i)
cnt =0
top_order = []
while queue:
u = queue.popleft()
top_order.append(u)
for i in G.get(u,[]):
in_degree[i] -= 1
if in_degree[i] == 0:
queue.append(i)
cnt += 1
if cnt != N:
Y(0);exit(0)
else:
Y(1);print(*top_order)
n,m,k = aj()
mark= {}
for i in range(n):
s = input()
mark[s] = i+1
B = []
for i in range(2**k):
f = bin(i)[2:]
f = '0'*(k - len(f)) + f
B.append(f)
for i in range(m):
s,mt = input().split(" ")
mt = int(mt)
st = set()
for j in B:
ss = ['']*k
for l in range(k):
if j[l] == '1':
ss[l] = s[l]
else:
ss[l] = '_'
ss = "".join(ss)
if ss in mark:
st.add(mark[ss])
#print(st)
if mt not in st:
Y(0);exit(0)
st.discard(mt)
for j in st:
addEdge(mt,j)
#print(G)
Kahn(n)
try:
#os.system("online_judge.py")
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
solve()
```
| 44,058 | [
0.296875,
0.023345947265625,
-0.0440673828125,
0.0161895751953125,
-0.353515625,
-0.32568359375,
-0.2303466796875,
-0.14404296875,
0.7451171875,
1.359375,
0.69970703125,
-0.16357421875,
0.039215087890625,
-0.95849609375,
-0.65673828125,
0.28857421875,
-0.822265625,
-1.140625,
-0.... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Submitted Solution:
```
import sys;input = sys.stdin.readline
def topological_sorted(digraph):
n = len(digraph);indegree = [0] * n
for v in range(n):
for nxt_v in digraph[v]:indegree[nxt_v] += 1
tp_order = [i for i in range(n) if indegree[i] == 0];stack = tp_order[:]
while stack:
v = stack.pop()
for nxt_v in digraph[v]:
indegree[nxt_v] -= 1
if indegree[nxt_v] == 0:stack.append(nxt_v);tp_order.append(nxt_v)
return len(tp_order) == n, tp_order
n, m, k = map(int, input().split());p = [input()[:-1] for i in range(n)];s = [list(input().split()) for i in range(m)];memo = {};graph = [[] for i in range(n)]
for idx, ptn in enumerate(p):val = sum([(ord(ptn[i]) - 96) * (27 ** i) for i in range(k) if ptn[i] != "_"]);memo[val] = idx
for i, (string, idx) in enumerate(s):s[i] = tuple(map(ord, string)), int(idx)
for string, idx in s:
idxs = []
idx -= 1
for bit_state in range(1 << k):
val = 0
for i in range(k):
if (bit_state >> i) & 1:
continue
val += (string[i] - 96) * (27 ** i)
if val in memo:
idxs.append(memo[val])
if idx not in idxs:print("NO");exit()
graph[idx] += [idx_to for idx_to in idxs if idx != idx_to]
flag, res = topological_sorted(graph)
if flag:print("YES");print(*[i + 1 for i in res])
else:print("NO")
```
Yes
| 44,059 | [
0.34375,
0.0246124267578125,
-0.05499267578125,
-0.12078857421875,
-0.45703125,
-0.24169921875,
-0.280517578125,
-0.1123046875,
0.58154296875,
1.3349609375,
0.64111328125,
-0.1138916015625,
0.0092620849609375,
-0.96142578125,
-0.68115234375,
0.1856689453125,
-0.74072265625,
-1.1650... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Submitted Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
from pprint import pprint
# toposort from pajenegod, AC server: https://discordapp.com/channels/555883512952258563/578670185007808512/708046996207829093
def toposort(graph):
res = []
found = [0] * len(graph)
stack = list(range(len(graph)))
while stack:
node = stack.pop()
if node < 0:
res.append(~node)
elif not found[node]:
found[node] = 1
stack.append(~node)
stack += graph[node]
# cycle check
for node in res:
if any(found[nei] for nei in graph[node]):
return None
found[node] = 0
return res[::-1]
def solve(N, M, K, P, S, MT):
graph = [[] for i in range(N)]
def isMatch(s, pattern):
for a, b in zip(s, pattern):
if b != "_" and a != b:
return False
return True
ordA = ord("a") - 1
def hashStr(s):
hsh = 0
for i, c in enumerate(s):
val = 27 if c == "_" else ord(c) - ordA
hsh = 32 * hsh + val
return hsh
patternToId = {}
for i, p in enumerate(P):
patternToId[hashStr(p)] = i
#print(patternToId)
for s, mt in zip(S, MT):
if not isMatch(s, P[mt]):
return "NO"
vals = [ord(c) - ordA for c in s]
hsh = 0
for mask in range(1 << K):
hsh = 0
for pos in range(K):
val = 27 if (1 << pos) & mask else vals[pos]
hsh = 32 * hsh + val
if hsh in patternToId:
mt2 = patternToId[hsh]
#print(s, bin(mask), hsh, P[mt2])
if mt2 != mt:
graph[mt].append(mt2)
ans = toposort(graph)
if ans is None:
return "NO"
return "YES\n" + " ".join(str(i + 1) for i in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = 1
for tc in range(1, TC + 1):
N, M, K = [int(x) for x in input().split()]
P = [input().decode().rstrip() for i in range(N)]
S = []
MT = []
for i in range(M):
s, mt = input().split()
s = s.decode()
mt = int(mt) - 1 # 0 indexed
S.append(s)
MT.append(mt)
ans = solve(N, M, K, P, S, MT)
print(ans)
```
Yes
| 44,060 | [
0.34375,
0.0246124267578125,
-0.05499267578125,
-0.12078857421875,
-0.45703125,
-0.24169921875,
-0.280517578125,
-0.1123046875,
0.58154296875,
1.3349609375,
0.64111328125,
-0.1138916015625,
0.0092620849609375,
-0.96142578125,
-0.68115234375,
0.1856689453125,
-0.74072265625,
-1.1650... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Submitted Solution:
```
#CF-E-00
import sys
from collections import deque, defaultdict
input = lambda: sys.stdin.readline().rstrip()
def topological_sort(In, Out):
dq, L = deque(), []
for i, I in enumerate(In):
if not I:
dq.append(i)
while dq:
v = dq.popleft()
L.append(v)
for w in Out[v]:
In[w].remove(v)
if not In[w]:
dq.append(w)
if len(L) < len(In):
return False
return L
def main():
n, m, k = map(int,input().split()) #k: length of following inputs
def edges(s):
Ans = set()
for i in range(2**k):
ans = [s[j] if i>>j&1 else '_' for j in range(k)]
Ans.add(''.join(ans))
return Ans
D = defaultdict(lambda : -1)
for i in range(n):
D[input()] = i
flag = 1
In, Out = [set() for _ in range(n)], [set() for _ in range(n)]
for _ in range(m):
S, t = input().split()
t = int(t)
for e in edges(S):
if D[e]+1:
Out[t-1].add(D[e])
In[D[e]].add(t-1)
if t-1 not in Out[t-1]:
flag = 0
break
else:
Out[t-1].remove(t-1)
In[t-1].remove(t-1)
T = topological_sort(In, Out)
if flag == 0 or not T:
print('NO')
else:
print('YES')
print(*[t+1 for t in T], sep = ' ')
main()
```
Yes
| 44,061 | [
0.34375,
0.0246124267578125,
-0.05499267578125,
-0.12078857421875,
-0.45703125,
-0.24169921875,
-0.280517578125,
-0.1123046875,
0.58154296875,
1.3349609375,
0.64111328125,
-0.1138916015625,
0.0092620849609375,
-0.96142578125,
-0.68115234375,
0.1856689453125,
-0.74072265625,
-1.1650... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Submitted Solution:
```
import sys;input = sys.stdin.readline
def topological_sorted(digraph):
n = len(digraph)
indegree = [0] * n
for v in range(n):
for nxt_v in digraph[v]:
indegree[nxt_v] += 1
tp_order = [i for i in range(n) if indegree[i] == 0]
stack = tp_order[:]
while stack:
v = stack.pop()
for nxt_v in digraph[v]:
indegree[nxt_v] -= 1
if indegree[nxt_v] == 0:
stack.append(nxt_v)
tp_order.append(nxt_v)
return len(tp_order) == n, tp_order
n, m, k = map(int, input().split())
p = [input()[:-1] for i in range(n)]
s = [list(input().split()) for i in range(m)]
memo = {}
for idx, ptn in enumerate(p):
val = 0
for i in range(k):
if ptn[i] == "_":
continue
val += (ord(ptn[i]) - 96) * (27 ** i)
memo[val] = idx
for i, (string, idx) in enumerate(s):
s[i] = tuple(map(ord, string)), int(idx)
graph = [[] for i in range(n)]
for string, idx in s:
idxs = []
idx -= 1
for bit_state in range(1 << k):
val = 0
for i in range(k):
if (bit_state >> i) & 1:
continue
val += (string[i] - 96) * (27 ** i)
if val in memo:
idxs.append(memo[val])
if idx not in idxs:
print("NO")
exit()
for idx_to in idxs:
if idx == idx_to:
continue
graph[idx].append(idx_to)
flag, res = topological_sorted(graph)
if flag:print("YES");print(*[i + 1 for i in res])
else:print("NO")
```
Yes
| 44,062 | [
0.34375,
0.0246124267578125,
-0.05499267578125,
-0.12078857421875,
-0.45703125,
-0.24169921875,
-0.280517578125,
-0.1123046875,
0.58154296875,
1.3349609375,
0.64111328125,
-0.1138916015625,
0.0092620849609375,
-0.96142578125,
-0.68115234375,
0.1856689453125,
-0.74072265625,
-1.1650... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Submitted Solution:
```
from collections import defaultdict
def main():
n, m, k = map(int, input().split(' '))
patterns = []
for i in range(n):
patterns.append((input(), i))
root = {}
for p, idx in patterns:
current_dict = root
for char in p:
if char not in current_dict:
current_dict[char] = {}
current_dict = current_dict[char]
current_dict["0"] = idx
graph = {i : set() for i in range(n)}
for _ in range(m):
wrd, idx = input().split(' ')
idx = int(idx)-1
indices = set()
def rec(word, i, d):
if i == k:
indices.add(d["0"])
else:
if word[i] in d:
rec(wrd, i+1 , d[word[i]])
if '_' in d:
rec(wrd, i+1 , d['_'])
rec(wrd, 0, root)
if idx not in indices:
print("NO")
return
indices.remove(idx)
for i in indices:
graph[idx].add(i)
print(graph)
def topological_sort(digraph):
n = len(digraph)
indegree = [0] * n
for v in range(n):
for nxt_v in digraph[v]:
indegree[nxt_v] += 1
tp_order = [i for i in range(n) if indegree[i] == 0]
stack = tp_order[:]
while stack:
v = stack.pop()
for nxt_v in digraph[v]:
indegree[nxt_v] -= 1
if indegree[nxt_v] == 0:
stack.append(nxt_v)
tp_order.append(nxt_v)
return len(tp_order) == n, tp_order
is_topo, ans = topological_sort(graph)
if not is_topo:
print("NO")
else:
print("YES")
print(" ".join(list(map(lambda x: str(x+1), ans))))
# region fastio
import os
import sys
from io import BytesIO, IOBase
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")
# endregion
if __name__ == "__main__":
main()
```
No
| 44,063 | [
0.34375,
0.0246124267578125,
-0.05499267578125,
-0.12078857421875,
-0.45703125,
-0.24169921875,
-0.280517578125,
-0.1123046875,
0.58154296875,
1.3349609375,
0.64111328125,
-0.1138916015625,
0.0092620849609375,
-0.96142578125,
-0.68115234375,
0.1856689453125,
-0.74072265625,
-1.1650... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Submitted Solution:
```
from copy import copy
def generate(s):
n = len(s)
sl = list(s)
a = []
for i in range(2 ** n):
v = copy(sl)
j = 0
while i > 0:
if i % 2 == 1:
v[j] = '_'
j += 1
i //= 2
a.append(''.join(v))
return a
n, m, k = map(int, input().split())
patterns = [input() for _ in range(n)]
ps = {pi: i for i, pi in enumerate(patterns)}
ks = []
js = []
for _ in range(m):
ke, j = input().split()
j = int(j) - 1
ks.append(ke)
js.append(j)
g = [[] for _ in range(n)]
for i, ki in enumerate(ks):
vertices = []
for v in generate(ki):
if v in ps:
vertices.append(ps[v])
if js[i] not in vertices:
print('NO')
exit()
for vi in vertices:
if vi == js[i]:
continue
g[js[i]].append(vi)
print(g)
final = []
def dfs(g, v, state):
print(v)
state[v] = -1
for u in g[v]:
if state[u] == -1:
print('NO')
exit()
if state[u] == -2:
continue
dfs(g, u, state)
final.append(v)
state[v] = -2
state = {i: 0 for i in range(n)}
for v in range(n):
if state[v] == 0:
dfs(g, v, state)
print('YES')
print(*(fi+1 for fi in final))
```
No
| 44,064 | [
0.34375,
0.0246124267578125,
-0.05499267578125,
-0.12078857421875,
-0.45703125,
-0.24169921875,
-0.280517578125,
-0.1123046875,
0.58154296875,
1.3349609375,
0.64111328125,
-0.1138916015625,
0.0092620849609375,
-0.96142578125,
-0.68115234375,
0.1856689453125,
-0.74072265625,
-1.1650... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
from bisect import *
from math import gcd
from itertools import permutations,combinations
from math import sqrt,ceil,floor
def main():
n,m,k=map(int,input().split())
b=Counter()
for i in range(1,n+1):
b[input().rstrip()]=i
ans=[0]*n
bk=1<<k
a=[]
c=set()
for _ in range(m):
s,ind=input().split()
c.add(s)
a.append([int(ind)-1,list(s)])
if len(c)!=m:
print("NO")
else:
a.sort(key=lambda x:x[0])
for l in range(m):
ind=a[l][0]
s=a[l][1]
mi=n+1
mis=""
for i in range(bk):
z=i
y=s[:]
j=0
while z:
if z&1:
y[j]="_"
j+=1
z>>=1
y="".join(y)
z=b[y]
if z:
if mi>z:
mi=z
mis=y
if mi==n+1:
ans=-1
break
else:
ans[ind]=mi
del b[mis]
if ans==-1:
print("NO")
else:
print("YES")
c=[]
for i in b:
c.append(b[i])
c.sort(reverse=True)
for i in range(n):
if not ans[i]:
ans[i]=c.pop()
print(*ans)
# 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")
if __name__ == "__main__":
main()
```
No
| 44,065 | [
0.34375,
0.0246124267578125,
-0.05499267578125,
-0.12078857421875,
-0.45703125,
-0.24169921875,
-0.280517578125,
-0.1123046875,
0.58154296875,
1.3349609375,
0.64111328125,
-0.1138916015625,
0.0092620849609375,
-0.96142578125,
-0.68115234375,
0.1856689453125,
-0.74072265625,
-1.1650... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches a pattern b if for each i from 1 to k either b_i is a wildcard character or b_i=a_i.
You are asked to rearrange the patterns in such a way that the first pattern the j-th string matches is p[mt_j]. You are allowed to leave the order of the patterns unchanged.
Can you perform such a rearrangement? If you can, then print any valid order.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 10^5, 1 ≤ k ≤ 4) — the number of patterns, the number of strings and the length of each pattern and string.
Each of the next n lines contains a pattern — k characters that are either lowercase Latin letters or underscores. All patterns are pairwise distinct.
Each of the next m lines contains a string — k lowercase Latin letters, and an integer mt (1 ≤ mt ≤ n) — the index of the first pattern the corresponding string should match.
Output
Print "NO" if there is no way to rearrange the patterns in such a way that the first pattern that the j-th string matches is p[mt_j].
Otherwise, print "YES" in the first line. The second line should contain n distinct integers from 1 to n — the order of the patterns. If there are multiple answers, print any of them.
Examples
Input
5 3 4
_b_d
__b_
aaaa
ab__
_bcd
abcd 4
abba 2
dbcd 5
Output
YES
3 2 4 5 1
Input
1 1 3
__c
cba 1
Output
NO
Input
2 2 2
a_
_b
ab 1
ab 2
Output
NO
Note
The order of patterns after the rearrangement in the first example is the following:
* aaaa
* __b_
* ab__
* _bcd
* _b_d
Thus, the first string matches patterns ab__, _bcd, _b_d in that order, the first of them is ab__, that is indeed p[4]. The second string matches __b_ and ab__, the first of them is __b_, that is p[2]. The last string matches _bcd and _b_d, the first of them is _bcd, that is p[5].
The answer to that test is not unique, other valid orders also exist.
In the second example cba doesn't match __c, thus, no valid order exists.
In the third example the order (a_, _b) makes both strings match pattern 1 first and the order (_b, a_) makes both strings match pattern 2 first. Thus, there is no order that produces the result 1 and 2.
Submitted Solution:
```
def KMPSearch(pat, txt):
M = len(pat)
N = len(txt)
# create lps[] that will hold the longest prefix suffix
# values for pattern
lps = [0]*M
j = 0 # index for pat[]
# Preprocess the pattern (calculate lps[] array)
computeLPSArray(pat, M, lps)
i = 0 # index for txt[]
while i < N:
if pat[j] == txt[i]:
i += 1
j += 1
if j == M:
print ("Found pattern at index " + str(i-j))
j = lps[j-1]
# mismatch after j matches
elif i < N and pat[j] != txt[i]:
# Do not match lps[0..lps[j-1]] characters,
# they will match anyway
if j != 0:
j = lps[j-1]
else:
i += 1
def computeLPSArray(pat, M, lps):
len = 0 # length of the previous longest prefix suffix
lps[0] # lps[0] is always 0
i = 1
# the loop calculates lps[i] for i = 1 to M-1
while i < M:
if pat[i]== pat[len]:
len += 1
lps[i] = len
i += 1
else:
if len != 0:
len = lps[len-1]
else:
lps[i] = 0
i += 1
txt = input()
pat = input()
KMPSearch(pat, txt)
```
No
| 44,066 | [
0.34375,
0.0246124267578125,
-0.05499267578125,
-0.12078857421875,
-0.45703125,
-0.24169921875,
-0.280517578125,
-0.1123046875,
0.58154296875,
1.3349609375,
0.64111328125,
-0.1138916015625,
0.0092620849609375,
-0.96142578125,
-0.68115234375,
0.1856689453125,
-0.74072265625,
-1.1650... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing minimum possible number of its substrings and find out which substrings you should reverse.
You are given a string s — original state of your string and string t — state of the string after hurricane. You should select k non-intersecting substrings of t in such a way that after reverse of these substrings string will be equal s and k is minimum possible.
Input
First line of input contains string s and second line contains string t. Both strings have same length and consist of lowercase English letters. 1 ≤ |s| = |t| ≤ 5·105
Output
In first line print k — minimum number of substrings you should reverse. Next output k lines. Each line should contain two integers li, ri meaning that you should reverse substring from symbol number li to symbol ri (strings are 1-indexed). These substrings shouldn't intersect. If there are multiple answers print any. If it's impossible to restore string output -1.
Example
Input
abcxxxdef
cbaxxxfed
Output
2
7 9
1 3
Submitted Solution:
```
def helperf(index):
max = 0
res = 0
delta = .5
while True:
loind = int(index-delta)
hiind = int(index+delta)
if loind<0 or hiind>=len(str1):break
if(str1[hiind] != str2[loind]):break
if(str2[hiind] != str1[loind]):break
max += 1
if(str1[hiind] != str2[hiind]):res = max
delta += 1
bounds = (0,0)
if(res):
bounds = (int(index-res+.5),int(index+res+.5))
return (res,max,index,bounds)
def helperi(index):
max = 0
res = 0
if(str1[index] != str2[index]):return (0,0,index,(0,0))
delta = 1
while True:
loind = int(index-delta)
hiind = int(index+delta)
if loind<0 or hiind>=len(str1):break
if(str1[hiind] != str2[loind]):break
if(str2[hiind] != str1[loind]):break
max += 1
if(str1[index+delta] != str2[index+delta]):res = max
delta += 1
return (res,max,index,(index-res,index+res+1))
def helper(index):
if(index%1==0):
return helperi(int(index))
return helperf(index)
def test(res):
str3 = list(str2)
for e in res:
for i in range((e[1]-e[0])//2):
# if(e[1]-i-1==i or e[1]-i==i):break
str3[i+e[0]],str3[e[1]-i-1] = str3[e[1]-i-1],str3[i+e[0]]
# print(''.join(str3))
str3 = ''.join(str3)
return str3==str1
str1 = input()
str2 = input()
res = []
for i in range(0,len(str1)*2-1):
t = helper(i/2)
if(t[0]):
# print(t)
res.append(t[3])
for i in range(len(res)):
if(res[i]==None):continue
for j in range(len(res)):
if(i==j):continue
if(res[j]==None):continue
if(res[i][0]<=res[j][0] and res[i][1]>=res[j][1]):
res[j] = None
res = [e for e in res if e!=None]
res = sorted(res,key=lambda x: x[0])
# print(len(res))
# for e in res:
# print(e[0]+1,e[1])
for i in range(1,len(res)):
if(res[i-1] == None):continue
if(res[i] == None):continue
if(res[i-1][0]==res[i][0]):
if(res[i-1][1]>res[i][1]):
res[i] = None
else:
res[i-1] = None
continue
if(res[i-1][1] >= res[i][0]):
res[i] = None
res = [e for e in res if e!=None]
if(not test(res)):
print(-1)
exit()
print(len(res))
for e in res:
print(e[0]+1,e[1])
r"""
cls ; cat .\e_test.txt | python.exe .\e.py
"""
```
No
| 44,381 | [
-0.0623779296875,
-0.035980224609375,
0.0232696533203125,
0.0204620361328125,
-0.62451171875,
-0.265869140625,
0.005035400390625,
-0.0187835693359375,
-0.246337890625,
0.80224609375,
0.77783203125,
-0.1392822265625,
-0.23974609375,
-0.64111328125,
-0.5087890625,
-0.0469970703125,
-0.... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing minimum possible number of its substrings and find out which substrings you should reverse.
You are given a string s — original state of your string and string t — state of the string after hurricane. You should select k non-intersecting substrings of t in such a way that after reverse of these substrings string will be equal s and k is minimum possible.
Input
First line of input contains string s and second line contains string t. Both strings have same length and consist of lowercase English letters. 1 ≤ |s| = |t| ≤ 5·105
Output
In first line print k — minimum number of substrings you should reverse. Next output k lines. Each line should contain two integers li, ri meaning that you should reverse substring from symbol number li to symbol ri (strings are 1-indexed). These substrings shouldn't intersect. If there are multiple answers print any. If it's impossible to restore string output -1.
Example
Input
abcxxxdef
cbaxxxfed
Output
2
7 9
1 3
Submitted Solution:
```
def main():
#firstStr = input('')
#secStr = input('')
firstStr="abcxxxdef"
secStr="cbaxxxfed"
stringLen=len(firstStr)
runLen=0
runLenStart=-1
runLenStop=-1
firstLenCount = 0
secondLenCount = 0
runs=[]
for iDx in range(stringLen-1,-1, -1):
firstStrItem=firstStr[iDx];
secStrItem=secStr[iDx];
if runLen == 0 and firstStrItem == secStrItem:
# skip
pass
else:
firstLenCount = firstLenCount + ord(firstStrItem)
secondLenCount = secondLenCount + ord(secStrItem)
if firstLenCount == secondLenCount:
if runLen > 0:
runLenStop=iDx
runs.append([runLenStop + 1, runLenStart + 1])
runLenStop=-1
runLenStart=0
firstLenCount=0
secondLenCount=0
runLen = 0
else:
if runLen == 0:
runLenStart = iDx
runLen = runLen + 1
if len(runs) > 0:
print(str(len(runs)))
for oneRun in runs:
print(str(oneRun[0]) + ", " + str(oneRun[1]))
else:
print("runs is empty.")
if __name__ == '__main__':
main()
```
No
| 44,382 | [
-0.035858154296875,
-0.10113525390625,
0.04266357421875,
-0.01363372802734375,
-0.5625,
-0.26416015625,
-0.09375,
-0.031890869140625,
-0.1190185546875,
0.69384765625,
0.83544921875,
-0.2430419921875,
-0.185546875,
-0.6669921875,
-0.56298828125,
-0.06378173828125,
-0.83056640625,
-0... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing minimum possible number of its substrings and find out which substrings you should reverse.
You are given a string s — original state of your string and string t — state of the string after hurricane. You should select k non-intersecting substrings of t in such a way that after reverse of these substrings string will be equal s and k is minimum possible.
Input
First line of input contains string s and second line contains string t. Both strings have same length and consist of lowercase English letters. 1 ≤ |s| = |t| ≤ 5·105
Output
In first line print k — minimum number of substrings you should reverse. Next output k lines. Each line should contain two integers li, ri meaning that you should reverse substring from symbol number li to symbol ri (strings are 1-indexed). These substrings shouldn't intersect. If there are multiple answers print any. If it's impossible to restore string output -1.
Example
Input
abcxxxdef
cbaxxxfed
Output
2
7 9
1 3
Submitted Solution:
```
def helperf(index):
max = 0
res = 0
delta = .5
while True:
loind = int(index-delta)
hiind = int(index+delta)
if loind<0 or hiind>=len(str1):break
if(str1[hiind] != str2[loind]):break
max += 1
if(str1[hiind] != str2[hiind]):res = max
delta += 1
bounds = (0,0)
if(res):
bounds = (int(index-res+.5),int(index+res+.5))
return (res,max,index,bounds)
def helperi(index):
max = 0
res = 0
if(str1[index] != str2[index]):return (0,0,index,(0,0))
delta = 1
while True:
if delta>index or delta+index >= len(str1):break
if(str1[index+delta] != str2[index-delta]):break
max += 1
if(str1[index+delta] != str2[index+delta]):res = max
delta += 1
return (res,max,index,(index-res,index+res+1))
def helper(index):
if(index%1==0):
return helperi(int(index))
return helperf(index)
def test(res):
str3 = list(str2)
for e in res:
for i in range((e[1]-e[0])//2):
# if(e[1]-i-1==i or e[1]-i==i):break
str3[i+e[0]],str3[e[1]-i-1] = str3[e[1]-i-1],str3[i+e[0]]
# print(''.join(str3))
str3 = ''.join(str3)
return str3==str1
str1 = input()
str2 = input()
res = []
for i in range(0,len(str1)*2-1):
t = helper(i/2)
if(t[0]):
res.append(t[3])
for i in range(len(res)):
if(res[i]==None):continue
for j in range(len(res)):
if(i==j):continue
if(res[j]==None):continue
if(res[i][0]<res[j][0] and res[i][1]>res[j][1]):
res[j] = None
res = [e for e in res if e!=None]
if(not test(res)):
print(-1)
exit()
print(len(res))
for e in res:
print(e[0]+1,e[1])
r"""
cls ; cat .\e_test.txt | python.exe .\e.py
"""
```
No
| 44,383 | [
-0.0643310546875,
-0.035675048828125,
0.022064208984375,
0.033416748046875,
-0.6337890625,
-0.264404296875,
0.01328277587890625,
0.0030975341796875,
-0.2509765625,
0.79833984375,
0.76904296875,
-0.1356201171875,
-0.2330322265625,
-0.6376953125,
-0.51025390625,
-0.04241943359375,
-0.9... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing minimum possible number of its substrings and find out which substrings you should reverse.
You are given a string s — original state of your string and string t — state of the string after hurricane. You should select k non-intersecting substrings of t in such a way that after reverse of these substrings string will be equal s and k is minimum possible.
Input
First line of input contains string s and second line contains string t. Both strings have same length and consist of lowercase English letters. 1 ≤ |s| = |t| ≤ 5·105
Output
In first line print k — minimum number of substrings you should reverse. Next output k lines. Each line should contain two integers li, ri meaning that you should reverse substring from symbol number li to symbol ri (strings are 1-indexed). These substrings shouldn't intersect. If there are multiple answers print any. If it's impossible to restore string output -1.
Example
Input
abcxxxdef
cbaxxxfed
Output
2
7 9
1 3
Submitted Solution:
```
def main():
#firstStr = input('')
#secStr = input('')
firstStr="abcxxxdef"
secStr="cbaxxxfed"
stringLen=len(firstStr)
runLen=0
runLenStart=-1
runLenStop=-1
firstLenCount = 0
secondLenCount = 0
runs=[]
for iDx in range(stringLen-1,-1, -1):
firstStrItem=firstStr[iDx];
secStrItem=secStr[iDx];
if runLen == 0 and firstStrItem == secStrItem:
# skip
pass
else:
firstLenCount = firstLenCount + ord(firstStrItem)
secondLenCount = secondLenCount + ord(secStrItem)
if firstLenCount == secondLenCount:
if runLen > 0:
runLenStop=iDx
runs.append([runLenStop + 1, runLenStart + 1])
runLenStop=-1
runLenStart=0
firstLenCount=0
secondLenCount=0
runLen = 0
else:
if runLen == 0:
runLenStart = iDx
runLen = runLen + 1
if len(runs) > 0:
print(str(len(runs)))
for oneRun in runs:
print(str(oneRun[0]) + " " + str(oneRun[1]))
else:
print("runs is empty.")
if __name__ == '__main__':
main()
```
No
| 44,384 | [
-0.035858154296875,
-0.10113525390625,
0.04266357421875,
-0.01363372802734375,
-0.5625,
-0.26416015625,
-0.09375,
-0.031890869140625,
-0.1190185546875,
0.69384765625,
0.83544921875,
-0.2430419921875,
-0.185546875,
-0.6669921875,
-0.56298828125,
-0.06378173828125,
-0.83056640625,
-0... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
"Correct Solution:
```
N = int(input())
MOD = 10 ** 9 + 7
memo = [{} for _ in range(N + 1)]
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i - 1], t[i] = t[i], t[i - 1]
if "".join(t).count("AGC") > 0:
return False
return True
def dfs(cur, last3):
if last3 in memo[cur]:
return memo[cur][last3]
if cur == N:
return 1
ret = 0
for c in "ACGT":
if ok(last3 + c):
ret = (ret + dfs(cur + 1, last3[1:] + c)) % MOD
memo[cur][last3] = ret
return ret
print(dfs(0, "TTT"))
```
| 44,469 | [
0.56689453125,
-0.13671875,
-0.00061798095703125,
0.352294921875,
-0.473876953125,
-0.51611328125,
0.279541015625,
0.2044677734375,
0.459228515625,
0.97705078125,
0.469482421875,
-0.36865234375,
0.209228515625,
-0.90380859375,
-0.376953125,
0.2166748046875,
-0.489013671875,
-0.8178... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
"Correct Solution:
```
n = int(input())
mod = 10**9+7
dp = [[0]*4 for i in range(n)]
for i in range(4):
dp[0][i] = 1
dp[1][i] = 4
dp[2][i] = 16
dp[2][1] -= 2
dp[2][2] -= 1
for i in range(3,n):
for j in range(4):
dp[i][j] = sum(dp[i-1])%mod
dp[i][1] -= dp[i-2][0] #AGC
dp[i][1] -= dp[i-2][2] #GAC
dp[i][1] -= dp[i-3][0]*3 #AGTC,AGGC,ATGC
dp[i][2] -= dp[i-2][0] #ACG
dp[i][2] += dp[i-3][2] #GACG
print(sum(dp[n-1])%mod)
```
| 44,470 | [
0.45556640625,
-0.1817626953125,
0.09344482421875,
0.398681640625,
-0.38916015625,
-0.6513671875,
0.1815185546875,
0.1710205078125,
0.379638671875,
0.818359375,
0.53564453125,
-0.294921875,
0.245361328125,
-0.978515625,
-0.2978515625,
0.146240234375,
-0.54931640625,
-0.748046875,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
"Correct Solution:
```
N = int(input())
mod = 10 ** 9 + 7
memo = [{} for i in range(N+1)]
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i-1], t[i] = t[i], t[i-1]
if ''.join(t).count('AGC') >= 1:
return False
return True
def dfs(cur, last3):
if last3 in memo[cur]:
return memo[cur][last3]
if cur == N:
return 1
ret = 0
for c in 'ATCG':
if ok(last3 + c):
ret = (ret + dfs(cur + 1, last3[1:]+c)) % mod
memo[cur][last3] = ret
#print(memo, cur)
return ret
print(dfs(0, 'TTT'))
```
| 44,471 | [
0.5537109375,
-0.1417236328125,
0.0391845703125,
0.317626953125,
-0.54541015625,
-0.48681640625,
0.269287109375,
0.197265625,
0.41064453125,
0.98046875,
0.468505859375,
-0.404052734375,
0.306884765625,
-0.875,
-0.35107421875,
0.1788330078125,
-0.50830078125,
-0.78515625,
-0.46435... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
"Correct Solution:
```
n=int(input())
M,R=10**9+7,range(4)
dp=[[[[0]*4for k in R]for j in R]for i in range(n+1)]
dp[0][3][3][3]=1
for i in range(1,n+1):
for j in R:
for k in R:
for l in R:
for m in R:
if(2,0,1)!=(k,l,m)!=(0,1,2)!=(k,l,m)!=(0,2,1)!=(j,l,m)!=(0,2,1)!=(j,k,m):dp[i][k][l][m]=(dp[i][k][l][m]+dp[i-1][j][k][l])%M
print(sum(c for a in dp[n]for b in a for c in b)%M)
```
| 44,472 | [
0.42236328125,
-0.14404296875,
0.00826263427734375,
0.2449951171875,
-0.300048828125,
-0.51318359375,
0.1907958984375,
0.1290283203125,
0.29345703125,
0.9296875,
0.51708984375,
-0.250244140625,
0.233154296875,
-0.8046875,
-0.45166015625,
0.19140625,
-0.64990234375,
-0.8134765625,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
"Correct Solution:
```
N , mod = int(input()) , 10**9+7
memo = [{} for i in range(N+1)]
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i-1] ,t[i] = t[i],t[i-1]
if ''.join(t).count("AGC") >= 1:
return False
return True
def dfs(cur,last3):
if last3 in memo[cur]:
return memo[cur][last3]
if cur == N:
return 1
ret = 0
for c in "AGCT":
if ok(last3+c):
ret = (ret + dfs(cur+1,last3[1:]+c)) % mod
memo[cur][last3] = ret
return ret
print(dfs(0,"TTT"))
```
| 44,473 | [
0.52880859375,
-0.10552978515625,
0.00565338134765625,
0.2939453125,
-0.474853515625,
-0.50048828125,
0.265380859375,
0.182861328125,
0.45263671875,
0.982421875,
0.47900390625,
-0.370849609375,
0.22705078125,
-0.8779296875,
-0.396240234375,
0.2275390625,
-0.51904296875,
-0.81884765... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
"Correct Solution:
```
N = int(input())
mod = 10**9+7
def check(s):
for i in range(4):
l=list(s)
if i>0:
l[i-1],l[i]=l[i],l[i-1]
if "".join(l).count("AGC"):
return False
else:
return True
memo=[dict() for _ in range(N)]
def dfp(i,seq):
if i==N:
return 1
if seq in memo[i]:
return memo[i][seq]
ret=0
for s in ["A","G","C","T"]:
if check(seq+s):
ret=(ret+dfp(i+1,seq[1:]+s))%mod
memo[i][seq] = ret
return ret
print(dfp(0,"TTT"))
```
| 44,474 | [
0.5458984375,
-0.16845703125,
0.02960205078125,
0.39013671875,
-0.421630859375,
-0.4462890625,
0.12310791015625,
0.126220703125,
0.4853515625,
0.97265625,
0.440673828125,
-0.384765625,
0.317626953125,
-0.8759765625,
-0.29052734375,
0.238525390625,
-0.468017578125,
-0.7880859375,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
"Correct Solution:
```
N = int(input())
mod = 10**9+7
dp = [[0]*4 for _ in range(N)]
dp[0] = [1,1,1,1]
dp[1] = [4,4,4,4]
#AGC, ACG, GAC, A?GC,AG?C -> AGGC, ATGC,AGTC
for i in range(2,N):
if i == 2:
dp[i][0] = dp[i-1][0]*4
dp[i][1] = dp[i-1][1]*4-2
dp[i][2] = dp[i-1][2]*4-1
dp[i][3] = dp[i-1][3]*4
else:
dp[i][0] = sum(dp[i-1])
dp[i][1] = sum(dp[i-1])-dp[i-2][0]-dp[i-2][2]-dp[i-3][0]*3
dp[i][2] = sum(dp[i-1])-dp[i-2][0]+dp[i-3][2]
dp[i][3] = sum(dp[i-1])
print(sum(dp[N-1])%mod)
```
| 44,475 | [
0.37841796875,
-0.16748046875,
0.03070068359375,
0.289306640625,
-0.36376953125,
-0.55224609375,
0.1689453125,
0.1260986328125,
0.395263671875,
0.89111328125,
0.5419921875,
-0.31640625,
0.3349609375,
-0.78125,
-0.466796875,
0.139892578125,
-0.5712890625,
-0.78759765625,
-0.471435... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
"Correct Solution:
```
N = int(input())
ng = ["agc", "aagc", "acgc", "aggc", "atgc", "agac", "agcc", "aggc", "agtc", "acg", "gac"]
x = {"a": 1, "g": 1, "c": 1, "t": 1}
for _ in range(1,N):
y = dict()
for let,num in x.items():
for a in ["a", "c", "g", "t"]:
if let[-3:] + a in ng or (let[-3:] + a)[-3:] in ng:
continue
else:
if let[-3:] + a in y.keys():
y[let[-3:] + a] += num
else:
y[let[-3:]+a] = num
x = y
print(sum(x.values()) % (10**9+7))
```
| 44,476 | [
0.4794921875,
-0.0283355712890625,
0.0343017578125,
0.380126953125,
-0.346923828125,
-0.5244140625,
0.39306640625,
0.1748046875,
0.50927734375,
1.021484375,
0.6640625,
-0.347900390625,
0.234130859375,
-0.958984375,
-0.333740234375,
0.09991455078125,
-0.64111328125,
-0.806640625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
Submitted Solution:
```
N = int(input())
MOD = 10 ** 9 + 7
memo = [{} for i in range(N + 1)]
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
tmp = t[i]
t[i] = t[i - 1]
t[i - 1] = tmp
if ''.join(t).count('AGC') >= 1:
return False
return True
def AGC(n, last3):
if last3 in memo[n]:
return memo[n][last3]
if n == N:
return 1
ret = 0
for c in 'AGCT':
if ok(last3 + c):
ret = (ret + AGC(n + 1, last3[1:] + c)) % MOD
memo[n][last3] = ret
return ret
print(AGC(0, 'TTT'))
```
Yes
| 44,477 | [
0.59423828125,
0.0065765380859375,
-0.0869140625,
0.392822265625,
-0.6181640625,
-0.60546875,
0.245849609375,
0.216552734375,
0.49658203125,
0.9951171875,
0.5419921875,
-0.266845703125,
0.1002197265625,
-0.91064453125,
-0.4150390625,
0.131591796875,
-0.47705078125,
-0.82080078125,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
Submitted Solution:
```
n = int(input())
memo = [{} for i in range(n+1)]
def ok(last4):
for i in range(4):
t = list(last4)
if i >= 1:
t[i-1], t[i] = t[i], t[i-1]
if ''.join(t).count('AGC') >= 1:
return False
return True
def dfs(cur, last3):
if last3 in memo[cur]:
return memo[cur][last3]
if cur == n:
return 1
ret = 0
for c in 'AGCT':
if ok(last3 + c):
ret = (ret + dfs(cur+1, last3[1:] + c)) % 1000000007
memo[cur][last3] = ret
return ret
print(dfs(0, 'TTT'))
```
Yes
| 44,478 | [
0.49072265625,
-0.09027099609375,
0.054656982421875,
0.384033203125,
-0.60009765625,
-0.4306640625,
0.207275390625,
0.2362060546875,
0.4091796875,
0.947265625,
0.45751953125,
-0.263427734375,
0.1768798828125,
-0.76708984375,
-0.460693359375,
0.041046142578125,
-0.49365234375,
-0.76... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
Submitted Solution:
```
import itertools
L = [''.join(i) for i in itertools.product('0123', repeat=3)]
l = len(L)
mod = 10**9+7
AGC = '021'
ACG = '012'
GAC = '201'
nc3 = set([AGC, ACG, GAC])
AGGC = '0221'
AGTC = '0231'
ATGC = '0321'
nc4 = set([AGGC, AGTC, ATGC])
n = int(input())
dp = [[0]*l for _ in range(n+1)]
for i in L:
if i in nc3: continue
dp[3][int(i, 4)] = 1
for i in range(3, n):
for jl in L:
for k in "0123":
nxt = jl[1:] + k
if nxt in nc3: continue
if jl+k in nc4: continue
dp[i+1][int(nxt, 4)] += dp[i][int(jl, 4)]
print(sum(dp[n])%mod)
```
Yes
| 44,479 | [
0.44970703125,
-0.1304931640625,
-0.1231689453125,
0.3017578125,
-0.40771484375,
-0.5361328125,
0.0587158203125,
0.1142578125,
0.31884765625,
0.9658203125,
0.381591796875,
-0.2318115234375,
0.1822509765625,
-0.931640625,
-0.3935546875,
0.10546875,
-0.488525390625,
-0.85791015625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
Submitted Solution:
```
n=int(input())
A,G,C,T,mod,ans=0,1,2,3,pow(10,9)+7,0
dp=[[[[0]*4for k in range(4)]for j in range(4)]for i in range(n+1)]
dp[0][T][T][T]=1
for i in range(1,n+1):
for j in range(4):
for k in range(4):
for l in range(4):
for m in range(4):
if(G,A,C)!=(k,l,m)!=(A,C,G)!=(k,l,m)!=(A,G,C)!=(j,l,m)!=(A,G,C)!=(j,k,m):
dp[i][k][l][m]+=dp[i-1][j][k][l]
dp[i][k][l][m]%=mod
for j in range(4):
for k in range(4):
for l in range(4):
ans+=dp[n][j][k][l]
print(ans%mod)
```
Yes
| 44,480 | [
0.42626953125,
-0.12939453125,
0.0243377685546875,
0.316650390625,
-0.4638671875,
-0.42138671875,
0.06640625,
0.146728515625,
0.348388671875,
0.98779296875,
0.54541015625,
-0.1871337890625,
0.2197265625,
-0.841796875,
-0.38232421875,
0.1558837890625,
-0.5283203125,
-0.83447265625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 16 20:52:46 2019
@author: Owner
"""
import collections
import scipy.misc
import sys
import numpy as np
import math
from operator import itemgetter
import itertools
import copy
import bisect
#素因数を並べる
def prime_decomposition(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n /= i
table.append(int(i))
i += 1
if n > 1:
table.append(int(n))
return table
# 桁数を吐く
def digit(i):
if i > 0:
return digit(i//10) + [i%10]
else:
return []
def getNearestValueIndex(list, num):
"""
概要: リストからある値に最も近い値のインデックスを取得する関数
@param list: データ配列
@param num: 対象値
@return 対象値に最も近い値
"""
# リスト要素と対象値の差分を計算し最小値のインデックスを取得
idx = np.abs(np.asarray(list) - num).argmin()
return idx
def find_index(l, x, default=False):
if x in l:
return l.index(x)
else:
return default
"""
N, X = map(int, input().split())
x = [0]*N
x[:] = map(int, input().split())
P = [0]*N
Y = [0]*N
for n in range(N):
P[n], Y[n] = map(int, input().split())
all(nstr.count(c) for c in '753')
# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)
# 2進数のbit判定
(x >> i) & 1
# dp最小化問題
dp = [np.inf]*N
for n in range(N):
if n == 0:
dp[n] = 0
else:
for k in range(1,K+1):
if n-k >= 0:
dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
else:
break
"""
N = int(input())
dp = [[[[0]*4]*4]*4]*(N+1)
dp[0][3][3][3] = 1
mod = 10**9+7
for n in range(N):
for i in range(4):
for j in range(4):
for k in range(4):
for now in range(4):
if now == 0 and i == 1 and j == 2:
continue
if now == 0 and i == 2 and j == 1:
continue
if now == 1 and i == 0 and j == 2:
continue
if now == 0 and i == 3 and j == 1 and k==2:
continue
if now == 0 and i == 1 and j == 3 and k==2:
continue
dp[n+1][now][i][j] = dp[n][i][j][k]
dp[n+1][now][i][j] %= mod
res = 0
for i in range(4):
for j in range(4):
for k in range(4):
res += dp[N][i][j][k]
res %= mod
print(res)
```
No
| 44,481 | [
0.30126953125,
-0.01503753662109375,
-0.1817626953125,
0.31591796875,
-0.459716796875,
-0.39111328125,
0.06793212890625,
0.1739501953125,
0.5380859375,
0.94287109375,
0.5458984375,
-0.177734375,
0.21337890625,
-0.7509765625,
-0.50390625,
0.11553955078125,
-0.414794921875,
-0.786621... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
Submitted Solution:
```
N = int(input())
print((4^N - (len(N)-2)) % (10^9 + 7))
```
No
| 44,482 | [
0.53759765625,
-0.006740570068359375,
-0.0667724609375,
0.32080078125,
-0.43212890625,
-0.453369140625,
0.1517333984375,
0.193115234375,
0.28955078125,
0.92333984375,
0.5693359375,
-0.1595458984375,
0.1552734375,
-0.84375,
-0.439208984375,
0.0650634765625,
-0.406982421875,
-0.79931... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
Submitted Solution:
```
N = input()
X = 16*(N-4)*4**(N-5)+2*(N-2)*4*(N-3)
A = (4**N-X)%(10**9+7)
print(A)
```
No
| 44,483 | [
0.57177734375,
-0.026397705078125,
-0.0740966796875,
0.308349609375,
-0.441162109375,
-0.44384765625,
0.06640625,
0.218505859375,
0.300537109375,
0.95263671875,
0.58154296875,
-0.1163330078125,
0.1966552734375,
-0.88037109375,
-0.387939453125,
0.06390380859375,
-0.452392578125,
-0.... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
Submitted Solution:
```
import itertools
N = int(input())
MOD = 10**9 + 7
ACGT = ["A","C","G","T"]
dp = [ [ [ [0 for l in range(4) ] for k in range(4)] for j in range(4)] for i in range(N+1)]
dp[0][-1][-1][1] = 1
for i,p,q,r,s in itertools.product(range(N),range(4),range(4),range(4),range(4)):
if ACGT[q] + ACGT[r] + ACGT[s] not in {'AGC', 'GAC', 'ACG'} \
and ACGT[p] + ACGT[r] + ACGT[s] != 'AGC' \
and ACGT[p] + ACGT[q] + ACGT[s] != 'AGC':
dp[i + 1][q][r][s] += dp[i][p][q][r]
dp[i + 1][q][r][s] %= MOD
print(dp)
print(sum(sum(sum(y) for y in x) for x in dp[N]) % MOD)
```
No
| 44,484 | [
0.474609375,
-0.10101318359375,
-0.08013916015625,
0.4833984375,
-0.49658203125,
-0.62451171875,
0.04656982421875,
0.1947021484375,
0.35595703125,
0.89111328125,
0.47607421875,
-0.284423828125,
0.095947265625,
-0.94091796875,
-0.3359375,
-0.0670166015625,
-0.481689453125,
-0.739257... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?
Constraints
* 2≦N≦3000
* 1≦M≦3000
* S consists of characters `0` and `1`.
* The length of S equals N.
* 1≦l_i < r_i≦N
* l_i ≦ l_{i+1}
Input
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M
Output
Print the number of the possible values for S after the M operations, modulo 1000000007.
Examples
Input
5 2
01001
2 4
3 5
Output
6
Input
9 3
110111110
1 4
4 6
6 9
Output
26
Input
11 6
00101000110
2 4
2 3
4 7
5 6
6 10
10 11
Output
143
"Correct Solution:
```
"""
Writer: SPD_9X2
https://atcoder.jp/contests/arc065/tasks/arc065_d
圧倒的dp感
lは非減少なので、 l[i-1] ~l[i] の間が確定する範囲
dp[i][今の区間に残っている1の数] = 並び替えの通り数 でやると
dp推移がO(N^2)になってしまう…
1の位置さえ決まればよい。
あらかじめ、それぞれの1に関して、移動しうる最小のindexと最大のindexを前計算
→どうやって?
→heapといもす法で、最小・最大値管理しつつ
あとはdp中に一点取得、区間加算がO(N)で出来れば、O(N**2)で解ける
→dp[i個目までの1を処理][右端にある1のindex]
とし、最後に累積和で区間加算する→DP推移はO(N)なのでおk
→なんか違う?
→1をもってける範囲の右端が実際より短くなっているのが原因
"""
from collections import deque
import heapq
N,M = map(int,input().split())
S = input()
"""
lri = deque([])
rpick = [ [] for i in range(N+1)]
for i in range(M):
l,r = map(int,input().split())
lri.append([l-1,r-1,i])
rpick[r].append(i)
lheap = []
rheap = []
state = [False] * M
LRlis = []
for i in range(N):
while len(lri) > 0 and lri[0][0] == i: #新たに区間を入れる
l,r,ind = lri.popleft()
heapq.heappush(lheap,[l,ind])
heapq.heappush(rheap,[-1*r,ind])
for pickind in rpick[i]:
state[pickind] = True
while len(lheap) > 0 and state[ lheap[0][1] ]:
heapq.heappop(lheap)
while len(rheap) > 0 and state[ rheap[0][1] ]:
heapq.heappop(rheap)
if S[i] == "1":
if len(lheap) == 0 or len(rheap) == 0:
LRlis.append([i,i])
else:
LRlis.append([lheap[0][0] , -1 * rheap[0][0] ])
"""
lri = []
for i in range(M):
l,r = map(int,input().split())
lri.append([l-1,r-1,i])
lri.append([N,float("inf"),float("inf")])
nexvisit = 0
onenum = 0
LRlis = []
LRlisind = 0
r = 0
for loop in range(M):
l,nr,tempi = lri[loop]
r = max(nr,r)
nexl = lri[loop+1][0]
#print (l,r,nexl)
for i in range( max(l,nexvisit) , r+1 ):
if S[i] == "1":
LRlis.append([l,None])
onenum += 1
nexvisit = max(nexvisit,i+1)
if r-nexl+1 < onenum:
for i in range(min(onenum , onenum - (r-nexl+1))):
LRlis[LRlisind][1] = r-onenum+1
onenum -= 1
LRlisind += 1
mod = 10**9+7
dp = [0] * (N+1)
#print (LRlis)
for i in range(len(LRlis)):
#print (dp)
l,r = LRlis[i]
ndp = [0] * (N+1)
if i == 0:
ndp[l] += 1
ndp[r+1] -= 1
else:
for v in range(r):
ndp[max(l,v+1)] += dp[v]
ndp[r+1] -= dp[v]
for j in range(N):
ndp[j+1] += ndp[j]
ndp[j] %= mod
ndp[j+1] % mod
dp = ndp
#print (dp)
print (sum(dp[0:N]) % mod)
```
| 44,540 | [
0.11541748046875,
0.01380157470703125,
-0.1063232421875,
0.0970458984375,
-0.52001953125,
-0.5322265625,
-0.1461181640625,
-0.0007519721984863281,
0.2279052734375,
0.97265625,
0.59375,
-0.094482421875,
0.0257415771484375,
-0.9423828125,
-0.537109375,
0.09051513671875,
-0.58154296875,... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?
Constraints
* 2≦N≦3000
* 1≦M≦3000
* S consists of characters `0` and `1`.
* The length of S equals N.
* 1≦l_i < r_i≦N
* l_i ≦ l_{i+1}
Input
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M
Output
Print the number of the possible values for S after the M operations, modulo 1000000007.
Examples
Input
5 2
01001
2 4
3 5
Output
6
Input
9 3
110111110
1 4
4 6
6 9
Output
26
Input
11 6
00101000110
2 4
2 3
4 7
5 6
6 10
10 11
Output
143
"Correct Solution:
```
#!/usr/bin/env python3
M = 10 ** 9 + 7
def solve(n, m, s, lst):
cnt = [0] * n
t = 0
for i in range(n):
if s[i] == '1':
t += 1
cnt[i] = t
dp = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 1
r = 0
j = 0
for i in range(n):
while j < m:
lj, rj = lst[j]
if lj <= i:
r = max(r, rj)
j += 1
else:
break
if r <= i:
c = cnt[i]
if 0 < c:
dp[i + 1][cnt[i]] = (dp[i][c] + dp[i][c - 1]) % M
else:
dp[i + 1][0] = dp[i][0]
else:
for k in range(max(0, cnt[r] - r + i), min(i + 1, cnt[r]) + 1):
if 0 < k:
dp[i + 1][k] = (dp[i][k] + dp[i][k - 1]) % M
else:
dp[i + 1][0] = dp[i][0]
return dp[n][cnt[n - 1]]
def main():
n, m = input().split()
n = int(n)
m = int(m)
s = input()
lst = []
for _ in range(m):
l, r = input().split()
l = int(l) - 1
r = int(r) - 1
lst.append((l, r))
print(solve(n, m, s, lst))
if __name__ == '__main__':
main()
```
| 44,541 | [
0.1593017578125,
-0.05316162109375,
-0.126953125,
0.12353515625,
-0.45361328125,
-0.5927734375,
-0.06500244140625,
0.12384033203125,
0.1925048828125,
0.9970703125,
0.52587890625,
-0.11053466796875,
0.07147216796875,
-0.99072265625,
-0.46337890625,
0.2154541015625,
-0.6962890625,
-0... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?
Constraints
* 2≦N≦3000
* 1≦M≦3000
* S consists of characters `0` and `1`.
* The length of S equals N.
* 1≦l_i < r_i≦N
* l_i ≦ l_{i+1}
Input
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M
Output
Print the number of the possible values for S after the M operations, modulo 1000000007.
Examples
Input
5 2
01001
2 4
3 5
Output
6
Input
9 3
110111110
1 4
4 6
6 9
Output
26
Input
11 6
00101000110
2 4
2 3
4 7
5 6
6 10
10 11
Output
143
"Correct Solution:
```
mod=10**9+7
N,M=map(int,input().split())
L=-1;R=-1
S=input()
ope=[]
for i in range(M):
l,r=map(int,input().split())
l-=1;r-=1
if L<=l and r<=R:
continue
else:
L,R=l,r
ope.append((l,r))
M=len(ope)
data=[-1]*N
for i in range(M):
l,r=ope[i]
for j in range(l,r+1):
data[j]=i
dp=[[0 for i in range(N+1)] for j in range(N+1)]
for j in range(N+1):
dp[-1][j]=1
for i in range(N-1,-1,-1):
id=data[i]
if id!=-1:
l,r=ope[id]
temp1=sum(int(S[k]) for k in range(r+1))
temp0=r+1-temp1
for j in range(temp1+1):
np1=temp1-j
np0=temp0-(i-j)
if np1==0:
if np0>0:
dp[i][j]=dp[i+1][j]
else:
if np0>0:
dp[i][j]=(dp[i+1][j+1]+dp[i+1][j])%mod
elif np0==0:
dp[i][j]=dp[i+1][j+1]
else:
if S[i]=="1":
for j in range(N):
dp[i][j]=dp[i+1][j+1]
else:
for j in range(N+1):
dp[i][j]=dp[i+1][j]
print(dp[0][0])
```
| 44,542 | [
0.0693359375,
-0.0919189453125,
-0.2056884765625,
0.148193359375,
-0.467041015625,
-0.55712890625,
-0.1680908203125,
0.0369873046875,
0.2467041015625,
0.9853515625,
0.53515625,
-0.085693359375,
0.1300048828125,
-0.904296875,
-0.4921875,
0.212890625,
-0.61376953125,
-0.5791015625,
... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?
Constraints
* 2≦N≦3000
* 1≦M≦3000
* S consists of characters `0` and `1`.
* The length of S equals N.
* 1≦l_i < r_i≦N
* l_i ≦ l_{i+1}
Input
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M
Output
Print the number of the possible values for S after the M operations, modulo 1000000007.
Examples
Input
5 2
01001
2 4
3 5
Output
6
Input
9 3
110111110
1 4
4 6
6 9
Output
26
Input
11 6
00101000110
2 4
2 3
4 7
5 6
6 10
10 11
Output
143
"Correct Solution:
```
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline
n,m = map(int,readline().split())
s = input()
mp = map(int,read().split())
r = list(range(n))
for i,j in zip(mp,mp):
if r[i-1] < j-1:
r[i-1] = j-1
for i in range(1,n):
if r[i] < r[i-1]: r[i] = r[i-1]
zero = [0]*n
one = [0]*n
for i in range(n):
zero[i] = zero[i-1]
one[i] = one[i-1]
if s[i]=="0": zero[i] += 1
else: one[i] += 1
#print(r)
#print(s)
#print(zero)
MOD = 10**9+7
dp = [0]*n
dp[0] = 1
for i in range(n):
L = max(zero[r[i]] + i - r[i],0)
R = min(zero[r[i]],i+1)
ndp = [0]*n
for i in range(L,R+1):
if i: ndp[i] += dp[i-1]
ndp[i] += dp[i]
ndp[i] %= MOD
dp = ndp
#print(L,R,r[i],zero[r[i]],dp)
print(sum(dp))
```
| 44,543 | [
0.10955810546875,
-0.08245849609375,
-0.231689453125,
0.0218963623046875,
-0.59765625,
-0.55078125,
-0.1192626953125,
0.1126708984375,
0.0975341796875,
1.0927734375,
0.54150390625,
-0.05743408203125,
0.2078857421875,
-0.87744140625,
-0.454833984375,
0.06829833984375,
-0.58984375,
-... | 0 |
Provide a correct Python 3 solution for this coding contest problem.
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?
Constraints
* 2≦N≦3000
* 1≦M≦3000
* S consists of characters `0` and `1`.
* The length of S equals N.
* 1≦l_i < r_i≦N
* l_i ≦ l_{i+1}
Input
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M
Output
Print the number of the possible values for S after the M operations, modulo 1000000007.
Examples
Input
5 2
01001
2 4
3 5
Output
6
Input
9 3
110111110
1 4
4 6
6 9
Output
26
Input
11 6
00101000110
2 4
2 3
4 7
5 6
6 10
10 11
Output
143
"Correct Solution:
```
import sys
readline = sys.stdin.readline
MOD = 10**9+7
N, M = map(int, readline().split())
S = list(map(int, readline().strip()))
Query = [tuple(map(lambda x: int(x) - 1, readline().split())) for _ in range(M)]
PP = S.count(1)
Li = [None]*PP
Ri = [None]*PP
T1 = S[:]
for l, r in Query:
cnt = 0
for i in range(l, r+1):
cnt += T1[i]
for i in range(l, l+cnt):
T1[i] = 1
for i in range(l+cnt, r+1):
T1[i] = 0
T2 = S[:]
for l, r in Query:
cnt = 0
for i in range(l, r+1):
cnt += 1 - T2[i]
for i in range(l, l+cnt):
T2[i] = 0
for i in range(l+cnt, r+1):
T2[i] = 1
cnt = 0
for i in range(N):
if T1[i]:
Li[cnt] = i
cnt += 1
cnt = 0
for i in range(N):
if T2[i]:
Ri[cnt] = i+1
cnt += 1
dp = [0]*N
for i in range(Li[0], Ri[0]):
dp[i] = 1
for j in range(1, PP):
dp2 = [0] + dp[:-1]
for i in range(1, N):
dp2[i] = (dp2[i]+dp2[i-1])%MOD
for i in range(Li[j]):
dp2[i] = 0
for i in range(Ri[j], N):
dp2[i] = 0
dp = dp2[:]
res = 0
for d in dp:
res = (res+d)%MOD
print(res)
```
| 44,544 | [
0.113525390625,
-0.074462890625,
-0.25537109375,
0.0771484375,
-0.6494140625,
-0.54248046875,
-0.1424560546875,
0.062469482421875,
0.13916015625,
1.0869140625,
0.63720703125,
-0.0611572265625,
0.058349609375,
-0.892578125,
-0.525390625,
0.20263671875,
-0.6513671875,
-0.650390625,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?
Constraints
* 2≦N≦3000
* 1≦M≦3000
* S consists of characters `0` and `1`.
* The length of S equals N.
* 1≦l_i < r_i≦N
* l_i ≦ l_{i+1}
Input
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M
Output
Print the number of the possible values for S after the M operations, modulo 1000000007.
Examples
Input
5 2
01001
2 4
3 5
Output
6
Input
9 3
110111110
1 4
4 6
6 9
Output
26
Input
11 6
00101000110
2 4
2 3
4 7
5 6
6 10
10 11
Output
143
Submitted Solution:
```
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n+1)]
self.rank = [0] * (n+1)
self.size = [1] * (n+1)
# 譬ケ繧呈、懃エ「縺吶k髢「謨ー
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.find(self.par[x])
# 邨仙粋(unite)縺吶k髢「謨ー
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.rank[x] < self.rank[y]:
self.par[x] = y
self.size[y] += self.size[x]
else:
self.par[y] = x
self.size[x] += self.size[y]
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
# 蜷後§繧ー繝ォ繝シ繝励↓螻槭☆繧九°繧貞愛螳壹☆繧矩未謨ー
def same_check(self, x, y):
return self.find(x) == self.find(y)
# 隕∫エ縺悟ア槭☆繧区惠縺ョ豺ア縺輔r霑斐☆髢「謨ー
def get_depth(self, x):
return self.rank[self.find(x)]
# 隕∫エ縺悟ア槭☆繧区惠縺ョ繧オ繧、繧コ繧定ソ斐☆髢「謨ー
def get_size(self, x):
return self.size[self.find(x)]
# 繧ー繝ォ繝シ繝玲焚繧定ソ斐☆髢「謨ー
def group_sum(self):
c = 0
for i in range(len(self.par)):
if self.find(i) == i:
c += 1
return c
if __name__ == "__main__":
N,K,L = map(int, input().split())
uf = UnionFind(N)
for i in range(K):
p, q = [int(i) for i in input().split()]
uf.unite(p, q)
ans = [1]*N
for i in range(L):
r, s = [int(i) for i in input().split()]
if uf.same_check(r, s):
ans[r-1] += 1
ans[s-1] += 1
print(*ans)
```
No
| 44,545 | [
0.307373046875,
-0.31396484375,
-0.1331787109375,
0.1790771484375,
-0.4873046875,
-0.339599609375,
0.05047607421875,
0.1387939453125,
0.402099609375,
0.87158203125,
0.9150390625,
-0.0130157470703125,
0.047393798828125,
-0.919921875,
-0.318603515625,
0.0240478515625,
-0.3564453125,
... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?
Constraints
* 2≦N≦3000
* 1≦M≦3000
* S consists of characters `0` and `1`.
* The length of S equals N.
* 1≦l_i < r_i≦N
* l_i ≦ l_{i+1}
Input
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M
Output
Print the number of the possible values for S after the M operations, modulo 1000000007.
Examples
Input
5 2
01001
2 4
3 5
Output
6
Input
9 3
110111110
1 4
4 6
6 9
Output
26
Input
11 6
00101000110
2 4
2 3
4 7
5 6
6 10
10 11
Output
143
Submitted Solution:
```
#include <bits/stdc++.h>
using namespace std;
const int MOD = (int)1e9 + 7;
int add(int x, int y) {
x += y;
if (x >= MOD) return x - MOD;
return x;
}
int sub(int x, int y) {
x -= y;
if (x < 0) return x + MOD;
return x;
}
int mult(int x, int y) { return ((long long)x * y) % MOD; }
const int N = 3030;
int n;
char s[N];
int a[N];
int b[N];
int dp[N][N];
int C[N][N];
void read() {
int m;
scanf("%d%d", &n, &m);
scanf(" %s ", s);
for (int i = 0; i < n; i++) a[i] = (int)(s[i] - '0');
for (int i = 0; i < n; i++) b[i] = i + 1;
while (m--) {
int l, r;
scanf("%d%d", &l, &r);
l--;
b[l] = max(b[l], r);
}
for (int i = 1; i < n; i++) b[i] = max(b[i], b[i - 1]);
}
int main() {
read();
for (int i = 0; i < N; i++) C[i][0] = C[i][i] = 1;
for (int i = 1; i < N; i++)
for (int j = 1; j < i; j++) C[i][j] = add(C[i - 1][j], C[i - 1][j - 1]);
dp[0][0] = 1;
int cur = 0;
for (int i = 0; i < n; i++) {
int willAdd = 0;
while (cur < b[i]) {
willAdd += a[cur];
cur++;
}
for (int x = 0; x <= n; x++) {
if (dp[i][x] == 0) continue;
int y = x + willAdd;
if (y != 0) dp[i + 1][y - 1] = add(dp[i + 1][y - 1], dp[i][x]);
if (y != cur - i) dp[i + 1][y] = add(dp[i + 1][y], dp[i][x]);
}
}
printf("%d\n", dp[n][0]);
return 0;
}
```
No
| 44,546 | [
0.240234375,
-0.22900390625,
-0.08062744140625,
0.1968994140625,
-0.546875,
-0.383056640625,
-0.094970703125,
0.099365234375,
0.064208984375,
1.0849609375,
0.65966796875,
-0.126953125,
0.08856201171875,
-0.93115234375,
-0.417724609375,
0.05523681640625,
-0.49609375,
-0.69873046875,... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?
Constraints
* 2≦N≦3000
* 1≦M≦3000
* S consists of characters `0` and `1`.
* The length of S equals N.
* 1≦l_i < r_i≦N
* l_i ≦ l_{i+1}
Input
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M
Output
Print the number of the possible values for S after the M operations, modulo 1000000007.
Examples
Input
5 2
01001
2 4
3 5
Output
6
Input
9 3
110111110
1 4
4 6
6 9
Output
26
Input
11 6
00101000110
2 4
2 3
4 7
5 6
6 10
10 11
Output
143
Submitted Solution:
```
#!/usr/bin/env python3
M = 10 ** 9 + 7
def solve(n, m, s, lst):
cnt = [0] * n
t = 0
for i in range(n):
if s[i] == '1':
t += 1
cnt[i] = t
dp = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 1
r = 0
j = 0
for i in range(n):
while j < m:
lj, rj = lst[j]
if lj <= i:
r = max(r, rj)
j += 1
else:
break
if r <= i:
c = cnt[i]
if 0 < c:
dp[i + 1][cnt[i]] = dp[i][c] + dp[i][c - 1]
else:
dp[i + 1][0] = dp[i][0]
else:
for k in range(max(0, cnt[r] - r + i), min(i + 1, cnt[r]) + 1):
if 0 < k:
dp[i + 1][k] = dp[i][k] + dp[i][k - 1]
else:
dp[i + 1][0] = dp[i][0]
return dp[n][cnt[n - 1]]
def main():
n, m = input().split()
n = int(n)
m = int(m)
s = input()
lst = []
for _ in range(m):
l, r = input().split()
l = int(l) - 1
r = int(r) - 1
lst.append((l, r))
print(solve(n, m, s, lst))
if __name__ == '__main__':
main()
```
No
| 44,547 | [
0.2196044921875,
-0.11224365234375,
-0.143798828125,
0.18359375,
-0.51953125,
-0.488525390625,
-0.06256103515625,
0.08154296875,
0.2139892578125,
1.0009765625,
0.54638671875,
-0.080078125,
0.0148162841796875,
-0.89306640625,
-0.53662109375,
0.1072998046875,
-0.5791015625,
-0.577636... | 0 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m:
* Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character.
Here, the sequence l_i is non-decreasing.
How many values are possible for S after the M operations, modulo 1000000007(= 10^9+7)?
Constraints
* 2≦N≦3000
* 1≦M≦3000
* S consists of characters `0` and `1`.
* The length of S equals N.
* 1≦l_i < r_i≦N
* l_i ≦ l_{i+1}
Input
The input is given from Standard Input in the following format:
N M
S
l_1 r_1
:
l_M r_M
Output
Print the number of the possible values for S after the M operations, modulo 1000000007.
Examples
Input
5 2
01001
2 4
3 5
Output
6
Input
9 3
110111110
1 4
4 6
6 9
Output
26
Input
11 6
00101000110
2 4
2 3
4 7
5 6
6 10
10 11
Output
143
Submitted Solution:
```
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline
n,m = map(int,readline().split())
s = input()
mp = map(int,read().split())
r = [0]*n
for i,j in zip(mp,mp):
if r[i-1] < j-1:
r[i-1] = j-1
for i in range(1,n):
if r[i] < r[i-1]: r[i] = r[i-1]
zero = [0]*n
for i in range(n):
zero[i] = zero[i-1]
if s[i]=="0": zero[i] += 1
#print(r)
#print(s)
#print(zero)
MOD = 10**9+7
dp = [0]*n
dp[0] = 1
for i in range(n):
L = max(zero[r[i]] + i - r[i],0)
R = min(zero[r[i]],i+1)
ndp = [0]*n
for i in range(L,R+1):
if i: ndp[i] += dp[i-1]
ndp[i] += dp[i]
ndp[i] %= MOD
dp = ndp
#print(L,R,r[i],zero[r[i]],dp)
print(sum(dp)%MOD)
```
No
| 44,548 | [
0.1885986328125,
-0.1029052734375,
-0.1588134765625,
0.035491943359375,
-0.59130859375,
-0.5302734375,
-0.09130859375,
0.0654296875,
0.06884765625,
1.1826171875,
0.53125,
-0.05950927734375,
0.130859375,
-0.8505859375,
-0.459716796875,
0.045928955078125,
-0.43896484375,
-0.669433593... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Tags: brute force, greedy, strings
Correct Solution:
```
st = input().rstrip()
a = []
for item in st:
a.append(int(item))
a.reverse()
zero_count = 0
for i, item in enumerate(a):\
#huaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#where all this peps got this kind of solutionnnnnnnnnn
#huaawdkaowkdoakwdoj
#zsevorinpunu8opzersvnopsvzerveorunppioupenirszuinorpsuozserinpvnopugiyuoprgeinwpuirzsdtgnopuvxynpozsdrtuoprtudsz
if item == 0:
zero_count += 1
elif zero_count > 0:
zero_count -= 1
else:
a[i] = 0
#print(i,item,zero_count)
a.reverse()
print("".join([str(item) for item in a]))
```
| 44,677 | [
0.166259765625,
-0.1513671875,
0.1531982421875,
0.256591796875,
-0.177001953125,
-0.65625,
-0.13671875,
-0.112548828125,
0.08734130859375,
1.0966796875,
0.58349609375,
-0.1402587890625,
0.412109375,
-1.0849609375,
-0.64306640625,
-0.061614990234375,
-0.1573486328125,
-0.67138671875... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Tags: brute force, greedy, strings
Correct Solution:
```
s = list(map(int, input()))
ps = [0]
for i in s:
if i == 0:
ps.append(ps[-1] + 1)
else:
ps.append(ps[-1] - 1)
b = 0
maba = 0
sufmax = [-10 ** 9]
for i in range(len(ps) - 1, 0, -1):
sufmax.append(max(sufmax[-1], ps[i]))
sufmax = sufmax[::-1]
ans = []
cnt = 0
if s[0] == 1:
cnt += 1
else:
ans.append('0')
for i in range(1, len(s)):
if s[i] == 0 and s[i - 1] == 0:
ans.append('0')
elif s[i] == 1:
cnt += 1
else:
maba = sufmax[i] - ps[i]
maba = min(maba, cnt)
for _ in range(cnt - maba):
ans.append('0')
for _ in range(maba):
ans.append('1')
cnt = 0
ans.append('0')
for _ in range(len(s) - len(ans)):
ans.append('0')
print(''.join(ans))
```
| 44,678 | [
0.166259765625,
-0.1513671875,
0.1531982421875,
0.256591796875,
-0.177001953125,
-0.65625,
-0.13671875,
-0.112548828125,
0.08734130859375,
1.0966796875,
0.58349609375,
-0.1402587890625,
0.412109375,
-1.0849609375,
-0.64306640625,
-0.061614990234375,
-0.1573486328125,
-0.67138671875... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Tags: brute force, greedy, strings
Correct Solution:
```
# -*- coding: utf-8 -*-
# @Date : 2019-08-21 13:24:15
# @Author : raj lath (oorja.halt@gmail.com)
# @Link : link
# @Version : 1.0.0
import sys
sys.setrecursionlimit(10**5+1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
given = input()[::-1]
zeros = 0
lens = len(given)
rets = ''
for i in range(lens):
if given[i] == '0':
zeros += 1
rets += '0'
elif zeros > 0:
zeros -= 1
rets += "1"
else:
rets += '0'
rets = rets[::-1]
print(rets)
```
| 44,679 | [
0.166259765625,
-0.1513671875,
0.1531982421875,
0.256591796875,
-0.177001953125,
-0.65625,
-0.13671875,
-0.112548828125,
0.08734130859375,
1.0966796875,
0.58349609375,
-0.1402587890625,
0.412109375,
-1.0849609375,
-0.64306640625,
-0.061614990234375,
-0.1573486328125,
-0.67138671875... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Tags: brute force, greedy, strings
Correct Solution:
```
s = str(input().strip())
t = list(s[::-1])
cnt = 0
for i,v in enumerate(t):
if v == '0':
cnt += 1
else:
if cnt:
cnt -= 1
else:
t[i] = '0'
print("".join(t[::-1]))
```
| 44,680 | [
0.166259765625,
-0.1513671875,
0.1531982421875,
0.256591796875,
-0.177001953125,
-0.65625,
-0.13671875,
-0.112548828125,
0.08734130859375,
1.0966796875,
0.58349609375,
-0.1402587890625,
0.412109375,
-1.0849609375,
-0.64306640625,
-0.061614990234375,
-0.1573486328125,
-0.67138671875... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Tags: brute force, greedy, strings
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=998244353
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
s = [int(i) for i in input()]
n = len(s)
ans = [0]*n
have = 0
for i in range(n-1,-1,-1):
if(not s[i]): have += 1
else:
if(have):
have -= 1
ans[i] = 1
print(*ans,sep="")
```
| 44,681 | [
0.166259765625,
-0.1513671875,
0.1531982421875,
0.256591796875,
-0.177001953125,
-0.65625,
-0.13671875,
-0.112548828125,
0.08734130859375,
1.0966796875,
0.58349609375,
-0.1402587890625,
0.412109375,
-1.0849609375,
-0.64306640625,
-0.061614990234375,
-0.1573486328125,
-0.67138671875... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Tags: brute force, greedy, strings
Correct Solution:
```
a=input()
a=list(a)
l=[]
for i in range(0,len(a)):
l.append([a[i],i])
i=1
while(i<len(l)):
if l[i][0]=='0' and l[i-1][0]=='1':
l.pop(i)
l.pop(i-1)
i-=2
if i==-1:
i=0
i+=1
for i in range(0,len(l)):
a[l[i][1]]=0
print (*a,sep="")
```
| 44,682 | [
0.166259765625,
-0.1513671875,
0.1531982421875,
0.256591796875,
-0.177001953125,
-0.65625,
-0.13671875,
-0.112548828125,
0.08734130859375,
1.0966796875,
0.58349609375,
-0.1402587890625,
0.412109375,
-1.0849609375,
-0.64306640625,
-0.061614990234375,
-0.1573486328125,
-0.67138671875... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Tags: brute force, greedy, strings
Correct Solution:
```
s = input()
res = ["0"]*len(s)
min_dif = 0
length = len(s)
for i in range(length):
if s[length-i-1] == "0":
min_dif = min([-1, min_dif-1])
else:
if min_dif < 0: res[length-i-1] = "1"
min_dif = min([1, min_dif+1])
print("".join(res))
```
| 44,683 | [
0.166259765625,
-0.1513671875,
0.1531982421875,
0.256591796875,
-0.177001953125,
-0.65625,
-0.13671875,
-0.112548828125,
0.08734130859375,
1.0966796875,
0.58349609375,
-0.1402587890625,
0.412109375,
-1.0849609375,
-0.64306640625,
-0.061614990234375,
-0.1573486328125,
-0.67138671875... | 0 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following conditions:
* For any l and r (1 ≤ l ≤ r ≤ n) the length of the longest non-decreasing subsequence of the substring s_{l}s_{l+1} … s_{r} is equal to the length of the longest non-decreasing subsequence of the substring t_{l}t_{l+1} … t_{r};
* The number of zeroes in t is the maximum possible.
A non-decreasing subsequence of a string p is a sequence of indices i_1, i_2, …, i_k such that i_1 < i_2 < … < i_k and p_{i_1} ≤ p_{i_2} ≤ … ≤ p_{i_k}. The length of the subsequence is k.
If there are multiple substrings which satisfy the conditions, output any.
Input
The first line contains a binary string of length not more than 2\: 000.
Output
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
Examples
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
Note
In the first example:
* For the substrings of the length 1 the length of the longest non-decreasing subsequnce is 1;
* For l = 1, r = 2 the longest non-decreasing subsequnce of the substring s_{1}s_{2} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{2} is 01;
* For l = 1, r = 3 the longest non-decreasing subsequnce of the substring s_{1}s_{3} is 11 and the longest non-decreasing subsequnce of the substring t_{1}t_{3} is 00;
* For l = 2, r = 3 the longest non-decreasing subsequnce of the substring s_{2}s_{3} is 1 and the longest non-decreasing subsequnce of the substring t_{2}t_{3} is 1;
The second example is similar to the first one.
Tags: brute force, greedy, strings
Correct Solution:
```
''' Hey stalker :) '''
INF = 10**10
def main():
print = out.append
''' Cook your dish here! '''
st = list(input())
stk = []
for index, i in enumerate(st):
if i=='0' and len(stk)>0 and stk[-1][0]=='1':
stk.pop()
else: stk.append([i, index])
for li in stk:
st[li[1]] = '0'
print("".join(st))
''' Pythonista fLite 1.1 '''
import sys
#from collections import defaultdict, Counter
#from bisect import bisect_left, bisect_right
#from functools import reduce
#import math
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda: int(input())
get_list = lambda: list(map(int, input().split()))
main()
#[main() for _ in range(int(input()))]
print(*out, sep='\n')
```
| 44,684 | [
0.166259765625,
-0.1513671875,
0.1531982421875,
0.256591796875,
-0.177001953125,
-0.65625,
-0.13671875,
-0.112548828125,
0.08734130859375,
1.0966796875,
0.58349609375,
-0.1402587890625,
0.412109375,
-1.0849609375,
-0.64306640625,
-0.061614990234375,
-0.1573486328125,
-0.67138671875... | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.