message stringlengths 2 23.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 97 109k | cluster float64 0 0 | __index_level_0__ int64 194 217k |
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
Evaluate all possible formulas, and print the sum of the results.
Constraints
* 1 \leq |S| \leq 10
* All letters in S are digits between `1` and `9`, inclusive.
Input
The input is given from Standard Input in the following format:
S
Output
Print the sum of the evaluated value over all possible formulas.
Examples
Input
125
Output
176
Input
9999999999
Output
12656242944 | instruction | 0 | 95,968 | 0 | 191,936 |
"Correct Solution:
```
s = input()
n = len(s)
ans = 0
for i in range(2**(n-1)):
key = ""
for j in range(n-1):
key = key + s[j]
if (i>>j)&1:
key = key + "+"
key = key + s[n-1]
ans += eval(key)
print(ans)
``` | output | 1 | 95,968 | 0 | 191,937 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
Evaluate all possible formulas, and print the sum of the results.
Constraints
* 1 \leq |S| \leq 10
* All letters in S are digits between `1` and `9`, inclusive.
Input
The input is given from Standard Input in the following format:
S
Output
Print the sum of the evaluated value over all possible formulas.
Examples
Input
125
Output
176
Input
9999999999
Output
12656242944 | instruction | 0 | 95,969 | 0 | 191,938 |
"Correct Solution:
```
S = input()
L = len(S)-1
a = 0
for i in range(2**L):
T = S[0]
for j in range(L):
T+=(i>>j&1)*"+"+S[1+j]
a+=eval(T)
print(a)
``` | output | 1 | 95,969 | 0 | 191,939 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
Evaluate all possible formulas, and print the sum of the results.
Constraints
* 1 \leq |S| \leq 10
* All letters in S are digits between `1` and `9`, inclusive.
Input
The input is given from Standard Input in the following format:
S
Output
Print the sum of the evaluated value over all possible formulas.
Examples
Input
125
Output
176
Input
9999999999
Output
12656242944 | instruction | 0 | 95,970 | 0 | 191,940 |
"Correct Solution:
```
s = input()
ans = 0
for i in range(2**(len(s)-1)):
t = 0
for j in range(len(s)-1):
if (i >> j)&1:
ans += int(s[t:j+1])
t = j+1
ans += int(s[t:])
print(ans)
``` | output | 1 | 95,970 | 0 | 191,941 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
Evaluate all possible formulas, and print the sum of the results.
Constraints
* 1 \leq |S| \leq 10
* All letters in S are digits between `1` and `9`, inclusive.
Input
The input is given from Standard Input in the following format:
S
Output
Print the sum of the evaluated value over all possible formulas.
Examples
Input
125
Output
176
Input
9999999999
Output
12656242944 | instruction | 0 | 95,971 | 0 | 191,942 |
"Correct Solution:
```
s = input()
l = len(s)
def dfs(i, f):
if i == l - 1:
return sum(list(map(int, f.split('+'))))
return dfs(i + 1, f + s[i + 1]) + dfs(i + 1, f + '+' + s[i + 1])
print(dfs(0, s[0]))
``` | output | 1 | 95,971 | 0 | 191,943 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
Evaluate all possible formulas, and print the sum of the results.
Constraints
* 1 \leq |S| \leq 10
* All letters in S are digits between `1` and `9`, inclusive.
Input
The input is given from Standard Input in the following format:
S
Output
Print the sum of the evaluated value over all possible formulas.
Examples
Input
125
Output
176
Input
9999999999
Output
12656242944 | instruction | 0 | 95,972 | 0 | 191,944 |
"Correct Solution:
```
s=input()
l=len(s)
def dfs(i,f):
if i==l-1:
return eval(f)
else:
return dfs(i+1, f+s[i+1]) + dfs(i+1,f+'+'+s[i+1])
print(dfs(0,s[0]))
``` | output | 1 | 95,972 | 0 | 191,945 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
Evaluate all possible formulas, and print the sum of the results.
Constraints
* 1 \leq |S| \leq 10
* All letters in S are digits between `1` and `9`, inclusive.
Input
The input is given from Standard Input in the following format:
S
Output
Print the sum of the evaluated value over all possible formulas.
Examples
Input
125
Output
176
Input
9999999999
Output
12656242944 | instruction | 0 | 95,973 | 0 | 191,946 |
"Correct Solution:
```
S = input()
def func(S, i):
if len(S) <= i:
return eval(S)
S1 = S[:i] + '+' + S[i:]
return func(S, i + 1) + func(S1, i + 2)
print(func(S, 1))
``` | output | 1 | 95,973 | 0 | 191,947 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6 | instruction | 0 | 96,205 | 0 | 192,410 |
Tags: data structures
Correct Solution:
```
# 1234D. Distinct Characters Queries
import sys
input = sys.stdin.readline
class SegmentTree:
def __init__(
self,
init_val: "initial value: Array or str",
segfunc: "operation unique in case",
ide_ele: "identity element corresponding init_val" = 0,
):
self.segfunc = segfunc
self.size = 1 << (len(init_val) - 1).bit_length()
self.ide_ele = ide_ele
self.tree = self._build(init_val)
def _build(self, init_val: "Array or str"):
tree = [self.ide_ele] * (2 * self.size)
for idx, val in enumerate(init_val): # set
# modify val if needed (e.g. str -> ord())
val = 1 << (ord(val) - 97)
tree[idx + self.size - 1] = val
for idx in range(self.size - 2, -1, -1): # build
tree[idx] = self.segfunc(tree[2 * idx + 1], tree[2 * idx + 2])
return tree
def update(self, idx: int, val):
idx += self.size - 1
# modify val if needed as same as in _build()
val = 1 << (ord(val) - 97)
self.tree[idx] = val
while idx > 0:
idx = (idx - 1) // 2
self.tree[idx] = self.segfunc(
self.tree[2 * idx + 1], self.tree[2 * idx + 2]
)
def query(self, left: int, right: int):
if left >= right:
return self.ide_ele
left += self.size
right += self.size
ret = self.ide_ele
while left < right:
if left & 1:
ret = self.segfunc(ret, self.tree[left - 1])
left += 1
if right & 1:
right -= 1
ret = self.segfunc(ret, self.tree[right - 1])
left >>= 1
right >>= 1
return ret
def main():
S = input().rstrip()
Q = int(input())
queries = tuple(input().split() for _ in range(Q))
segfunc = lambda x, y: x | y
seg = SegmentTree(S, segfunc)
ans = []
for q_type, var1, var2 in queries:
if q_type == "1":
idx, char = int(var1) - 1, var2
seg.update(idx, char)
else:
left, right = int(var1) - 1, int(var2) # [left, right)
x = seg.query(left, right)
cnt = bin(x).count("1")
ans.append(cnt)
print("\n".join(map(str, ans)))
if __name__ == "__main__":
main()
``` | output | 1 | 96,205 | 0 | 192,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6 | instruction | 0 | 96,206 | 0 | 192,412 |
Tags: data structures
Correct Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
from copy import deepcopy
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split()))
def inps(): return sys.stdin.readline()
def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x])
def err(x): print(x); exit()
import sys
input = sys.stdin.readline
def solve():
ordA = ord('a')
# N = int(input())
Ss = input().rstrip()
N = len(Ss)
Q = int(input())
querys = [tuple(input().split()) for _ in range(Q)]
idEle = 0
def _binOpe(x, y):
return x | y
def makeSegTree(numEle):
numPow2 = 2 ** (numEle-1).bit_length()
data = [idEle] * (2*numPow2)
return data, numPow2
def setInit(As):
for iST, A in enumerate(As, numPow2):
data[iST] = A
for iST in reversed(range(1, numPow2)):
data[iST] = _binOpe(data[2*iST], data[2*iST+1])
def _update1(iA, A):
iST = iA + numPow2
data[iST] = A
def update(iA, A):
_update1(iA, A)
iST = iA + numPow2
while iST > 1:
iST >>= 1
data[iST] = _binOpe(data[2*iST], data[2*iST+1])
def getValue(iSt, iEn):
L = iSt + numPow2
R = iEn + numPow2
ans = idEle
while L < R:
if L & 1:
ans = _binOpe(ans, data[L])
L += 1
if R & 1:
R -= 1
ans = _binOpe(ans, data[R])
L >>= 1
R >>= 1
return ans
data, numPow2 = makeSegTree(N)
As = [(1<<(ord(S)-ordA)) for S in Ss]
setInit(As)
anss = []
for tp, *vs in querys:
if tp == '1':
i, c = vs
i = int(i)
update(i-1, 1<<(ord(c)-ordA))
else:
L, R = vs
L, R = int(L), int(R)
v = getValue(L-1, R)
anss.append(bin(v).count('1'))
print('\n'.join(map(str, anss)))
solve()
``` | output | 1 | 96,206 | 0 | 192,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6 | instruction | 0 | 96,207 | 0 | 192,414 |
Tags: data structures
Correct Solution:
```
import heapq
import math
import sys
input = sys.stdin.readline
def li():return [int(i) for i in input().rstrip('\n').split()]
def value():return int(input())
def givesum(a,b):
c=[0]*26
for i in range(len(a)):
c[i] = a[i]+b[i]
return c
def dolist(a):
c = [0]*26
c[ord(a)-ord('a')] = 1
return c
class Node:
def __init__(self,s,e):
self.start=s
self.end=e
self.lis=[0]*26
self.left=None
self.right=None
def build(nums,l,r):
if l == r:
temp = Node(l,l)
# print(temp.start,ord(nums[l])-ord('a'),nums)
temp.lis[ord(nums[l])-ord('a')] = 1
else:
mid=(l+r)>>1
# print(mid,l,r)
temp=Node(l,r)
temp.left=build(nums,l,mid)
temp.right=build(nums,mid+1,r)
temp.lis=givesum(temp.left.lis,temp.right.lis)
return temp
def update(root,start,value):
if root.start==root.end==start:
root.lis=dolist(value)
elif root.start<=start and root.end>=start:
mid=(root.start+root.end)>>1
root.left=update(root.left,start,value)
root.right=update(root.right,start,value)
root.lis=givesum(root.left.lis,root.right.lis)
return root
def query(root,start,end):
if root.start>=start and root.end<=end:return root.lis
elif root.start>end or root.end<start:return [0]*26;
else:
mid=(start+end)>>1
return givesum(query(root.left,start,end),query(root.right,start,end))
s = input().rstrip('\n')
root = build(s,0,len(s)-1)
ansarun = []
# print('arun')
for _ in range(int(input())):
templist = list(input().split())
if templist[0] == '1':
root = update(root,int(templist[1])-1,templist[2])
else:
temp1 = query(root,int(templist[1])-1,int(templist[2])-1)
total = 0
for i in temp1:
if i:total+=1
ansarun.append(total)
for i in ansarun:print(i)
``` | output | 1 | 96,207 | 0 | 192,415 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6 | instruction | 0 | 96,208 | 0 | 192,416 |
Tags: data structures
Correct Solution:
```
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
class OrderedList(SortedList): #Codeforces, Ordered Multiset
def __init__(self, arg):
super().__init__(arg)
def rangeCountByValue(self, leftVal, rightVal): #returns number of items in range [leftVal,rightVal] inclusive
leftCummulative = self.bisect_left(leftVal)
rightCummulative = self.bisect_left(rightVal + 1)
return rightCummulative - leftCummulative
def charToInt(c): #'a'->0
return ord(c)-ord('a')
def intToChar(x): #0->'a'
return chr(ord('a')+x)
def main():
s=input()
n=len(s)
arr=[charToInt(c) for c in s]
olArr=[OrderedList([]) for _ in range(26)]
for i in range(n):
olArr[arr[i]].add(i)
q=int(input())
allans=[]
for _ in range(q):
typee,x,y=input().split()
if typee=='1':
replaceIdx=int(x)-1
replaceChar=charToInt(y)
prevChar=arr[replaceIdx]
olArr[prevChar].remove(replaceIdx)
olArr[replaceChar].add(replaceIdx)
arr[replaceIdx]=replaceChar
else:
l=int(x)-1
r=int(y)-1
cnt=0
for i in range(26):
left=olArr[i].bisect_left(l)
right=olArr[i].bisect_right(r)
if left<right:
cnt+=1
allans.append(cnt)
multiLineArrayPrint(allans)
return
import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(i,j):
print('? {} {}'.format(i,j))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(' '.join([str(x) for x in ans])))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main()
``` | output | 1 | 96,208 | 0 | 192,417 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6 | instruction | 0 | 96,209 | 0 | 192,418 |
Tags: data structures
Correct Solution:
```
import sys
input = sys.stdin.readline
class SegmentTree:
a = ord('a')
def __init__(self):
data = [1 << ord(c) - self.a for c in input()[:-1]]
self.n = 1 << len(bin(len(data) - 1)) - 2
self.data = [0] * self.n + data + [0] * (self.n - len(data))
for k in range(self.n - 1, 0, -1):
self.data[k] = self.data[2 * k + 1] | self.data[2 * k]
def update(self, k, c):
k += self.n
self.data[k] = 1 << ord(c) - self.a
while k > 1:
k >>= 1
self.data[k] = self.data[2 * k + 1] | self.data[2 * k]
def query(self, l, r):
l += self.n
r += self.n
s = self.data[r] | self.data[l]
while l < r - 1:
if r & 1: s |= self.data[r - 1]
if not l & 1: s |= self.data[l + 1]
l >>= 1
r >>= 1
return s
tree = SegmentTree()
for i in range(int(input())):
q = input()[:-1].split()
if q[0] == "1":
tree.update(int(q[1]) - 1, q[2])
else:
s = tree.query(int(q[1]) - 1, int(q[2]) - 1)
print(bin(s)[2:].count("1"))
``` | output | 1 | 96,209 | 0 | 192,419 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6 | instruction | 0 | 96,210 | 0 | 192,420 |
Tags: data structures
Correct Solution:
```
import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
class SegTree:
# limit for array size
N = 100002
def __init__(self):
self.tree = [0] * (2 * self.N)
# function to build the tree
def build(self, arr):
# insert leaf nodes in tree
for i in range(n):
self.tree[n + i] = arr[i]
# build the tree by calculating parents
for i in range(n - 1, 0, -1):
self.tree[i] = self.tree[i << 1] + self.tree[i << 1 | 1]
# function to update a tree node
def update_tree_node(self, p, value):
# set value at position p
self.tree[p + n] = value
p = p + n
# move upward and update parents
i = p
while i > 1:
self.tree[i >> 1] = self.tree[i] + self.tree[i ^ 1]
i >>= 1
# function to get sum on interval [l, r)
def query(self, l, r):
res = 0
# loop to find the sum in the range
l += n
r += n
while l < r:
if l & 1:
res += self.tree[l]
l += 1
if r & 1:
r -= 1
res += self.tree[r]
l >>= 1
r >>= 1
return res
if __name__ == "__main__":
s = list(input())
n = len(s)
trees = []
for i in range(26):
trees.append(SegTree())
trees[-1].build([0] * n)
for idx, c in enumerate(s):
trees[ord(c) - ord('a')].update_tree_node(idx, 1)
t = int(input())
for _ in range(t):
q, p1, p2 = input().split()
q, p1 = int(q), int(p1) - 1
if q == 1:
trees[ord(s[p1]) - ord('a')].update_tree_node(p1, 0)
trees[ord(p2) - ord('a')].update_tree_node(p1, 1)
s[p1] = p2
else:
p2 = int(p2) - 1
ans = 0
for seg in trees:
if seg.query(p1, p2 + 1) != 0:
ans += 1
print(ans)
``` | output | 1 | 96,210 | 0 | 192,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6 | instruction | 0 | 96,211 | 0 | 192,422 |
Tags: data structures
Correct Solution:
```
class SegmentTree:
def __init__(self, n):
self.n = 2**(n-1).bit_length()
self.data = [0 for _ in range(2*self.n)]
def build(self, arr):
for i in range(len(arr)):
self.data[self.n+i] = 1<<arr[i]
for i in range(self.n-1, 0, -1):
self.data[i] = self.data[i<<1] | self.data[i<<1 | 1]
def updateTreeNode(self, p, value):
p = p+self.n
self.data[p] = 1<<value
while p > 1:
self.data[p>>1] = self.data[p] | self.data[p^1]
p>>=1
def __repr__(self):
return ' '.join(str(bin(val).count("1")) for val in self.data)
def query(self, l, r):
ans = 0
l+=self.n
r+=self.n
while l < r:
if l & 1:
ans |= self.data[l]
l+=1
if r & 1:
r-=1
ans |= self.data[r]
l >>= 1
r >>= 1
return ans
aval = ord('a')
s = [ord(c)-aval for c in input()]
segTree = SegmentTree(len(s))
segTree.build(s)
for _ in range(int(input())):
q, a, b = input().split()
#print(segTree)
if q=="1":
segTree.updateTreeNode(int(a)-1, ord(b)-aval)
else:
print(bin(segTree.query(int(a)-1, int(b))).count("1"))
``` | output | 1 | 96,211 | 0 | 192,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6 | instruction | 0 | 96,212 | 0 | 192,424 |
Tags: data structures
Correct Solution:
```
# -*- coding: utf-8 -*-
# Baqir Khan
# Software Engineer (Backend)
from sys import stdin
inp = stdin.readline
class SegmentTree:
def __init__(self, values, default, func):
"""
Segment tree to find Value function for any segment of some array A.
Suppose we want to find some V for every slice of a given array
and that if we know values on slices [a:b] and [b:c] then it's easy to
calculate value for slice [a:c] - in other words there exists associative binary
operation ~ such that for any given a, b (where 0 <= a <= b < len(A))
V(A[a:b]) = V(A[a:c]) ~ V(A[c:b]) for any c between a and b, particularly:
V(A[a:b]) = V(A[a]) ~ V(A[a + 1]) ~ ... ~ V(A[b - 1])
And suppose that we need to change separate values in array and keep results up to date.
Example 1:
~ is min of two numbers and Value(array[a:b]) is minimum element on slice array[a:b]
Example 2:
~ is addition and Value(array[a:b]) means sum of elements in A[a:b])
Args:
values:
pre-calculated values for V function on elements of array
default:
value for empty segment, such that func(v, default) = v
func:
combining binary operation as function taking two arguments: func(a, b) means a ~ b
"""
k = 0
while 2 ** k < len(values):
k += 1
# heap_size = 2 ** (k + 1) - 1
heap = (2 ** k - 1) * [default] + list(values) + (2 ** k - len(values)) * [default]
for index in range(2 ** k - 1 - 1, -1, -1):
heap[index] = func(heap[2 * index + 1], heap[2 * index + 2])
self._length = len(values)
self.func = func
self.heap = heap
self.k = k
self.default = default
def __getitem__(self, indexer):
shift = 2 ** self.k - 1
if isinstance(indexer, int):
return self.heap[shift + indexer]
elif isinstance(indexer, slice):
left, right = shift + indexer.start, shift + indexer.stop - 1
if left > right:
return self.default
func = self.func
heap = self.heap
res = func(heap[left], heap[right])
while left < right:
if ~(left & 1):
res = func(res, heap[left])
left += 1
if right & 1:
res = func(res, heap[right])
right -= 1
left = (left + 1) // 2 - 1
right = (right + 1) // 2 - 1
if left == right:
res = func(res, heap[left])
return res
raise TypeError()
def __setitem__(self, array_index, value):
if array_index > len(self):
raise IndexError
index = (2 ** self.k) - 1 + array_index
heap = self.heap
func = self.func
heap[index] = value
while index:
# until there is an ancestor node in heap for current index
index = (index + 1) // 2 - 1
heap[index] = func(heap[2 * index + 1], heap[2 * index + 2])
def __len__(self):
return self._length
def get_binary(c):
return 1 << (ord(c) - ord('a'))
def get_ones_place(c):
place = 0
while c:
place += c & 1
c >>= 1
return place
s = list(inp()[:-1])
q = int(inp())
segment_tree = SegmentTree([get_binary(c) for c in s], 0, lambda x, y: x | y)
while q:
q -= 1
a, b, c = inp().split()
if a == "1":
segment_tree[int(b) - 1] = get_binary(c)
else:
print(get_ones_place(segment_tree[int(b) - 1: int(c)]))
``` | output | 1 | 96,212 | 0 | 192,425 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6
Submitted Solution:
```
'''input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
'''
from sys import stdin
from collections import deque
import math
# builds the segment tree.... time complexity O(n)
def build_segment_tree(tree, string, index, start, end):
if start > end:
return
# for node element
if start == end:
tree[index][ord(string[start]) - ord('a')] += 1
# for internal node
else:
mid = (start + end) // 2
build_segment_tree(tree, string, 2 * index, start, mid)
build_segment_tree(tree, string, 2 * index + 1, mid + 1, end)
for i in range(26):
tree[index][i] = tree[2 * index][i] + tree[2 * index + 1][i]
def combine(first, second):
aux = [0] * 26
for i in range(26):
aux[i] = first[i] + second[i]
return aux
# query function. Outputs the minimum element in the given range. Time complexity is O(log(n))
def query(tree, a, index, start, end, qs, qe):
if qs > end or qe < start:
return [0] * 26
# total overlap
if qs <= start and end <= qe:
return tree[index][:]
# partial overlap
else:
mid = (start + end) // 2
left = query(tree, a, 2 * index, start, mid, qs, qe)
right = query(tree, a, 2 * index + 1, mid + 1, end, qs, qe)
return combine(left, right)
# update the given node. Time complexity is O(log(n))
def update_node(tree, string, index, start, end, n_index, c):
# No overlap
if n_index < start or n_index > end:
return
# reach the node
if start == end:
tree[index][ord(string[n_index]) - ord('a')] -= 1
tree[index][ord(c) - ord('a')] += 1
string[n_index] = c
return
# partial or complete overlap
else:
mid = (start + end) // 2
update_node(tree, string, 2 * index, start, mid, n_index, c)
update_node(tree, string, 2 * index + 1, mid + 1, end, n_index, c)
aux = combine(tree[ 2 * index], tree[ 2 * index + 1])
for i in range(26):
tree[index][i] = aux[i]
return
# main starts
string = list(stdin.readline().strip())
n = len(string)
tree = [[0 for x in range(26)] for y in range(4 * n + 1)]
index = 1
start = 0
end = n - 1
build_segment_tree(tree, string, index, start, end)
# print(tree[1])
q = int(stdin.readline().strip())
for _ in range(q):
t, x, y = list(stdin.readline().split())
if t == '1':
update_node(tree, string, index, start, end, int(x) - 1, y)
# print(tree[1])
else:
result = query(tree, string, index, start, end, int(x) - 1, int(y) - 1)
# print(result)
count = 0
for i in result:
if i > 0:
count += 1
print(count)
``` | instruction | 0 | 96,213 | 0 | 192,426 |
Yes | output | 1 | 96,213 | 0 | 192,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6
Submitted Solution:
```
def solve(s,qs):
n=len(s)
bits=[[0 for i in range(n+1)] for j in range(26)]
def update(i,j,val):
while j <= n:
bits[i][j] += val
j += j & (-j)
def _query(i,j):
s = 0
while j > 0:
s += bits[i][j]
j -= j & (-j)
return s
def query(i,a,b):
return _query(i,b) - _query(i,a-1)
for i,c in enumerate(s):
update(c-ord('a'),i+1,1)
for q in qs:
if q[0] == 1:
update(s[q[1]-1]-ord('a'),q[1],-1)
s[q[1]-1]=q[2]
update(q[2]-ord('a'),q[1],1)
else:
ans = 0
for i in range(26):
ans += query(i,q[1],q[2]) > 0
print(ans)
s=[ord(c) for c in input()]
qs=[input().split() for i in range(int(input()))]
for i in range(len(qs)):
q=qs[i]
if q[0] == '1': qs[i] = [int(q[0]),int(q[1]),ord(q[2])]
else: qs[i] = list(map(int,q))
solve(s,qs)
``` | instruction | 0 | 96,214 | 0 | 192,428 |
Yes | output | 1 | 96,214 | 0 | 192,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6
Submitted Solution:
```
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
s = input()
a = []
for i in s:
a += [2**(ord(i)-97)]
st = SegmentTree(a, func=lambda x, y: x | y)
for _ in range(int(input())):
p, q, r = input().split()
if p == "1":
st.__setitem__(int(q)-1, 2**(ord(r) - 97))
else:
result = st.query(int(q)-1, int(r)-1)
print(bin(result)[2:].count('1'))
``` | instruction | 0 | 96,215 | 0 | 192,430 |
Yes | output | 1 | 96,215 | 0 | 192,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6
Submitted Solution:
```
import sys
input = sys.stdin.readline
def update(BIT,n,i,v):
while i<=n:
BIT[i]+=v
i+=i&(-i)
#print(BIT)
def getsum(BIT,i):
s=0
while i>0:
s+=BIT[i]
i-=i&(-i)
return(s)
s=[i for i in input() if i !='\n']
#print(s)
LEN=len(s)
BIT=[[0]*(LEN+1) for i in range(26)]
for i in range(len(s)):
char=ord(s[i])-97
update(BIT[char],LEN,i+1,1)
#print(BIT)
q=int(input())
for i in range(q):
c=[i for i in input().split()]
#print(c)
if c[0]=='1':
char1=ord(s[int(c[1])-1])-97
s[int(c[1])-1]=c[2]
update(BIT[char1],LEN,int(c[1]),-1)
char2=ord(c[2])-97
update(BIT[char2],LEN,int(c[1]),1)
#print(BIT)
if c[0]=='2':
l=int(c[1])
r=int(c[2])
p=0
for i in range(len(BIT)):
p+=(min(1,getsum(BIT[i],r)-getsum(BIT[i],l-1)))
print(p)
``` | instruction | 0 | 96,216 | 0 | 192,432 |
Yes | output | 1 | 96,216 | 0 | 192,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6
Submitted Solution:
```
s = input()
list1 = list(s)
q = int(input())
for i in range(q):
a,b,c = input().split()
ds=0
list3 = []
if int(a) == 1:
list1[int(b)-1] = c
else:
list2 = list1[int(b)-1:int(c)-1]
for char in list2:
if char not in list3:
list3.append(char)
ds += 1
print(ds)
``` | instruction | 0 | 96,217 | 0 | 192,434 |
No | output | 1 | 96,217 | 0 | 192,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6
Submitted Solution:
```
n = 1101053527189095067 * 1000000000000000007
mod = 1000003
aa = [[0,0],[0,0]]
bb = [[0,0],[0,0]]
def mul():
ans = [[0,0],[0,0]]
for i in range(2):
for j in range(2):
ans[i][j] = sum(aa[i][k] * bb[k][j] % mod for k in range(2)) % mod
return ans
def mpow(a, b):
ret = [[1,0],[0,1]]
while b:
if b & 1:
ret = mul()
b >>= 1
a = mul()
return ret
print(mpow([[1,1],[1,0]], n)[0][0])
mod = 100003
n = 100003
a = 1
for i in range(10000):
a = mpow([[1,1],[1,0]], n)[0][0]
# for i in range(2, 1000009):
# a = mpow([[1,1],[1,0]], i)[0][0]
# b = mpow([[1,1],[1,0]], i+1)[0][0]
# if a == 1 and b == 1:
# print(i)
# fib = [0,1]
# for i in range(2000009):
# fib.append((fib[-1] + fib[-2])%mod)
# if fib[-1] == 1 and fib[-2] == 1:
# print(i)
``` | instruction | 0 | 96,218 | 0 | 192,436 |
No | output | 1 | 96,218 | 0 | 192,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6
Submitted Solution:
```
string = list(input())
answer = ""
for query in range(int(input())):
type, a, b = input().split()
if type == '1':
a = int(a)
string[a-1] = b
else:
a,b = map(int,[a,b])
amDistinct = len(set(string[a:b]))
answer += str(amDistinct) + "\n"
print(answer[:-1])
``` | instruction | 0 | 96,219 | 0 | 192,438 |
No | output | 1 | 96,219 | 0 | 192,439 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of lowercase Latin letters and q queries for this string.
Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} ... s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".
There are two types of queries:
* 1~ pos~ c (1 ≤ pos ≤ |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c);
* 2~ l~ r (1 ≤ l ≤ r ≤ |s|): calculate the number of distinct characters in the substring s[l; r].
Input
The first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.
The second line of the input contains one integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.
Examples
Input
abacaba
5
2 1 4
1 4 b
1 5 b
2 4 6
2 1 7
Output
3
1
2
Input
dfcbbcfeeedbaea
15
1 6 e
1 4 b
2 6 14
1 7 b
1 12 c
2 6 8
2 1 6
1 7 c
1 2 f
1 10 a
2 7 9
1 10 a
1 14 b
1 1 f
2 1 11
Output
5
2
5
2
6
Submitted Solution:
```
s = input()
q = int(input())
qs = []
for _ in range(q):
qs.append(input().split())
# num_uniq = []
# uniq_count = 0
# s_set = set()
# for _s in s:
# if _s not in s_set:
# s_set.add(_s)
# uniq_count += 1
# num_uniq.append(uniq_count)
# print(num_uniq)
for t, a, b in qs:
if int(t) != 2:
continue
a, b = int(a), int(b)
print(len(set(s[a:b+1])))
``` | instruction | 0 | 96,220 | 0 | 192,440 |
No | output | 1 | 96,220 | 0 | 192,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5. | instruction | 0 | 96,324 | 0 | 192,648 |
Tags: dp, strings
Correct Solution:
```
n,m=map(int,input().split())
s=input().strip()
t=input().strip()
dp=[[0]*(m+1) for j in range(n+1)]
ans=0
for j in range(1,n+1):
for k in range(1,m+1):
if s[j-1]==t[k-1]:
dp[j][k]=max(0,dp[j-1][k-1]+2,dp[j-1][k]-1,dp[j][k-1]-1)
else:
dp[j][k]=max(0,dp[j-1][k]-1,dp[j][k-1]-1)
ans=max(ans,dp[j][k])
print(ans)
``` | output | 1 | 96,324 | 0 | 192,649 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5. | instruction | 0 | 96,325 | 0 | 192,650 |
Tags: dp, strings
Correct Solution:
```
import sys
import math
def II():
return int(sys.stdin.readline())
def LI():
return list(map(int, sys.stdin.readline().split()))
def MI():
return map(int, sys.stdin.readline().split())
def SI():
return sys.stdin.readline().strip()
def FACT(n, mod):
s = 1
facts = [1]
for i in range(1,n+1):
s*=i
s%=mod
facts.append(s)
return facts[n]
def C(n, k, mod):
return (FACT(n,mod) * pow((FACT(k,mod)*FACT(n-k,mod))%mod,mod-2, mod))%mod
n,m = MI()
a = list(SI())
b = list(SI())
n1 = len(a)
n2 = len(b)
ans = 0
dp = [[0 for i in range(n2 + 1)] for i in range(n1 + 1)]
for i in range(1,n+1):
for j in range(1,m+1):
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1]+2
else:
dp[i][j] = max(dp[i-1][j]-1, dp[i][j-1]-1, 0)
ans = max(ans,dp[i][j])
print(ans)
``` | output | 1 | 96,325 | 0 | 192,651 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5. | instruction | 0 | 96,326 | 0 | 192,652 |
Tags: dp, strings
Correct Solution:
```
def LCS(str1,m,str2,n):
dp=[[0 for x in range(n)]for y in range(m)]
dp[0][0]=2 if str1[0]==str2[0] else 0
m_score=dp[0][0]
for x in range(1,n):
if str1[0]==str2[x]:
dp[0][x]=2
m_score=max(m_score,dp[0][x])
else:
dp[0][x]=max(dp[0][x-1]-1,0)
for y in range(1,m):
if str1[y]==str2[0]:
dp[y][0]=2
m_score=max(m_score,dp[y][0])
else:
dp[y][0]=max(dp[y-1][0]-1,0)
for y in range(1,m):
for x in range(1,n):
if str1[y]==str2[x]:
dp[y][x]=max(2,dp[y-1][x-1]+2)
m_score=max(m_score,dp[y][x])
else:
dp[y][x]=max(dp[y-1][x]-1,dp[y][x-1]-1,0)
# [[print(' '.join(list(map(str,s))))]for s in dp]
return m_score
import sys
l1,l2=list(map(int,sys.stdin.readline().strip().split()))
s1=sys.stdin.readline().strip()
s2=sys.stdin.readline().strip()
print(LCS(s1,l1,s2,l2))
``` | output | 1 | 96,326 | 0 | 192,653 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5. | instruction | 0 | 96,327 | 0 | 192,654 |
Tags: dp, strings
Correct Solution:
```
m,n = map(int,input().split())
s1 = input()
s2 = input()
dp = [[0 for j in range(n+1)] for i in range(m+1)]
for i in range(m):
dp[i][n] = -i-1
for j in range(n):
dp[m][j] = -j-1
ans = 0
for i in range(m):
for j in range(n):
if s1[i]!=s2[j]:
dp[i][j] = max(max(dp[i-1][j],dp[i][j-1]) - 1,-2)
else:
dp[i][j] = max(dp[i-1][j-1],0) + 2
ans = max(ans,dp[i][j])
#print(dp)
print(ans)
``` | output | 1 | 96,327 | 0 | 192,655 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5. | instruction | 0 | 96,328 | 0 | 192,656 |
Tags: dp, strings
Correct Solution:
```
#!/usr/bin/env python3.9
from operator import itemgetter
def maxS(A, B):
''' S(C,D) = 4*LCS(C,D) - |C| - |D| '''
# tuple(lcs, len(c), len(d)), len(c) <= len(d)
# zero-padding (1, 1, 0, 0)
# LCS = [[(0, 0, 0,)]*(len(B)+1) for _ in range(len(A)+1)]
# LCS = [[(0, 0, 0,)]*(len(B)+1) for _ in range(2)]
S = [[0]*(len(B)+1) for _ in range(2)]
# SS1 = [[0]*(len(B)+1) for _ in range(len(A)+1)]
maxS = 0
for i in range(1, len(A)+1):
ii = i % 2
for j in range(1, len(B)+1):
res_lcs = 0, 0, 0
# S = 0
if A[i-1] == B[j-1]:
# lcs, lc, ld = LCS[ii-1][j-1]
# S = 4*lcs - lc - ld
if S[ii-1][j-1] < 0:
# res_lcs = 1, 1, 1
S[ii][j] = 2
else:
# res_lcs = lcs+1, lc+1, ld+1
S[ii][j] = S[ii-1][j-1] + 2
else:
# up = LCS[ii-1][j]
# left = LCS[ii][j-1]
# lcs, lc, ld = 0, 0, 0
# left_S = 4 * left[0] - left[1] - left[2]
# up_S = 4 * up[0] - up[1] - up[2]
if S[ii][j-1] >= S[ii-1][j]:
# lcs, lc, ld = left
S[ii][j] = S[ii][j-1] - 1
else:
# lcs, lc, ld = up
S[ii][j] = S[ii-1][j] - 1
# lcs, lc, ld = max(left, up, key=itemgetter(0))
# res_lcs = lcs, lc, ld+1
# S = 4 * res_lcs[0] - res_lcs[1] - res_lcs[2]
# LCS[ii][j] = res_lcs
# SS1[i][j] = max(S, 0)
if S[ii][j] > maxS:
maxS = S[ii][j]
# [print(*s) for s in LCS]
# print()
# [print(*s) for s in SS1]
# print()
return maxS
n, m = list(map(int, input().split(' ')))
A = input()
B = input()
if len(B) > len(A):
A, B = B, A
print(maxS(A, B))
``` | output | 1 | 96,328 | 0 | 192,657 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5. | instruction | 0 | 96,329 | 0 | 192,658 |
Tags: dp, strings
Correct Solution:
```
n,m=map(int,input().split())
s=input().strip()
t=input().strip()
dp=[[0]*(m+1) for j in range(n+1)]
ans=0
for j in range(1,n+1):
for k in range(1,m+1):
if s[j-1]==t[k-1]:
dp[j][k]=max(0,dp[j-1][k-1]+2)
else:
dp[j][k]=max(0,dp[j-1][k]-1,dp[j][k-1]-1)
ans=max(ans,dp[j][k])
print(ans)
``` | output | 1 | 96,329 | 0 | 192,659 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5. | instruction | 0 | 96,330 | 0 | 192,660 |
Tags: dp, strings
Correct Solution:
```
import sys
import os
from io import BytesIO, IOBase
#Fast IO Region
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")
n, m = map(int, input().split())
a, b = input(), input()
dp = [[0] * (m+2) for _ in range(n+2)]
ans = 0
for i in range(n-1, -1, -1):
for j in range(m-1, -1, -1):
if a[i] == b[j]:
dp[i][j] = dp[i+1][j+1] + 2
else:
dp[i][j] = max(0, max(dp[i][j+1], dp[i+1][j]) -1)
ans = max(ans, dp[i][j])
print(ans)
``` | output | 1 | 96,330 | 0 | 192,661 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5. | instruction | 0 | 96,331 | 0 | 192,662 |
Tags: dp, strings
Correct Solution:
```
import io, os
from math import *
def lcs(x, y):
n = len(x)
m = len(y)
dp = [[0]*(m+1) for _ in range(n+1)]
best = 0
for i in range(1, n+1):
for j in range(1, m+1):
opt1 = dp[i-1][j] - 1
opt2 = dp[i][j-1] - 1
opt3 = dp[i-1][j-1] - 2
if x[i-1] == y[j-1]:
opt3 += 4
dp[i][j] = max(opt1, opt2, opt3, 0)
best = max(best, dp[i][j])
return best
def main():
n, m = list(map(int, input().split()))
a = input()
b = input()
print(lcs(a, b))
main()
``` | output | 1 | 96,331 | 0 | 192,663 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
Submitted Solution:
```
from sys import stdin
input = stdin.readline
k,n = map(int, input().split())
a = input()
b = input()
dp = [[0 for i in range(n + 1)] for __ in range(k + 1)]
ans = 0
for i in range(1, k + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = max(dp[i][j],dp[i - 1][j - 1] + 2)
ans = max(ans, dp[i][j])
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) - 1
dp[i][j] = max(0 , dp[i][j])
print(ans)
``` | instruction | 0 | 96,332 | 0 | 192,664 |
Yes | output | 1 | 96,332 | 0 | 192,665 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
x, y = input().strip(), input().strip()
dp, best = [[0] * (m + 1) for _ in range(n + 1)], 0
for i in range(n):
for j in range(m):
if x[i] == y[j]:
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 2) # not 4
else:
dp[i][j] = max(dp[i][j], dp[i - 1][j] - 1, dp[i][j - 1] - 1)
best = max(best, dp[i][j], dp[i - 1][j])
print(best)
``` | instruction | 0 | 96,333 | 0 | 192,666 |
Yes | output | 1 | 96,333 | 0 | 192,667 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
Submitted Solution:
```
n,m=map(int,input().split())
dp=[[0 for i in range(m+1)] for i in range(n+1)]
a=str(input())
b=str(input())
ans=0
for i in range(1,n+1):
for j in range(1,m+1):
if a[i-1]==b[j-1]:
dp[i][j]=max(dp[i][j],dp[i-1][j-1]+2)
ans=max(ans,dp[i][j])
else:
dp[i][j]=max(dp[i][j],max(dp[i-1][j],dp[i][j-1])-1)
ans=max(ans,dp[i][j])
print(ans)
``` | instruction | 0 | 96,334 | 0 | 192,668 |
Yes | output | 1 | 96,334 | 0 | 192,669 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
Submitted Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa=ifa[::-1]
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def linc(f,t,l,r):
while l<r:
mid=(l+r)//2
if t>f(mid):
l=mid+1
else:
r=mid
return l
def rinc(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t<f(mid):
r=mid-1
else:
l=mid
return l
def ldec(f,t,l,r):
while l<r:
mid=(l+r)//2
if t<f(mid):
l=mid+1
else:
r=mid
return l
def rdec(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t>f(mid):
r=mid-1
else:
l=mid
return l
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def binfun(x):
c=0
for w in arr:
c+=ceil(w/x)
return c
def lowbit(n):
return n&-n
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
'''
class SMT:
def __init__(self,arr):
self.n=len(arr)-1
self.arr=[0]*(self.n<<2)
self.lazy=[0]*(self.n<<2)
def Build(l,r,rt):
if l==r:
self.arr[rt]=arr[l]
return
m=(l+r)>>1
Build(l,m,rt<<1)
Build(m+1,r,rt<<1|1)
self.pushup(rt)
Build(1,self.n,1)
def pushup(self,rt):
self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1]
def pushdown(self,rt,ln,rn):#lr,rn表区间数字数
if self.lazy[rt]:
self.lazy[rt<<1]+=self.lazy[rt]
self.lazy[rt<<1|1]=self.lazy[rt]
self.arr[rt<<1]+=self.lazy[rt]*ln
self.arr[rt<<1|1]+=self.lazy[rt]*rn
self.lazy[rt]=0
def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间
if r==None: r=self.n
if L<=l and r<=R:
self.arr[rt]+=c*(r-l+1)
self.lazy[rt]+=c
return
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
if L<=m: self.update(L,R,c,l,m,rt<<1)
if R>m: self.update(L,R,c,m+1,r,rt<<1|1)
self.pushup(rt)
def query(self,L,R,l=1,r=None,rt=1):
if r==None: r=self.n
#print(L,R,l,r,rt)
if L<=l and R>=r:
return self.arr[rt]
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
ans=0
if L<=m: ans+=self.query(L,R,l,m,rt<<1)
if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1)
return ans
'''
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]<self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
for v in graph[u]:
if v not in d or d[v]>d[u]+graph[u][v]:
d[v]=d[u]+graph[u][v]
heappush(heap,(d[v],v))
return d
def GP(it): return [(ch,len(list(g))) for ch,g in groupby(it)]
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
class Trie:
def __init__(self,d):
if d>=0:
self.left=Trie(d-1)
else:
self.right=Trie(d-1)
self.c=0
def put(self,x,i):
if i==-1:
self.c=1
return
if x&1<<i:
self.left.put(x,i-1)
else:
self.right.put(x,i-1)
t=1
for i in range(t):
n,m=RL()
a=input()
b=input()
dp=[[0]*(m+1) for i in range(n+1)]
for i in range(n):
for j in range(m):
if a[i]==b[j]:
dp[i+1][j+1]=dp[i][j]+2
else:
dp[i+1][j+1]=max(0,dp[i+1][j]-1,dp[i][j+1]-1)
print(max(dp[i+1][j+1] for i in range(n) for j in range(m)))
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
``` | instruction | 0 | 96,335 | 0 | 192,670 |
Yes | output | 1 | 96,335 | 0 | 192,671 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
from collections import deque, defaultdict, namedtuple
import heapq
from math import sqrt, factorial, gcd, ceil, atan, pi
from itertools import permutations
# def input(): return sys.stdin.readline().strip()
# def input(): return sys.stdin.buffer.readline()[:-1] # warning bytes
# def input(): return sys.stdin.buffer.readline().strip() # warning bytes
def input(): return sys.stdin.buffer.readline().decode('utf-8').strip()
import string
import operator
import random
# string.ascii_lowercase
from bisect import bisect_left, bisect_right
from functools import lru_cache, reduce
MOD = int(1e9)+7
INF = float('inf')
# sys.setrecursionlimit(MOD)
def lcs(s1, s2):
matrix = [[[] for x in range(len(s2))] for x in range(len(s1))]
for i in range(len(s1)):
for j in range(len(s2)):
if s1[i] == s2[j]:
if i == 0 or j == 0:
matrix[i][j] = [(i, j)]
else:
matrix[i][j] = matrix[i-1][j-1] + [(i, j)]
else:
matrix[i][j] = max(matrix[i-1][j], matrix[i][j-1], key=lambda x: (len(x), -(x[-1][1] - x[0][1] + x[-1][0] - x[0][0]) if x else -INF))
return matrix
def solve():
n, m = [int(x) for x in input().split()]
s = input()
t = input()
a = (lcs(s, t))
ans = 0
for i in range(n):
for j in range(m):
if s[i] == t[j]:
_lcs = len(a[i][j])
xx, yy = a[i][j][0]
xxx, yyy = a[i][j][-1]
x = xxx - xx + 1
y = yyy - yy + 1
scd = 4 * _lcs - x - y
ans = max(ans, scd)
print(ans)
T = 1
# T = int(input())
for case in range(1,T+1):
ans = solve()
"""
1
2
1 2
10 10
"""
``` | instruction | 0 | 96,336 | 0 | 192,672 |
No | output | 1 | 96,336 | 0 | 192,673 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
Submitted Solution:
```
l0, l1 = map(int,input().split())
l = [l0,l1]
s = []
s.append(input()[:l[0]])
s.append(input()[:l[1]])
n = max(len(s[0]), len(s[1]))
if len(s[0])<len(s[1]):
s[0] += (n-len(s[0]))*"`"
else:
s[1] += (n-len(s[1]))*"`"
last_literka = []
for i in range(2):
last_literka.append([[-1]*27 for i in range(n)])
for j in range(2):
last = [-1] * 27
for i in range(n):
last[ord(s[j][i])-96] = i
for t in range(27):
last_literka[j][i][t] = last[t]
wynik = [[0]*(n+1) for i in range(n+1)]
res = 0
for i in range(n):
for j in range(n):
x = 0
if i == 0 and j == 0:
wynik[i][j] = 2
if s[0][i] != s[1][j]:
wynik[i][j] -= 4
else:
if i == 0:
if s[0][i] == s[1][j]:
wynik[i][j] = 2
elif j > 0 and s[0][i] == s[1][j-1]:
wynik[i][j] = 1
elif j > 1 and s[0][i] == s[1][j-2]:
wynik[i][j] = 0
elif j > 2 and s[0][i] == s[1][j-3]:
wynik[i][j] = -1
else:
wynik[i][j] = -2
else:
if j == 0:
if s[1][j] == s[0][i]:
wynik[i][j] = 2
elif i > 0 and s[1][j] == s[0][i-1]:
wynik[i][j] = 1
elif i > 1 and s[1][j] == s[0][i-2]:
wynik[i][j] = 0
elif i > 2 and s[1][j] == s[0][i-3]:
wynik[i][j] = -1
else:
wynik[i][j] = -2
else:
if s[0][i] == s[1][j]:
wynik[i][j] = wynik[i-1][j-1] + 2
else:
wynik[i][j] = max(wynik[i-1][j]-1, wynik[i][j-1]-1)
res = max(res, wynik[i][j])
print(res)
``` | instruction | 0 | 96,337 | 0 | 192,674 |
No | output | 1 | 96,337 | 0 | 192,675 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
Submitted Solution:
```
import pprint
n, m = map(int, input().split())
s = input()
t = input()
ans = 0
def lcs(X, Y):
global ans
m = len(X)
n = len(Y)
L = [[0]*(n + 1) for i in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if X[i-1] == Y[j-1]:
L[i][j] = max(L[i][j], L[i-1][j-1]) + 2
L[i][j] = max(L[i][j], L[i][j - 1] - 1, L[i - 1][j])
if L[i][j] > ans:
ans = L[i][j]
lcs(s, t)
print(ans)
``` | instruction | 0 | 96,338 | 0 | 192,676 |
No | output | 1 | 96,338 | 0 | 192,677 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
Submitted Solution:
```
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
a = input()
b = input()
a = a[:-1:]
b = b[:-1:]
dp = [([0] * (M + 1)) for i in range(N + 1)]
ans = 0
for i in range(N + 1):
dp[i][0] = i
for i in range(M + 1):
dp[0][i] = i
for i in range(1, N + 1):
for j in range(1, M + 1):
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, (dp[i - 1][j - 1]) if a[i - 1] == b[j - 1] else dp[i - 1][j - 1] + 1)
ans = max(ans, 4 * (max(i, j) - dp[i][j]) - i - j + 1)
print(ans)
``` | instruction | 0 | 96,339 | 0 | 192,678 |
No | output | 1 | 96,339 | 0 | 192,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally, let's define <image> as maximum value of <image> over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know <image> for all x from 0 to |s| where |s| denotes the length of string s.
Input
The first line of the input contains the string s (1 ≤ |s| ≤ 2 000).
The second line of the input contains the string p (1 ≤ |p| ≤ 500).
Both strings will only consist of lower case English letters.
Output
Print |s| + 1 space-separated integers in a single line representing the <image> for all x from 0 to |s|.
Examples
Input
aaaaa
aa
Output
2 2 1 1 0 0
Input
axbaxxb
ab
Output
0 1 1 2 1 1 0 0
Note
For the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}.
For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}. | instruction | 0 | 96,521 | 0 | 193,042 |
Tags: dp, strings
Correct Solution:
```
s, p = input(), input()
n, m = len(s) + 1, len(p)
d = [[0] * n for t in range(n)]
for x in range(1, n):
i, j = x, m
while i and j:
j -= s[i - 1] == p[j - 1]
i -= 1
if not j:
for y in range(i + 1): d[x][y + x - i - m] = d[i][y] + 1
for y in range(x): d[x][y] = max(d[x][y], d[x - 1][y])
print(*d[-1])
``` | output | 1 | 96,521 | 0 | 193,043 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally, let's define <image> as maximum value of <image> over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know <image> for all x from 0 to |s| where |s| denotes the length of string s.
Input
The first line of the input contains the string s (1 ≤ |s| ≤ 2 000).
The second line of the input contains the string p (1 ≤ |p| ≤ 500).
Both strings will only consist of lower case English letters.
Output
Print |s| + 1 space-separated integers in a single line representing the <image> for all x from 0 to |s|.
Examples
Input
aaaaa
aa
Output
2 2 1 1 0 0
Input
axbaxxb
ab
Output
0 1 1 2 1 1 0 0
Note
For the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}.
For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}.
Submitted Solution:
```
#input
s=str(input())
p=str(input())
#variables
occlist=[]
occ=0
j=0
time=0
timelist=[]
stop=False
#main
for i in range(len(s)):
time+=1
if s[i]==p[j]:
j+=1
if j==len(p):
occ+=1
j=0
timelist.append(time-len(p))
time=0
if i==len(s)-1:
stop=True
if i==len(s)-1:
timelist.append(time)
occlist+=[i//len(p) for i in range(occ*len(p)+1)]
timelist.sort()
timelist.reverse()
if s[0]==p[0] and stop:
for i in range(len(timelist)):
occlist+=[occ-i-1]*timelist[i]
else:
for i in range(len(timelist)):
occlist+=[occ-i]*timelist[i]
print(''.join([str(occlist[i])+' ' for i in range(len(occlist)-1,-1,-1)]))
``` | instruction | 0 | 96,522 | 0 | 193,044 |
No | output | 1 | 96,522 | 0 | 193,045 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally, let's define <image> as maximum value of <image> over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know <image> for all x from 0 to |s| where |s| denotes the length of string s.
Input
The first line of the input contains the string s (1 ≤ |s| ≤ 2 000).
The second line of the input contains the string p (1 ≤ |p| ≤ 500).
Both strings will only consist of lower case English letters.
Output
Print |s| + 1 space-separated integers in a single line representing the <image> for all x from 0 to |s|.
Examples
Input
aaaaa
aa
Output
2 2 1 1 0 0
Input
axbaxxb
ab
Output
0 1 1 2 1 1 0 0
Note
For the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}.
For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}.
Submitted Solution:
```
a=str(input())
b=str(input())
c=[]
n=len(a)
for i in range(n):
c.append(a[0:len(a)-i:])
c.append(" ")
for i in c:
print(i.count(b))
``` | instruction | 0 | 96,523 | 0 | 193,046 |
No | output | 1 | 96,523 | 0 | 193,047 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally, let's define <image> as maximum value of <image> over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know <image> for all x from 0 to |s| where |s| denotes the length of string s.
Input
The first line of the input contains the string s (1 ≤ |s| ≤ 2 000).
The second line of the input contains the string p (1 ≤ |p| ≤ 500).
Both strings will only consist of lower case English letters.
Output
Print |s| + 1 space-separated integers in a single line representing the <image> for all x from 0 to |s|.
Examples
Input
aaaaa
aa
Output
2 2 1 1 0 0
Input
axbaxxb
ab
Output
0 1 1 2 1 1 0 0
Note
For the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}.
For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}.
Submitted Solution:
```
s = input()
p = input()
val = s.count(p)
res_str = str(val) + ' '
ls = len(s)
lp = len(p)
for i in range(1, ls + 1):
if lp > ls - i:
res_str += '0 '
else:
max_c = s.count(p)
founded = False
for j in range(len(s)):
if not (s[j] in p):
if (s[:j] + s[j+1:]).count(p) >= max_c:
founded = True
max_c = (s[:j] + s[j+1:]).count(p)
s = s[:j] + s[j+1:]
break
if not founded:
founded = False
for j in range(len(s)):
if not (s[j] in p):
s = s[:j] + s[j+1:]
founded = True
break
if not founded:
founded = False
for j in range(len(s)):
if (s[:j] + s[j+1:]).count(p) >= max_c:
founded = True
max_c = (s[:j] + s[j+1:]).count(p)
s = s[:j] + s[j+1:]
break
if not founded:
s = s[:-1]
res_str += str(s.count(p)) + ' '
print(res_str[:-1])
``` | instruction | 0 | 96,524 | 0 | 193,048 |
No | output | 1 | 96,524 | 0 | 193,049 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates <image> that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.
More formally, let's define <image> as maximum value of <image> over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know <image> for all x from 0 to |s| where |s| denotes the length of string s.
Input
The first line of the input contains the string s (1 ≤ |s| ≤ 2 000).
The second line of the input contains the string p (1 ≤ |p| ≤ 500).
Both strings will only consist of lower case English letters.
Output
Print |s| + 1 space-separated integers in a single line representing the <image> for all x from 0 to |s|.
Examples
Input
aaaaa
aa
Output
2 2 1 1 0 0
Input
axbaxxb
ab
Output
0 1 1 2 1 1 0 0
Note
For the first sample, the corresponding optimal values of s' after removal 0 through |s| = 5 characters from s are {"aaaaa", "aaaa", "aaa", "aa", "a", ""}.
For the second sample, possible corresponding optimal values of s' are {"axbaxxb", "abaxxb", "axbab", "abab", "aba", "ab", "a", ""}.
Submitted Solution:
```
s = input()
p = input()
val = s.count(p)
res_str = str(val) + ' '
ls = len(s)
lp = len(p)
for i in range(1, ls + 1):
if lp > ls - i:
res_str += '0 '
else:
max_c = s.count(p)
founded = False
for j in range(len(s)):
if not (s[j] in p):
if (s[:j] + s[j+1:]).count(p) >= max_c:
founded = True
max_c = (s[:j] + s[j+1:]).count(p)
s = s[:j] + s[j+1:]
break
if not founded:
founded = False
for j in range(len(s)):
if not (s[j] in p):
s = s[:j] + s[j+1:]
founded = True
break
if not founded:
founded = False
for j in range(len(s)):
if (s[:j] + s[j+1:]).count(p) >= max_c:
founded = True
max_c = (s[:j] + s[j+1:]).count(p)
s = s[:j] + s[j+1:]
break
if not founded:
s = s[1:]
res_str += str(s.count(p)) + ' '
print(res_str[:-1])
``` | instruction | 0 | 96,525 | 0 | 193,050 |
No | output | 1 | 96,525 | 0 | 193,051 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:
* l_1 + len \leq l_2
* S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)
If there is no such integer len, print 0.
Constraints
* 2 \leq N \leq 5 \times 10^3
* |S| = N
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.
Examples
Input
5
ababa
Output
2
Input
2
xy
Output
0
Input
13
strangeorange
Output
5 | instruction | 0 | 96,762 | 0 | 193,524 |
"Correct Solution:
```
N = int(input())
S = input()
dp = [[0]*N for i in range(N)]
pm = 0
ans = 0
for i in range(N-1,0,-1):
for j in range(i-1,-1,-1):
if S[i]==S[j]:
if i<N-1:
dp[i][j] = min(dp[i+1][j+1]+1, i-j)
else:
dp[i][j] = 1
else:
dp[i][j] = 0
if dp[i][j]>ans:
ans = dp[i][j]
print(ans)
``` | output | 1 | 96,762 | 0 | 193,525 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:
* l_1 + len \leq l_2
* S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)
If there is no such integer len, print 0.
Constraints
* 2 \leq N \leq 5 \times 10^3
* |S| = N
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.
Examples
Input
5
ababa
Output
2
Input
2
xy
Output
0
Input
13
strangeorange
Output
5 | instruction | 0 | 96,763 | 0 | 193,526 |
"Correct Solution:
```
def main():
n=int(input())
s=input()
dp=[[0]*(n+1) for i in range(n+1)]
ans=0
for i in reversed(range(n)):
for j in reversed(range(i+1,n)):
if s[i]==s[j]:
dp[i][j]=dp[i+1][j+1]+1
ans=max(ans,min(j-i,dp[i][j]))
print(ans)
if __name__=='__main__':
main()
``` | output | 1 | 96,763 | 0 | 193,527 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:
* l_1 + len \leq l_2
* S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)
If there is no such integer len, print 0.
Constraints
* 2 \leq N \leq 5 \times 10^3
* |S| = N
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.
Examples
Input
5
ababa
Output
2
Input
2
xy
Output
0
Input
13
strangeorange
Output
5 | instruction | 0 | 96,764 | 0 | 193,528 |
"Correct Solution:
```
I=input;n=int(I());s=I();j=1;r=[]
for i in range(n):
while (j<n)and(s[i:j] in s[j:]):j+=1
r.append(j-i-1)
print(max(r))
``` | output | 1 | 96,764 | 0 | 193,529 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:
* l_1 + len \leq l_2
* S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)
If there is no such integer len, print 0.
Constraints
* 2 \leq N \leq 5 \times 10^3
* |S| = N
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.
Examples
Input
5
ababa
Output
2
Input
2
xy
Output
0
Input
13
strangeorange
Output
5 | instruction | 0 | 96,765 | 0 | 193,530 |
"Correct Solution:
```
N = int(input())
S = input()
ans = 0
dp = [0] * N
for i in range(N - 1):
dp2 = dp[:]
for j in range(i + 1, N):
if S[i] == S[j] and j - i > dp2[j-1]:
dp[j] = dp2[j-1] + 1
ans = max(ans, dp[j])
else:
dp[j] = 0
print(ans)
``` | output | 1 | 96,765 | 0 | 193,531 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:
* l_1 + len \leq l_2
* S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)
If there is no such integer len, print 0.
Constraints
* 2 \leq N \leq 5 \times 10^3
* |S| = N
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.
Examples
Input
5
ababa
Output
2
Input
2
xy
Output
0
Input
13
strangeorange
Output
5 | instruction | 0 | 96,766 | 0 | 193,532 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
def main():
n = int(input())
s = input()[::-1]
ans = 0
l = 0
r = 1
for r in range(1,n):
if s[l:r] in s[r:]:
ans=r-l
else:
l += 1
print(ans)
main()
``` | output | 1 | 96,766 | 0 | 193,533 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:
* l_1 + len \leq l_2
* S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)
If there is no such integer len, print 0.
Constraints
* 2 \leq N \leq 5 \times 10^3
* |S| = N
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.
Examples
Input
5
ababa
Output
2
Input
2
xy
Output
0
Input
13
strangeorange
Output
5 | instruction | 0 | 96,767 | 0 | 193,534 |
"Correct Solution:
```
n=int(input())
s=input()
ans=i=0
j=1
while j<n:
t=s[i:j]
if t in s[j:]:
ans=max(ans,j-i)
j+=1
else:
i+=1
print(ans)
``` | output | 1 | 96,767 | 0 | 193,535 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:
* l_1 + len \leq l_2
* S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)
If there is no such integer len, print 0.
Constraints
* 2 \leq N \leq 5 \times 10^3
* |S| = N
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.
Examples
Input
5
ababa
Output
2
Input
2
xy
Output
0
Input
13
strangeorange
Output
5 | instruction | 0 | 96,768 | 0 | 193,536 |
"Correct Solution:
```
N = int(input())
S = input()
ans = 0
right = 0
for left in range(N - 1):
while right < N and (S[left : right] in S[right :]):
right += 1
if left == right:
right += 1
ans = max(ans, right - left - 1)
print(ans)
``` | output | 1 | 96,768 | 0 | 193,537 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.