message stringlengths 2 23.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 97 109k | cluster float64 0 0 | __index_level_0__ int64 194 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".
Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".
Help Maxim solve the problem that the teacher gave him.
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.
Input
The first line contains a single integer n (4 ≤ n ≤ 50) — the length of the string s.
The second line contains the string s, consisting of exactly n uppercase letters of the Latin alphabet.
Output
Output the minimum number of operations that need to be applied to the string s so that the genome appears as a substring in it.
Examples
Input
4
ZCTH
Output
2
Input
5
ZDATG
Output
5
Input
6
AFBAKC
Output
16
Note
In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.
In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
Submitted Solution:
```
n = int(input())
s = list(input())
genome = ["A", "C", "T", "G"]
counter = []
for i in range(0, len(s) - 3):
counter_temp = 0
counter_temp += min(abs(ord(s[i]) - ord(genome[0])), 26 - abs(ord(s[i]) - ord(genome[0])))
counter_temp += min(abs(ord(s[i+1]) - ord(genome[1])), 26 - abs(ord(s[i+1]) - ord(genome[1])))
counter_temp += min(abs(ord(s[i+2]) - ord(genome[2])), 26 - abs(ord(s[i+2]) - ord(genome[2])))
counter_temp += min(abs(ord(s[i+3]) - ord(genome[3])), 26 - abs(ord(s[i+3]) - ord(genome[3])))
counter.append(counter_temp)
#print(counter)
print(min(counter))
``` | instruction | 0 | 48,897 | 0 | 97,794 |
Yes | output | 1 | 48,897 | 0 | 97,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".
Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".
Help Maxim solve the problem that the teacher gave him.
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.
Input
The first line contains a single integer n (4 ≤ n ≤ 50) — the length of the string s.
The second line contains the string s, consisting of exactly n uppercase letters of the Latin alphabet.
Output
Output the minimum number of operations that need to be applied to the string s so that the genome appears as a substring in it.
Examples
Input
4
ZCTH
Output
2
Input
5
ZDATG
Output
5
Input
6
AFBAKC
Output
16
Note
In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.
In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
Submitted Solution:
```
def change(a, b):
return min((ord(a)-ord(b))%26, (ord(b)-ord(a))%26)
N = int(input())
s = input()
ls = []
for i in range(N-3):
ls.append(change(s[i], 'A')+change(s[i+1], 'C')+change(s[i+2], 'T')+change(s[i+3], 'G'))
print(min(ls))
``` | instruction | 0 | 48,898 | 0 | 97,796 |
Yes | output | 1 | 48,898 | 0 | 97,797 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".
Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".
Help Maxim solve the problem that the teacher gave him.
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.
Input
The first line contains a single integer n (4 ≤ n ≤ 50) — the length of the string s.
The second line contains the string s, consisting of exactly n uppercase letters of the Latin alphabet.
Output
Output the minimum number of operations that need to be applied to the string s so that the genome appears as a substring in it.
Examples
Input
4
ZCTH
Output
2
Input
5
ZDATG
Output
5
Input
6
AFBAKC
Output
16
Note
In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.
In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
Submitted Solution:
```
n = int(input())
s = input().lower()
res = 9984649494964654
gen = 'actg'
for i in range(n):
if n-i >= 4:
temp,k = 0,i
for j in range(4):
temp+=(abs(ord(s[k+j])-ord(gen[j])) if abs(ord(s[k+j])-ord(gen[j])) <= 13 else (26-abs(ord(s[k+j])-ord(gen[j]))))
res = min(res,temp)
print(res)
``` | instruction | 0 | 48,899 | 0 | 97,798 |
Yes | output | 1 | 48,899 | 0 | 97,799 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".
Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".
Help Maxim solve the problem that the teacher gave him.
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.
Input
The first line contains a single integer n (4 ≤ n ≤ 50) — the length of the string s.
The second line contains the string s, consisting of exactly n uppercase letters of the Latin alphabet.
Output
Output the minimum number of operations that need to be applied to the string s so that the genome appears as a substring in it.
Examples
Input
4
ZCTH
Output
2
Input
5
ZDATG
Output
5
Input
6
AFBAKC
Output
16
Note
In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.
In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
Submitted Solution:
```
import math
n = int(input())
s = input()
def compute(subs):
ops = min(ord(subs[0]) - ord('A'), 26 - (ord(subs[0]) - ord('A')))
ops += min(abs(ord(subs[1]) - ord('C')), 26 - abs((ord(subs[1]) - ord('C'))))
ops += min(abs(ord(subs[2]) - ord('T')), 26 - abs((ord(subs[2]) - ord('T'))))
ops += min(abs(ord(subs[3]) - ord('G')), 26 - abs((ord(subs[3]) - ord('G'))))
return ops
min_ops = math.inf
for i in range(n-3):
t = compute(s[i:i+4])
if t < min_ops:
min_ops = t
print(min_ops)
``` | instruction | 0 | 48,900 | 0 | 97,800 |
Yes | output | 1 | 48,900 | 0 | 97,801 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".
Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".
Help Maxim solve the problem that the teacher gave him.
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.
Input
The first line contains a single integer n (4 ≤ n ≤ 50) — the length of the string s.
The second line contains the string s, consisting of exactly n uppercase letters of the Latin alphabet.
Output
Output the minimum number of operations that need to be applied to the string s so that the genome appears as a substring in it.
Examples
Input
4
ZCTH
Output
2
Input
5
ZDATG
Output
5
Input
6
AFBAKC
Output
16
Note
In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.
In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
Submitted Solution:
```
n=int(input())
s=str(input())
c=[]
for i in range(3,n):
if 65<=ord(s[i-3])<=77:
d=abs(65-ord(s[i-3]))
else:
d=1+90-ord(s[i-3])
if 65<=ord(s[i-2])<=79:
d=d+abs(67-ord(s[i-2]))
else:
d=3+d+90-ord(s[i-2])
if 72<=ord(s[i-1])<=90:
d=d+abs(84-ord(s[i-1]))
else:
d=d+6+ord(s[i-1])-65
if 65<=ord(s[i])<=83:
d=d+abs(71-ord(s[i]))
else:
d=d+7+90-ord(s[i])
c.append(d)
print(min(c))
``` | instruction | 0 | 48,901 | 0 | 97,802 |
No | output | 1 | 48,901 | 0 | 97,803 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".
Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".
Help Maxim solve the problem that the teacher gave him.
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.
Input
The first line contains a single integer n (4 ≤ n ≤ 50) — the length of the string s.
The second line contains the string s, consisting of exactly n uppercase letters of the Latin alphabet.
Output
Output the minimum number of operations that need to be applied to the string s so that the genome appears as a substring in it.
Examples
Input
4
ZCTH
Output
2
Input
5
ZDATG
Output
5
Input
6
AFBAKC
Output
16
Note
In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.
In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
Submitted Solution:
```
n = int(input())
s = input()
genome = "ACTG"
res = 999999999
temp = 0
for i in range(0, n - 3) :
for j in range(0, 4) :
diff = abs(ord(s[i + j]) - ord(genome[j]))
if(diff == 25) : diff = 1
temp = temp + diff
if(temp < res) : res = temp
temp = 0
print(res)
``` | instruction | 0 | 48,902 | 0 | 97,804 |
No | output | 1 | 48,902 | 0 | 97,805 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".
Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".
Help Maxim solve the problem that the teacher gave him.
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.
Input
The first line contains a single integer n (4 ≤ n ≤ 50) — the length of the string s.
The second line contains the string s, consisting of exactly n uppercase letters of the Latin alphabet.
Output
Output the minimum number of operations that need to be applied to the string s so that the genome appears as a substring in it.
Examples
Input
4
ZCTH
Output
2
Input
5
ZDATG
Output
5
Input
6
AFBAKC
Output
16
Note
In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.
In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
Submitted Solution:
```
#n, k = map(int, input().split())
#s = list(map(int, input().split()))
n = int(input())
s = input()
g='ACTG'
l = [ord(i)-65 for i in g]
d = [ord(i)-65 for i in s]
#[print(ord(i)-65, end=' ') for i in g]
#print(d)
r = 200
for i in range(0, n-3):
t = 0
for j in range(0, 4):
#print(l[j], d[i+j], abs(l[j]-d[i+j]), 26-d[i+j]+l[j])
t+=min(abs(l[j]-d[i+j]), 26-d[i+j]+l[j])
#print(t)
if t<r: r=t
print(r)
``` | instruction | 0 | 48,903 | 0 | 97,806 |
No | output | 1 | 48,903 | 0 | 97,807 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG".
Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of at least 4, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string s with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A".
Help Maxim solve the problem that the teacher gave him.
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.
Input
The first line contains a single integer n (4 ≤ n ≤ 50) — the length of the string s.
The second line contains the string s, consisting of exactly n uppercase letters of the Latin alphabet.
Output
Output the minimum number of operations that need to be applied to the string s so that the genome appears as a substring in it.
Examples
Input
4
ZCTH
Output
2
Input
5
ZDATG
Output
5
Input
6
AFBAKC
Output
16
Note
In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring.
In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
Submitted Solution:
```
def genomeOps(s):
slist = list(s)
genome = [ord(i) for i in "ACTG"]
count = 0
for i in range(len(genome)):
asci = ord(s[i])
if asci == genome[i]:
continue
elif s[i] =='A':
if genome[i] in [j for j in range(78,91)]:
asci = ord('Z')
if asci == genome[i]:
count += 1
else:
while asci != genome[i]:
asci -= 1
count += 1
else:
while asci != genome[i]:
asci += 1
count += 1
elif s[i] == 'Z':
if genome[i] in [j for j in range(65,78)]:
asci = ord('A')
if asci == genome[i]:
count += 1
else:
while asci != genome[i]:
asci += 1
count += 1
else:
while asci != genome[i]:
asci -= 1
count += 1
elif asci > genome[i]:
while asci != genome[i]:
asci -= 1
count += 1
elif asci < genome[i]:
while asci != genome[i]:
asci += 1
count += 1
slist[i] = chr(asci)
# print(slist)
return(count)
def substrlenfour(s,l):
array = []
for i in range(0,len(s)-1):
for j in range(i+1,len(s)+1):
if len(s[i:j]) == 4:
# print(s[i:j])
array.append(genomeOps(s[i:j]))
# print(array)
return(min(array))
if __name__ == "__main__":
# s = input()
l=int(input())
s = input()
print(substrlenfour(s,l))
``` | instruction | 0 | 48,904 | 0 | 97,808 |
No | output | 1 | 48,904 | 0 | 97,809 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a binary string s awesome, if it has at least 1 symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are awesome, but 0, 110, 01010 aren't.
You are given a binary string s. Count the number of its awesome substrings.
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.
Input
The first line contains the string s (1 ≤ |s|≤ 200 000) consisting only of zeros and ones.
Output
Output a single number — the number of awesome substrings of s.
Examples
Input
111
Output
6
Input
01010
Output
10
Input
0000
Output
0
Input
1111100000
Output
25
Note
In the first sample, all substrings of s are awesome.
In the second sample, we have the following awesome substrings of s: 1 (2 times), 01 (2 times), 10 (2 times), 010 (2 times), 1010, 0101
In the third sample, no substring is awesome.
Submitted Solution:
```
count=0
a=input()
b=len(a)
z=a.count("1")
if z==0:
print(0)
elif z==1:
print(b)
else:
for i in range(1,b+1):
for j in range(0,b+1-i):
x=a[j:j+i]
n=x.count("1")
if n==0:
continue
if i%n!=0:
continue
else:
count+=1
print(count)
``` | instruction | 0 | 48,933 | 0 | 97,866 |
No | output | 1 | 48,933 | 0 | 97,867 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a binary string s awesome, if it has at least 1 symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are awesome, but 0, 110, 01010 aren't.
You are given a binary string s. Count the number of its awesome substrings.
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.
Input
The first line contains the string s (1 ≤ |s|≤ 200 000) consisting only of zeros and ones.
Output
Output a single number — the number of awesome substrings of s.
Examples
Input
111
Output
6
Input
01010
Output
10
Input
0000
Output
0
Input
1111100000
Output
25
Note
In the first sample, all substrings of s are awesome.
In the second sample, we have the following awesome substrings of s: 1 (2 times), 01 (2 times), 10 (2 times), 010 (2 times), 1010, 0101
In the third sample, no substring is awesome.
Submitted Solution:
```
s = list(input())
n = len(s)
x = s.count('1')+s.count('11')+s.count('10')+s.count('01')+s.count('001')+s.count('010')+s.count('100')+s.count('111')
for i in range(3, n):
for j in range(n-i):
a = s[j:(j+i+1)]
c = a.count('1')
if c != 0 and (i+1) % c == 0:
x += 1
print(x)
``` | instruction | 0 | 48,934 | 0 | 97,868 |
No | output | 1 | 48,934 | 0 | 97,869 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a binary string s awesome, if it has at least 1 symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are awesome, but 0, 110, 01010 aren't.
You are given a binary string s. Count the number of its awesome substrings.
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.
Input
The first line contains the string s (1 ≤ |s|≤ 200 000) consisting only of zeros and ones.
Output
Output a single number — the number of awesome substrings of s.
Examples
Input
111
Output
6
Input
01010
Output
10
Input
0000
Output
0
Input
1111100000
Output
25
Note
In the first sample, all substrings of s are awesome.
In the second sample, we have the following awesome substrings of s: 1 (2 times), 01 (2 times), 10 (2 times), 010 (2 times), 1010, 0101
In the third sample, no substring is awesome.
Submitted Solution:
```
from collections import Counter
s = input()
n = len(s)
LIMIT = max(int(n**.5 / 3),1)
out = 0
for rat in range(LIMIT):
seen = Counter()
count = 0
seen[0] = 1
for c in s:
if c == '0':
count += 1
else:
count -= rat
out += seen[count]
seen[count] += 1
zeroes = []
last = 0
for c in s:
if c == '0':
last += 1
else:
zeroes.append(last)
last = 0
zeroes.append(last)
MAX_ONES = n // LIMIT + 2
for size in range(1, MAX_ONES):
if size >= len(zeroes):
break
curr = sum(zeroes[:size + 1])
left = 0
right = size
while True:
min_size = (curr - zeroes[left] - zeroes[right]) // size
if min_size < LIMIT:
min_size = LIMIT - 1
max_size = curr // size
#Range: min_size
amount = max_size - min_size
if amount > 0:
for i in range(min_size + 1, max_size + 1):
out += min(zeroes[left] + 1, zeroes[right] + 1, i * size + 1, curr - i * size + 1)
"""
#print(left, right, size, curr)
cutoff = min(zeroes[left], zeroes[right]) + 1
#Left Range
smol = min_size + 1
tol = max((cutoff - 1) // size, min_size)
#print(((tol - smol + 1) * ((smol + tol) * size + 2)) // 2)
out += ((tol - smol + 1) * ((smol + tol) * size + 2)) // 2
#Mid Range
smol = tol + 1
tol = min(max_size + 1, (curr - cutoff) // size)
#print((tol - smol + 1) * cutoff)
out += (tol - smol + 1) * cutoff
#Right Range
smol = tol + 1
tol = max_size
#print(smol, tol)
#print(((tol - smol + 1) * ((curr - smol + curr - tol) * size + 2)) // 2)
out += ((tol - smol + 1) * ((curr - smol * size + curr - tol * size)+ 2)) // 2
"""
curr -= zeroes[left]
left += 1
right += 1
if right == len(zeroes):
break
else:
curr += zeroes[right]
print(out)
``` | instruction | 0 | 48,935 | 0 | 97,870 |
No | output | 1 | 48,935 | 0 | 97,871 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a binary string s awesome, if it has at least 1 symbol 1 and length of the string is divisible by the number of 1 in it. In particular, 1, 1010, 111 are awesome, but 0, 110, 01010 aren't.
You are given a binary string s. Count the number of its awesome substrings.
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.
Input
The first line contains the string s (1 ≤ |s|≤ 200 000) consisting only of zeros and ones.
Output
Output a single number — the number of awesome substrings of s.
Examples
Input
111
Output
6
Input
01010
Output
10
Input
0000
Output
0
Input
1111100000
Output
25
Note
In the first sample, all substrings of s are awesome.
In the second sample, we have the following awesome substrings of s: 1 (2 times), 01 (2 times), 10 (2 times), 010 (2 times), 1010, 0101
In the third sample, no substring is awesome.
Submitted Solution:
```
from collections import Counter
s = input()
n = len(s)
LIMIT = max(int(n**.5/3),1)
out = 0
for rat in range(LIMIT):
seen = Counter()
count = 0
seen[0] = 1
for c in s:
if c == '0':
count += 1
else:
count -= rat
out += seen[count]
seen[count] += 1
zeroes = []
last = 0
for c in s:
if c == '0':
last += 1
else:
zeroes.append(last)
last = 0
zeroes.append(last)
MAX_ONES = n // LIMIT + 2
for size in range(1, MAX_ONES):
if size >= len(zeroes):
break
curr = sum(zeroes[:size + 1])
left = 0
right = size
while True:
min_size = (curr - zeroes[left] - zeroes[right]) // size
if min_size < LIMIT:
min_size = LIMIT - 1
max_size = curr // size
#Range: min_size
amount = max_size - min_size
if amount > 0:
"""
for i in range(min_size + 1, max_size + 1):
out += min(zeroes[left] + 1, zeroes[right] + 1, i * size + 1, curr - i * size + 1)
"""
#print(left, right, size, curr)
cutoff = min(zeroes[left], zeroes[right]) + 1
#Left Range
smol = min_size + 1
tol = max((cutoff - 1) // size, min_size)
#print(((tol - smol + 1) * ((smol + tol) * size + 2)) // 2)
out += ((tol - smol + 1) * ((smol + tol) * size + 2)) // 2
#Mid Range
smol = tol + 1
tol = min(max_size + 1, (curr - cutoff) // size)
#print((tol - smol + 1) * cutoff)
out += (tol - smol + 1) * cutoff
#Right Range
smol = tol + 1
tol = max_size
#print(smol, tol)
#print(((tol - smol + 1) * ((curr - smol + curr - tol) * size + 2)) // 2)
out += ((tol - smol + 1) * ((curr - smol * size + curr - tol * size)+ 2)) // 2
curr -= zeroes[left]
left += 1
right += 1
if right == len(zeroes):
break
else:
curr += zeroes[right]
print(out)
``` | instruction | 0 | 48,936 | 0 | 97,872 |
No | output | 1 | 48,936 | 0 | 97,873 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that:
1. choose any non-empty string from strings s1, s2, ..., sn;
2. choose an arbitrary character from the chosen string and write it on a piece of paper;
3. remove the chosen character from the chosen string.
Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.
There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).
Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
Input
The first line of the input contains string t — the string that you need to build.
The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si.
All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
Output
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
Examples
Input
bbaze
3
bzb 2
aeb 3
ba 10
Output
8
Input
abacaba
4
aba 2
bcc 1
caa 2
bbb 5
Output
18
Input
xyz
4
axx 8
za 1
efg 4
t 1
Output
-1
Note
Notes to the samples:
In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.
In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.
In the third sample the solution doesn't exist because there is no character "y" in given strings. | instruction | 0 | 49,125 | 0 | 98,250 |
Tags: flows, graphs
Correct Solution:
```
class Edge:
def __init__(self, to, cost, capacity, next_edge):
self.to = to
self.cost = cost
self.origin_cost = cost
self.capacity = capacity
self.next_edge = next_edge
self.pair = None
class MinCostMaxFlow:
def __init__(self, max_node):
self.null = Edge(0, 0, 0, None)
self.max_node = max_node + 3
self.total_cost = 0
self.current_cost = 0
self.visited = [False] * self.max_node
self.arc_list = []
self.edge_head = [self.null] * self.max_node
self.source = max_node + 1
self.sink = max_node + 2
def AddArcWithCapacityAndUnitCost(self, start_node, end_node, capacity, cost):
self.edge_head[start_node] = Edge(end_node, cost, capacity, self.edge_head[start_node])
self.edge_head[end_node] = Edge(start_node, -cost, 0, self.edge_head[end_node])
self.edge_head[start_node].pair = self.edge_head[end_node]
self.edge_head[end_node].pair = self.edge_head[start_node]
if start_node != self.source and start_node != self.sink and end_node != self.source and end_node != self.sink:
self.arc_list.append(self.edge_head[end_node])
def NumArcs(self):
return len(self.arc_list)
def Tail(self, index):
return self.arc_list[index].to
def Head(self, index):
return self.arc_list[index].pair.to
def UnitCost(self, index):
return self.arc_list[index].pair.origin_cost
def Flow(self, index):
return self.arc_list[index].capacity
def OptimalFlow(self):
edge = self.edge_head[self.sink]
total_flow = 0
while id(edge) != id(self.null):
total_flow += edge.capacity
edge = edge.next_edge
return total_flow
def OptimalCost(self):
return self.total_cost
def SetNodeSupply(self, node, supply):
if supply > 0:
self.AddArcWithCapacityAndUnitCost(self.source, node, supply, 0)
elif supply < 0:
self.AddArcWithCapacityAndUnitCost(node, self.sink, -supply, 0)
def aug(self, node_id, total_flow):
if node_id == self.sink:
self.total_cost += self.current_cost * total_flow
return total_flow
self.visited[node_id] = True
flow = total_flow
edge = self.edge_head[node_id]
while id(edge) != id(self.null):
if edge.capacity > 0 and edge.cost == 0 and not self.visited[edge.to]:
delta = self.aug(edge.to, min(flow, edge.capacity))
edge.capacity -= delta
edge.pair.capacity += delta
flow -= delta
if flow == 0:
return total_flow
edge = edge.next_edge
return total_flow - flow
def modify_label(self):
min_cost = 1 << 63
for node_id in range(0, self.max_node):
if not self.visited[node_id]:
continue
edge = self.edge_head[node_id]
while id(edge) != id(self.null):
if edge.capacity > 0 and not self.visited[edge.to] and edge.cost < min_cost:
min_cost = edge.cost
edge = edge.next_edge
if min_cost == 1 << 63:
return False
for node_id in range(0, self.max_node):
if not self.visited[node_id]:
continue
edge = self.edge_head[node_id]
while id(edge) != id(self.null):
edge.cost -= min_cost
edge.pair.cost += min_cost
edge = edge.next_edge
self.current_cost += min_cost
return True
def Solve(self):
while True:
while True:
self.visited = [False] * self.max_node
if self.aug(self.source, 1 << 63) == 0:
break
if not self.modify_label():
break
return self.total_cost
def main():
s = input()
n = int(input())
source = 0
sink = n + 26 + 1
mcmf = MinCostMaxFlow(n + 28)
length = len(s)
num = [0] * 29
for i in range(0, length):
num[ord(s[i]) - ord('a') + 1] += 1
for i in range(1, 27):
if num[i] > 0:
mcmf.AddArcWithCapacityAndUnitCost(i, sink, num[i], 0)
for i in range(1, n + 1):
s, used = input().split(' ')
mcmf.AddArcWithCapacityAndUnitCost(source, 26 + i, int(used), 0)
num = [0] * 29
for j in range(0, len(s)):
num[ord(s[j]) - ord('a') + 1] += 1
for j in range(1, 27):
if num[j] > 0:
mcmf.AddArcWithCapacityAndUnitCost(26 + i, j, num[j], i)
mcmf.SetNodeSupply(source, 1 << 63)
mcmf.SetNodeSupply(sink, -(1 << 63))
mcmf.Solve()
if mcmf.OptimalFlow() != length:
print("-1")
else:
print(mcmf.OptimalCost())
if __name__ == '__main__':
main()
``` | output | 1 | 49,125 | 0 | 98,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that:
1. choose any non-empty string from strings s1, s2, ..., sn;
2. choose an arbitrary character from the chosen string and write it on a piece of paper;
3. remove the chosen character from the chosen string.
Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.
There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).
Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
Input
The first line of the input contains string t — the string that you need to build.
The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si.
All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
Output
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
Examples
Input
bbaze
3
bzb 2
aeb 3
ba 10
Output
8
Input
abacaba
4
aba 2
bcc 1
caa 2
bbb 5
Output
18
Input
xyz
4
axx 8
za 1
efg 4
t 1
Output
-1
Note
Notes to the samples:
In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.
In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.
In the third sample the solution doesn't exist because there is no character "y" in given strings. | instruction | 0 | 49,126 | 0 | 98,252 |
Tags: flows, graphs
Correct Solution:
```
from heapq import heappush, heappop
class MinCostFlow:
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap, cost):
G = self.G
G[fr].append([to, cap, cost, len(G[to])])
G[to].append([fr, 0, -cost, len(G[fr])-1])
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0]*N
prv_v = [0]*N
prv_e = [0]*N
while f:
dist = [INF]*N
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
for i, (w, cap, cost, _) in enumerate(G[v]):
if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w]:
dist[w] = r = dist[v] + cost + H[v] - H[w]
prv_v[w] = v; prv_e[w] = i
heappush(que, (r, w))
if dist[t] == INF:
return -1
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, G[prv_v[v]][prv_e[v]][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = G[prv_v[v]][prv_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prv_v[v]
return res
T = input()
need = [0] * 30
for t in T:
need[ord(t) - ord('a')] += 1
have = [[0] * 30 for _ in range(110)]
N = int(input())
a = [0] * 110
for i in range(N):
v = input().split()
S = v[0]
a[i] = int(v[1])
for s in S:
have[i][ord(s)-ord('a')] += 1
V = 30 + N + 10
flow = MinCostFlow(V)
start = 30 + N + 5
target = 30 + N + 6
for c in range(26):
flow.add_edge(start, c, need[c], 0)
for j in range(N):
flow.add_edge(c, 30+j, have[j][c], 0)
for i in range(N):
flow.add_edge(30+i, target, a[i], i+1)
ans = flow.flow(start, target, len(T))
print(ans)
``` | output | 1 | 49,126 | 0 | 98,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that:
1. choose any non-empty string from strings s1, s2, ..., sn;
2. choose an arbitrary character from the chosen string and write it on a piece of paper;
3. remove the chosen character from the chosen string.
Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.
There are other limitations, though. For each string si you know number ai — the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).
Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.
Input
The first line of the input contains string t — the string that you need to build.
The second line contains a single integer n (1 ≤ n ≤ 100) — the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≤ ai ≤ 100). Number ai represents the maximum number of characters that can be deleted from string si.
All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
Output
Print a single number — the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.
Examples
Input
bbaze
3
bzb 2
aeb 3
ba 10
Output
8
Input
abacaba
4
aba 2
bcc 1
caa 2
bbb 5
Output
18
Input
xyz
4
axx 8
za 1
efg 4
t 1
Output
-1
Note
Notes to the samples:
In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" и "b" with price 2 rubles. The price of the string t in this case is 2·1 + 3·2 = 8.
In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2·1 + 1·2 + 2·3 + 2·4 = 18.
In the third sample the solution doesn't exist because there is no character "y" in given strings.
Submitted Solution:
```
class Edge:
def __init__(self, to, cost, capacity, next_edge):
self.to = to
self.cost = cost
self.origin_cost = cost
self.capacity = capacity
self.next_edge = next_edge
self.pair = None
class MinCostMaxFlow:
def __init__(self, max_node):
self.null = Edge(0, 0, 0, None)
self.max_node = max_node + 3
self.total_cost = 0
self.current_cost = 0
self.visited = [False] * self.max_node
self.arc_list = []
self.edge_head = [self.null] * self.max_node
self.source = max_node + 1
self.sink = max_node + 2
def AddArcWithCapacityAndUnitCost(self, start_node, end_node, capacity, cost):
self.edge_head[start_node] = Edge(end_node, cost, capacity, self.edge_head[start_node])
self.edge_head[end_node] = Edge(start_node, -cost, 0, self.edge_head[end_node])
self.edge_head[start_node].pair = self.edge_head[end_node]
self.edge_head[end_node].pair = self.edge_head[start_node]
if start_node != self.source and start_node != self.sink and end_node != self.source and end_node != self.sink:
self.arc_list.append(self.edge_head[end_node])
def NumArcs(self):
return len(self.arc_list)
def Tail(self, index):
return self.arc_list[index].to
def Head(self, index):
return self.arc_list[index].pair.to
def UnitCost(self, index):
return self.arc_list[index].pair.origin_cost
def Flow(self, index):
return self.arc_list[index].capacity
def OptimalFlow(self):
edge = self.edge_head[self.sink]
total_flow = 0
while id(edge) != id(self.null):
total_flow += edge.capacity
edge = edge.next_edge
return total_flow
def OptimalCost(self):
return self.total_cost
def SetNodeSupply(self, node, supply):
if supply > 0:
self.AddArcWithCapacityAndUnitCost(self.source, node, supply, 0)
elif supply < 0:
self.AddArcWithCapacityAndUnitCost(node, self.sink, -supply, 0)
def aug(self, node_id, total_flow):
if node_id == self.sink:
self.total_cost += self.current_cost * total_flow
return total_flow
self.visited[node_id] = True
flow = total_flow
edge = self.edge_head[node_id]
while id(edge) != id(self.null):
if edge.capacity > 0 and edge.cost == 0 and not self.visited[edge.to]:
delta = self.aug(edge.to, min(flow, edge.capacity))
edge.capacity -= delta
edge.pair.capacity += delta
flow -= delta
if flow == 0:
return total_flow
edge = edge.next_edge
return total_flow - flow
def modify_label(self):
min_cost = 1 << 63
for node_id in range(0, self.max_node):
if not self.visited[node_id]:
continue
edge = self.edge_head[node_id]
while id(edge) != id(self.null):
if edge.capacity > 0 and not self.visited[edge.to] and edge.cost < min_cost:
min_cost = edge.cost
edge = edge.next_edge
if min_cost == 1 << 63:
return False
for node_id in range(0, self.max_node):
if not self.visited[node_id]:
continue
edge = self.edge_head[node_id]
while id(edge) != id(self.null):
edge.cost -= min_cost
edge.pair.cost += min_cost
edge = edge.next_edge
self.current_cost += min_cost
return True
def Solve(self):
while True:
while True:
self.visited = [False] * self.max_node
if self.aug(self.source, 1 << 63) == 0:
break
if not self.modify_label():
break
return self.total_cost
def main():
s = input()
length = len(s)
num = [0] * 28
for i in range(0, length):
v = ord(s[i]) - ord('a') + 1
num[v] += 1
n = int(input())
mcmf = MinCostMaxFlow(n + 28)
cnt = [[0] * 28] * (n + 28)
used = [0] * (n + 1)
for i in range(1, n + 1):
s, use = input().split(' ')
used[i] = int(use)
for j in range(0, len(s)):
v = ord(s[j]) - ord('a') + 1
cnt[i][v] += 1
source = 0
sink = n + 26 + 1
for i in range(1, 27):
if num[i] == 0:
continue
mcmf.AddArcWithCapacityAndUnitCost(source, i, num[i], 0)
for j in range(1, n + 1):
if cnt[j][i] == 0:
continue
mcmf.AddArcWithCapacityAndUnitCost(i, 26 + j, cnt[j][i], j)
for i in range(1, n + 1):
mcmf.AddArcWithCapacityAndUnitCost(i + 26, sink, used[i], 0)
mcmf.SetNodeSupply(source, 1 << 63)
mcmf.SetNodeSupply(sink, -(1 << 63))
mcmf.Solve()
if mcmf.OptimalFlow() != length:
print("-1")
else:
print(mcmf.OptimalCost())
if __name__ == '__main__':
main()
``` | instruction | 0 | 49,127 | 0 | 98,254 |
No | output | 1 | 49,127 | 0 | 98,255 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The first semester ended. You know, after the end of the first semester the holidays begin. On holidays Noora decided to return to Vičkopolis. As a modest souvenir for Leha, she brought a sausage of length m from Pavlopolis. Everyone knows that any sausage can be represented as a string of lowercase English letters, the length of which is equal to the length of the sausage.
Leha was very pleased with the gift and immediately ate the sausage. But then he realized that it was a quite tactless act, because the sausage was a souvenir! So the hacker immediately went to the butcher shop. Unfortunately, there was only another sausage of length n in the shop. However Leha was not upset and bought this sausage. After coming home, he decided to cut the purchased sausage into several pieces and number the pieces starting from 1 from left to right. Then he wants to select several pieces and glue them together so that the obtained sausage is equal to the sausage that Noora gave. But the hacker can glue two pieces together only when the number of the left piece is less than the number of the right piece. Besides he knows that if he glues more than x pieces, Noora will notice that he has falsified souvenir sausage and will be very upset. Of course Leha doesn’t want to upset the girl. The hacker asks you to find out whether he is able to cut the sausage he bought, and then glue some of the pieces so that Noora doesn't notice anything.
Formally, you are given two strings s and t. The length of the string s is n, the length of the string t is m. It is required to select several pairwise non-intersecting substrings from s, so that their concatenation in the same order as these substrings appear in s, is equal to the string t. Denote by f(s, t) the minimal number of substrings to be chosen so that their concatenation is equal to the string t. If it is impossible to choose such substrings, then f(s, t) = ∞. Leha really wants to know whether it’s true that f(s, t) ≤ x.
Input
The first line contains single integer n (1 ≤ n ≤ 105) — length of sausage bought by Leha, i.e. the length of the string s.
The second line contains string s of the length n consisting of lowercase English letters.
The third line contains single integer m (1 ≤ m ≤ n) — length of sausage bought by Noora, i.e. the length of the string t.
The fourth line contains string t of the length m consisting of lowercase English letters.
The fifth line contains single integer x (1 ≤ x ≤ 30) — the maximum number of pieces of sausage that Leha can glue so that Noora doesn’t notice anything.
Output
In the only line print "YES" (without quotes), if Leha is able to succeed in creating new sausage so that Noora doesn't notice anything. Otherwise print "NO" (without quotes).
Examples
Input
9
hloyaygrt
6
loyyrt
3
Output
YES
Input
9
hloyaygrt
6
loyyrt
2
Output
NO
Note
Let's consider the first sample.
In the optimal answer, Leha should cut the sausage he bought in the following way: hloyaygrt = h + loy + a + y + g + rt. Then he numbers received parts from 1 to 6:
* h — number 1
* loy — number 2
* a — number 3
* y — number 4
* g — number 5
* rt — number 6
Hereupon the hacker should glue the parts with numbers 2, 4 and 6 and get sausage loyygrt equal to one that is given by Noora. Thus, he will have to glue three pieces. Since x = 3 you should print "YES" (without quotes).
In the second sample both sausages coincide with sausages from the first sample. However since x = 2 you should print "NO" (without quotes).
Submitted Solution:
```
x = int(input())
a = input()
y = int(input())
b = input()
n = int(input())
t = dict()
s = {b[0]:[0]}
l = 0
for i in range(y):
t[i] = 31
for i in range(x):
if a[i] in s:
for j in s[a[i]]:
if j == 0:
t[j] = 1
else:
if a[i-1] == b[j-1]:
t[j] = t[j-1]
elif t[j] > t[j-1] + 1:
t[j] = t[j-1] + 1
if l in s[a[i]]:
l += 1
if l < y:
if b[l] in s:
s[b[l]].append(l)
else:
s[b[l]] = [l]
if t[y-1] <= n:
print('YES')
else:
print('NO')
``` | instruction | 0 | 49,352 | 0 | 98,704 |
No | output | 1 | 49,352 | 0 | 98,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the Byteland State University marks are strings of the same length. Mark x is considered better than y if string y is lexicographically smaller than x.
Recently at the BSU was an important test work on which Vasya recived the mark a. It is very hard for the teacher to remember the exact mark of every student, but he knows the mark b, such that every student recieved mark strictly smaller than b.
Vasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.
More formally: you are given two strings a, b of the same length and you need to figure out the number of different strings c such that:
1) c can be obtained from a by swapping some characters, in other words c is a permutation of a.
2) String a is lexicographically smaller than c.
3) String c is lexicographically smaller than b.
For two strings x and y of the same length it is true that x is lexicographically smaller than y if there exists such i, that x1 = y1, x2 = y2, ..., xi - 1 = yi - 1, xi < yi.
Since the answer can be very large, you need to find answer modulo 109 + 7.
Input
First line contains string a, second line contains string b. Strings a, b consist of lowercase English letters. Their lengths are equal and don't exceed 106.
It is guaranteed that a is lexicographically smaller than b.
Output
Print one integer — the number of different strings satisfying the condition of the problem modulo 109 + 7.
Examples
Input
abc
ddd
Output
5
Input
abcdef
abcdeg
Output
0
Input
abacaba
ubuduba
Output
64
Note
In first sample from string abc can be obtained strings acb, bac, bca, cab, cba, all of them are larger than abc, but smaller than ddd. So the answer is 5.
In second sample any string obtained from abcdef is larger than abcdeg. So the answer is 0.
Submitted Solution:
```
syms = [
{
"val": 1,
"sym": "a"
},{
"val": 2,
"sym": "b"
},{
"val": 3,
"sym": "c"
},{
"val": 4,
"sym": "d"
},{
"val": 5,
"sym": "e"
},{
"val": 6,
"sym": "f"
},{
"val": 7,
"sym": "g"
},{
"val": 8,
"sym": "h"
},{
"val": 9,
"sym": "i"
},{
"val": 10,
"sym": "j"
},{
"val": 11,
"sym": "k"
},{
"val": 12,
"sym": "l"
},{
"val": 13,
"sym": "m"
},{
"val": 14,
"sym": "n"
},{
"val": 15,
"sym": "o"
},{
"val": 16,
"sym": "p"
},{
"val": 17,
"sym": "q"
},{
"val": 18,
"sym": "r"
},{
"val": 19,
"sym": "s"
},{
"val": 20,
"sym": "t"
},{
"val": 21,
"sym": "u"
},{
"val": 22,
"sym": "v"
},{
"val": 23,
"sym": "w"
},{
"val": 24,
"sym": "x"
},{
"val": 25,
"sym": "y"
},{
"val": 26,
"sym": "z"
},
]
import itertools
str1 = input()
str2 = input()
def To(tup):
arr = []
ans = 0
for i in tup:
for j in syms:
if i == j['sym']:
arr.append(j['val'])
j = 0
arr = reversed(arr)
for i in arr:
ans += i * 26 ** j
j+=1
return ans
ans = 0
arr1 = list(itertools.permutations(str1, len(str1)))
k = To(str1)
k2 = To(str2)
art = set()
j = 0
for i in arr1:
p = To(i)
art.add(p)
arr1.pop(j)
j+=1
for i in art:
if i > k and i < k2:
ans += 1
print(ans)
``` | instruction | 0 | 49,357 | 0 | 98,714 |
No | output | 1 | 49,357 | 0 | 98,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the Byteland State University marks are strings of the same length. Mark x is considered better than y if string y is lexicographically smaller than x.
Recently at the BSU was an important test work on which Vasya recived the mark a. It is very hard for the teacher to remember the exact mark of every student, but he knows the mark b, such that every student recieved mark strictly smaller than b.
Vasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.
More formally: you are given two strings a, b of the same length and you need to figure out the number of different strings c such that:
1) c can be obtained from a by swapping some characters, in other words c is a permutation of a.
2) String a is lexicographically smaller than c.
3) String c is lexicographically smaller than b.
For two strings x and y of the same length it is true that x is lexicographically smaller than y if there exists such i, that x1 = y1, x2 = y2, ..., xi - 1 = yi - 1, xi < yi.
Since the answer can be very large, you need to find answer modulo 109 + 7.
Input
First line contains string a, second line contains string b. Strings a, b consist of lowercase English letters. Their lengths are equal and don't exceed 106.
It is guaranteed that a is lexicographically smaller than b.
Output
Print one integer — the number of different strings satisfying the condition of the problem modulo 109 + 7.
Examples
Input
abc
ddd
Output
5
Input
abcdef
abcdeg
Output
0
Input
abacaba
ubuduba
Output
64
Note
In first sample from string abc can be obtained strings acb, bac, bca, cab, cba, all of them are larger than abc, but smaller than ddd. So the answer is 5.
In second sample any string obtained from abcdef is larger than abcdeg. So the answer is 0.
Submitted Solution:
```
a = input().strip()
b = input().strip()
MOD = 10**9 + 7
f = [1]*(10**6+1)
inv = [1]*(10**6 + 1)
st = 1
for i in range(1, 10**6 + 1):
st = st*i % MOD
f[i] = st
if i < 10**5:
inv[i] = pow(st, MOD - 2, MOD)
def ways(sez):
vrni = f[sum(sez)]
for x in sez:
if x < len(inv):
vrni = vrni*inv[x] % MOD
else:
vrni = vrni*pow(f[x],MOD-2,MOD) % MOD
return vrni % MOD
koliko = [0]*26
for znak in a:
koliko[ord(znak) - 97] += 1
koliko2 = koliko[:]
def calc(s, koliko):
ALL = 0
for znak in s:
tag = ord(znak) - 97
for i in range(tag):
if koliko[i] > 0:
koliko[i] -= 1
ALL += ways(koliko)
ALL = ALL % MOD
koliko[i] += 1
if koliko[tag] >= 1:
koliko[tag] -= 1
else:
break
return ALL % MOD
print((calc(b,koliko) - calc(a,koliko) - 1) % MOD)
``` | instruction | 0 | 49,358 | 0 | 98,716 |
No | output | 1 | 49,358 | 0 | 98,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the Byteland State University marks are strings of the same length. Mark x is considered better than y if string y is lexicographically smaller than x.
Recently at the BSU was an important test work on which Vasya recived the mark a. It is very hard for the teacher to remember the exact mark of every student, but he knows the mark b, such that every student recieved mark strictly smaller than b.
Vasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.
More formally: you are given two strings a, b of the same length and you need to figure out the number of different strings c such that:
1) c can be obtained from a by swapping some characters, in other words c is a permutation of a.
2) String a is lexicographically smaller than c.
3) String c is lexicographically smaller than b.
For two strings x and y of the same length it is true that x is lexicographically smaller than y if there exists such i, that x1 = y1, x2 = y2, ..., xi - 1 = yi - 1, xi < yi.
Since the answer can be very large, you need to find answer modulo 109 + 7.
Input
First line contains string a, second line contains string b. Strings a, b consist of lowercase English letters. Their lengths are equal and don't exceed 106.
It is guaranteed that a is lexicographically smaller than b.
Output
Print one integer — the number of different strings satisfying the condition of the problem modulo 109 + 7.
Examples
Input
abc
ddd
Output
5
Input
abcdef
abcdeg
Output
0
Input
abacaba
ubuduba
Output
64
Note
In first sample from string abc can be obtained strings acb, bac, bca, cab, cba, all of them are larger than abc, but smaller than ddd. So the answer is 5.
In second sample any string obtained from abcdef is larger than abcdeg. So the answer is 0.
Submitted Solution:
```
a = input().strip()
b = input().strip()
MOD = 10**9 + 7
f = [1]*(10**6+1)
inv = [1]*(10**6 + 1)
st = 1
for i in range(1, 10**6 + 1):
st = st*i % MOD
f[i] = st
if i < 10**5:
inv[i] = pow(st, MOD - 2, MOD)
def ways(sez):
vrni = f[sum(sez)]
for x in sez:
if x < len(inv):
vrni = vrni*inv[x] % MOD
else:
vrni = vrni*pow(f[x],MOD-2,MOD) % MOD
return vrni
koliko = [0]*26
for znak in a:
koliko[ord(znak) - 97] += 1
koliko2 = koliko[:]
def calc(s, koliko):
ALL = 0
for znak in s:
tag = ord(znak) - 97
for i in range(tag):
if koliko[i] > 0:
koliko[i] -= 1
ALL += ways(koliko)
koliko[i] += 1
if koliko[tag] >= 1:
koliko[tag] -= 1
else:
break
return ALL
print(calc(b,koliko) - calc(a,koliko) - 1)
``` | instruction | 0 | 49,359 | 0 | 98,718 |
No | output | 1 | 49,359 | 0 | 98,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
At the Byteland State University marks are strings of the same length. Mark x is considered better than y if string y is lexicographically smaller than x.
Recently at the BSU was an important test work on which Vasya recived the mark a. It is very hard for the teacher to remember the exact mark of every student, but he knows the mark b, such that every student recieved mark strictly smaller than b.
Vasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.
More formally: you are given two strings a, b of the same length and you need to figure out the number of different strings c such that:
1) c can be obtained from a by swapping some characters, in other words c is a permutation of a.
2) String a is lexicographically smaller than c.
3) String c is lexicographically smaller than b.
For two strings x and y of the same length it is true that x is lexicographically smaller than y if there exists such i, that x1 = y1, x2 = y2, ..., xi - 1 = yi - 1, xi < yi.
Since the answer can be very large, you need to find answer modulo 109 + 7.
Input
First line contains string a, second line contains string b. Strings a, b consist of lowercase English letters. Their lengths are equal and don't exceed 106.
It is guaranteed that a is lexicographically smaller than b.
Output
Print one integer — the number of different strings satisfying the condition of the problem modulo 109 + 7.
Examples
Input
abc
ddd
Output
5
Input
abcdef
abcdeg
Output
0
Input
abacaba
ubuduba
Output
64
Note
In first sample from string abc can be obtained strings acb, bac, bca, cab, cba, all of them are larger than abc, but smaller than ddd. So the answer is 5.
In second sample any string obtained from abcdef is larger than abcdeg. So the answer is 0.
Submitted Solution:
```
MOD = int(1e9 + 7) #primo para el módulo
pows = 0
fact = 0
n = 0
def perms(m, nums):
"""
Entradas:
m -> entero con la cantidad total de elementos a permutar
nums -> lista de enteros donde la posicón i tiene las ocurrencias del i-ésimo elemento
Descripción:
Función que calcula las permutaciones distintas de un multiconjunto módulo MOD
Salida:
perm -> entero con las permutaciones distintas de un multiconjunto módulo MOD
"""
perm = fact[m] #Guardamos el factorial de m
for i in range(m): #Por cada ocurrencia del elemento i
perm = perm * pow(int(fact[nums[i]]), MOD-2, MOD) % MOD #Se divide el factorial de las ocurrencias de i
return int(perm)
def res(s1, s2):
"""
Entradas:
s1 -> string
s2 -> string
Descripción:
Dados dos strings s1 y s2, se devuelve la cantidad de permutaciones del string s1 que son
menores que s2
Salida:
cant -> cantidad de permutaciones del string s1 que son menores que s2
"""
cant = 0 #cantidad de permutaciones del string s1 que son menores que s2
abc = [0]*30 #ocurrencias de cada letra en s1
for i in range(n):
abc[ord(s1[i]) - ord('a')] += 1 #se cuentan las ocurrencias de cada letra en s1
actFact = perms(n, abc)#Se guarda las permutaciones distintas de las letras de s1 módulo MOD
for i in range(n):#Se fija un prefijo m de tamaño i en s2
for j in range(ord(s2[i]) - ord('a')):
if abc[j] > 0: #Si la letra prefijo está en s1, esto es también que no se ha usado anteriormente
actFact = actFact * pows[n - i] % MOD #...
actFact = actFact * abc[j] % MOD #Se multiplica por las ocurrencias de las letras menores que el final del prefijo
cant = (cant + actFact) % MOD #Se actualiza el resultado
actFact = actFact * (n - i) % MOD #...
actFact = actFact * pows[abc[j]] % MOD #Se sacan de la permutación los elementos que se usaron en el prefijo
if abc[ord(s2[i]) - ord('a')] == 0: #Si la letra de s2 no está en s1 el prefijo no se puede formar el prefijo de tamaño i+1
break
else:
actFact = actFact * pows[n - i] % MOD #Se quitan del factorial las repeticiones de ...
actFact = actFact * abc[ord(s2[i]) - ord('a')] % MOD #...
abc[ord(s2[i]) - ord('a')]-= 1 #Se quita la letra que se usó
return int(cant)
def Main():
global pows
global fact
global n
s1 = input()
s2 = input()
n = len(s1)
fact = [0]*(n+1) #fact[i] -> i!
pows = [0]*(n+1) #pows[i] -> i^(MOD-2)% MOD
fact[0] = 1
for i in range(1, n+1): #Se le da valor a fact y a pows
fact[i] = (fact[i-1]* i) % MOD
pows[i] = pow(i, MOD-2, MOD)
sol = 0
if s1 < s2:
sol = res(s1, s2) - res(s1, s1) - 1
else:
sol = res(s1, s2)
if sol < 0:
sol += MOD
print(sol)
Main()
``` | instruction | 0 | 49,360 | 0 | 98,720 |
No | output | 1 | 49,360 | 0 | 98,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.
For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string t matches the given string s, print "YES", otherwise print "NO".
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the length of the string s and the length of the string t, respectively.
The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string t of length m, which consists only of lowercase Latin letters.
Output
Print "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).
Examples
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
Note
In the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO". | instruction | 0 | 49,619 | 0 | 99,238 |
Tags: brute force, implementation, strings
Correct Solution:
```
from string import printable
#print(printable[10:36])
n,m = (input().split(" "))
#n=int(input())
#m=int(input())
#s,t = (input().split(" "))
s=(input())
t=(input())
if int(n)>int(int(m)+1):
print("NO")
exit(0)
if int(n)<=int(int(m)+1):
if '*' in s:
x = s.split('*')
#print(x)
h=len(x[1] )
z=len(x[0] )
#print( t[len(t)-h:] )
if x[0] == t[:z] and x[1] == t[len(t)-h:] :
print("YES")
else:
print("NO")
else:
if s!=t:
print("NO")
else:
print("YES")
``` | output | 1 | 49,619 | 0 | 99,239 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.
For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string t matches the given string s, print "YES", otherwise print "NO".
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the length of the string s and the length of the string t, respectively.
The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string t of length m, which consists only of lowercase Latin letters.
Output
Print "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).
Examples
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
Note
In the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO". | instruction | 0 | 49,620 | 0 | 99,240 |
Tags: brute force, implementation, strings
Correct Solution:
```
n, m = [int(x) for x in str(input()).split(' ', 1)]
s = str(input().strip())
t = str(input().strip())
s = s.split('*', 1)
# print(s, len(s))
if len(s) == 1:
if s[0] == t:
print('YES')
else:
print('NO')
elif s == ['', '']:
print('YES')
else:
# print(s, m - len(s[1]), len(s[0]), t[:len(s[0])], t[m-len(s[1]):])
if m - len(s[1]) < len(s[0]):
print('NO')
elif t[:len(s[0])] == s[0] and t[m - len(s[1]):] == s[1]:
print('YES')
else:
print('NO')
``` | output | 1 | 49,620 | 0 | 99,241 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.
For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string t matches the given string s, print "YES", otherwise print "NO".
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the length of the string s and the length of the string t, respectively.
The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string t of length m, which consists only of lowercase Latin letters.
Output
Print "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).
Examples
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
Note
In the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO". | instruction | 0 | 49,621 | 0 | 99,242 |
Tags: brute force, implementation, strings
Correct Solution:
```
n, m = map(int,input().split())
s = input()
t = input()
ans = ''
if n - 1 > m:
ans = 'NO'
else:
if '*' not in s:
if s == t:
ans = 'YES'
else:
ans = 'NO'
else:
if s[:s.index('*')] == t[:s.index('*')] and s[s.index('*')+1:] == t[len(t) - (len(s)-1-s.index('*')):]:
ans = 'YES'
else:
ans = "NO"
print(ans)
``` | output | 1 | 49,621 | 0 | 99,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.
For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string t matches the given string s, print "YES", otherwise print "NO".
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the length of the string s and the length of the string t, respectively.
The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string t of length m, which consists only of lowercase Latin letters.
Output
Print "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).
Examples
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
Note
In the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO". | instruction | 0 | 49,622 | 0 | 99,244 |
Tags: brute force, implementation, strings
Correct Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def solve():
n, m = map(int, input().split())
s, t = input().strip(), input().strip()
if s.find("*") >= 0:
ai = s.find("*")
if t.find(s[:ai]) != 0:
print("NO")
return
if ai == n - 1:
print("YES")
else:
t2 = t[ai:]
i2 = t2.rfind(s[ai + 1:])
print("YES" if 0 <= i2 and t2[i2:] == s[ai + 1:] else "NO")
else:
print("YES" if s == t else "NO")
if __name__ == "__main__":
solve()
``` | output | 1 | 49,622 | 0 | 99,245 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.
For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string t matches the given string s, print "YES", otherwise print "NO".
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the length of the string s and the length of the string t, respectively.
The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string t of length m, which consists only of lowercase Latin letters.
Output
Print "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).
Examples
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
Note
In the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO". | instruction | 0 | 49,623 | 0 | 99,246 |
Tags: brute force, implementation, strings
Correct Solution:
```
n,m=map(int,input().split())
s,t=input(),input()
if s.count("*")==0 :
if s==t :
exit( print("YES"))
else :
exit(print("NO"))
a,b=s.split("*")
l1=len(a)
l2=len(b)
#print(a)
#print(t[:l1])
if a==t[:l1] :
if (m+1 )>=n :
# print("sdsdsd")
#print(b,t[m-l2:m])
if b==t[m-l2:m]:
exit( print("YES"))
else :
exit(print("NO"))
else :
exit( print("NO"))
else :
exit( print("NO"))
``` | output | 1 | 49,623 | 0 | 99,247 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.
For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string t matches the given string s, print "YES", otherwise print "NO".
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the length of the string s and the length of the string t, respectively.
The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string t of length m, which consists only of lowercase Latin letters.
Output
Print "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).
Examples
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
Note
In the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO". | instruction | 0 | 49,624 | 0 | 99,248 |
Tags: brute force, implementation, strings
Correct Solution:
```
n,m=map(int,input().split())
s1=list(input())
s2=input()
i=0
seen=0
j=0
if '*' not in s1:
if ''.join(s1)!=s2:
print('NO')
exit()
while i<n and j<m:
if s1[i]=='*':
seen=1
break
i+=1
if not seen:
if s1[i]!=s2[j]:
print('NO')
exit()
else:
i+=1
j+=1
i=n-1
seen=0
j=m-1
while i>=0 and j>=0:
if s1[i]=='*':
seen=1
break
if not seen:
if s1[i]!=s2[j]:
print('NO')
exit()
else:
i-=1
j-=1
if '*' in s1:
s1.remove('*')
s1=''.join(s1)
n=len(s1)
i=0
j= 0
c=0
while i<n and j<m:
if s1[i]==s2[j]:
i+=1
j+=1
c+=1
else:
j+=1
print('YES' if c==n else 'NO')
``` | output | 1 | 49,624 | 0 | 99,249 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.
For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string t matches the given string s, print "YES", otherwise print "NO".
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the length of the string s and the length of the string t, respectively.
The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string t of length m, which consists only of lowercase Latin letters.
Output
Print "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).
Examples
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
Note
In the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO". | instruction | 0 | 49,625 | 0 | 99,250 |
Tags: brute force, implementation, strings
Correct Solution:
```
n, m = [int(j) for j in input().split()]
s = input()
t = input()
if s == '*':
print('YES')
exit(0)
if len(s) - 1 > len(t):
print('NO')
exit(0)
a = s.split('*')
# print(len(a))
if len(a) == 1 and s != t:
print('NO')
exit(0)
elif len(a) == 1 and s == t:
print('YES')
exit(0)
if len(a) == 2:
s1 = t[:len(a[0])]
s2 = t[-len(a[1]):]
if len(a[0]) == 0:
if s2 == a[0] + a[1]:
print("YES")
exit(0)
else:
print('NO')
exit(0)
if len(a[1]) == 0:
if s1 == a[0] + a[1]:
print('YES')
exit(0)
else:
print('NO')
exit(0)
if s1 + s2 == a[0] + a[1]:
print('YES')
else:
print('NO')
``` | output | 1 | 49,625 | 0 | 99,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of s can be replaced with anything. If it is possible to replace a wildcard character '*' in s to obtain a string t, then the string t matches the pattern s.
For example, if s="aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string t matches the given string s, print "YES", otherwise print "NO".
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5) — the length of the string s and the length of the string t, respectively.
The second line contains string s of length n, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string t of length m, which consists only of lowercase Latin letters.
Output
Print "YES" (without quotes), if you can obtain the string t from the string s. Otherwise print "NO" (without quotes).
Examples
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
Note
In the first example a wildcard character '*' can be replaced with a string "force". So the string s after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string s after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string t so the answer is "NO". | instruction | 0 | 49,626 | 0 | 99,252 |
Tags: brute force, implementation, strings
Correct Solution:
```
input()
a = input()
b = input()
a = a.split('*')
# print(a)
# print([b[:len(a[0])], b[-len(a[1]):]])
if len(a) == 1:
if a[0] == b:
print('YES')
else:
print('NO')
else:
if len(b) < len(a[0]) + len(a[1]) \
or (a[0] != b[:len(a[0])] and len(a[0]) > 0) \
or (a[1] != b[-len(a[1]):] and len(a[1]) > 0):
print('NO')
else:
print('YES')
``` | output | 1 | 49,626 | 0 | 99,253 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3. | instruction | 0 | 50,026 | 0 | 100,052 |
Tags: greedy
Correct Solution:
```
#compute hamming distance
# mark indexes that differ
#m_benefit=0,s_i,s_j
#for each i in index
# for each j in i+1
# swap i & j and see what is the benefit
# if benefit > m_benefit:
# m_ben=ben
# record m_i and m_j
#if m_ben = 0 then -1 -1
#else distance-benefit and print s_i+1&s_j+1
diff = []
wrong_t = {}
def distance(n,s,t):
count = 0
for i in range(n):
if s[i] != t[i]:
diff.append(i)
wrong_t[t[i]] = i
count+=1
return count
def minDistance():
m_ben = 0
m_i = -2
m_j = -2
for i in diff:
v = wrong_t[s[i]] if (s[i] in wrong_t) else None
if v != None:
m_ben = 1
m_i = i
m_j = v
if s[v] == t[i]:
return (2,i,v)
return (m_ben,m_i,m_j)
n = int(input())
s = input()
t = input()
d = distance(n,s,t)
m_ben,m_i,m_j = minDistance()
print(d - m_ben)
print("{0} {1}".format(m_i + 1,m_j + 1))
``` | output | 1 | 50,026 | 0 | 100,053 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3. | instruction | 0 | 50,027 | 0 | 100,054 |
Tags: greedy
Correct Solution:
```
import string
n, s, t = int(input()), input(), input()
x, i, j = 0, -1, -1
sc_dict = {c: set() for c in string.ascii_lowercase}
tc_dict = {c: set() for c in string.ascii_lowercase}
sti_dict, tsi_dict = dict(), dict()
for ci, sc, tc in zip(range(n), s, t):
if sc == tc:
continue
sc_dict[sc].add(tc)
tc_dict[tc].add(sc)
sti_dict[sc + tc] = ci
tsi_dict[tc + sc] = ci
x += 1
for c in string.ascii_lowercase:
cs = sc_dict[c] & tc_dict[c]
if not cs:
continue
c2 = cs.pop()
x -= 2
i = sti_dict[c + c2] + 1
j = tsi_dict[c + c2] + 1
break
else:
for c in string.ascii_lowercase:
if not sc_dict[c] or not tc_dict[c]:
continue
x -= 1
i = sti_dict[c + sc_dict[c].pop()] + 1
j = tsi_dict[c + tc_dict[c].pop()] + 1
break
print(x)
print(i, j)
``` | output | 1 | 50,027 | 0 | 100,055 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3. | instruction | 0 | 50,028 | 0 | 100,056 |
Tags: greedy
Correct Solution:
```
n, s, t = int(input()), input(), input()
t_dict = dict()
diffs = list()
res_i, res_j = -1, -1
res_d = 0
for i in range(n):
if s[i] == t[i]:
continue
res_d += 1
diffs.append(i)
t_dict[t[i]] = i
perfect_swapped = False
swapped = False
for i in diffs:
if s[i] not in t_dict:
continue
swapped = True
res_i = i + 1
j = t_dict[s[i]]
res_j = j + 1
if s[j] == t[i]:
perfect_swapped = True
break
print(res_d - (2 if perfect_swapped else 1 if swapped else 0))
print(res_i, res_j)
``` | output | 1 | 50,028 | 0 | 100,057 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3. | instruction | 0 | 50,029 | 0 | 100,058 |
Tags: greedy
Correct Solution:
```
_,s,t=input(),input(),input()
d=0
p=[[-1 for _ in range(26)] for _ in range(26)]
a,b=[-1 for _ in range(26)],[-1 for _ in range(26)]
for i in range(len(s)):
if s[i]!=t[i]:
cs=ord(s[i])-97
ct=ord(t[i])-97
d+=1
p[cs][ct]=i+1
a[cs]=i+1
b[ct]=i+1
for i in range(26*26):
if p[i//26][i%26]>-1 and p[i%26][i//26]>-1:
print(d-2)
print(p[i//26][i%26],p[i%26][i//26])
break
else:
for i in range(26):
if a[i]>-1 and b[i]>-1:
print(d-1)
print(a[i],b[i])
break
else:
print(d)
print(-1,-1)
``` | output | 1 | 50,029 | 0 | 100,059 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3. | instruction | 0 | 50,030 | 0 | 100,060 |
Tags: greedy
Correct Solution:
```
n=int(input())
s=input()
t=input()
dis=0
d=[[False for i in range(30)] for i in range(30)]
x=[[0 for i in range(30)] for i in range(30)]
for i in range(n):
if s[i]!=t[i]:
dis+=1
d[ord(s[i])-ord('a')][ord(t[i])-ord('a')]=True
x[ord(s[i])-ord('a')][ord(t[i])-ord('a')]=i+1
def progress():
for i in range(26):
for j in range(26):
if (d[i][j]) and (d[j][i]):
print ("{}\n{} {}".format(dis-2,x[i][j],x[j][i]))
return 0
for i in range(26):
for j in range(26):
if d[i][j]:
for t in range(26):
if d[j][t]:
print ("{}\n{} {}".format(dis-1,x[i][j],x[j][t]))
return 0
print ("{}\n{} {}".format(dis,-1,-1))
progress()
``` | output | 1 | 50,030 | 0 | 100,061 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3. | instruction | 0 | 50,031 | 0 | 100,062 |
Tags: greedy
Correct Solution:
```
def solve():
r = 0
d = {}
for i in range(n):
if a[i] != b[i]:
r += 1
d[(a[i], b[i])] = i+1
symbols = [chr(ord('a') + i) for i in range(26)]
for i in symbols:
for j in symbols:
if (i, j) in d and (j, i) in d:
return(r-2, d[(i, j)], d[(j, i)])
for i in symbols:
for j in symbols:
for k in symbols:
if (i, j) in d and (j, k) in d:
return(r-1, d[(i, j)], d[(j, k)])
return(r, -1, -1)
n = int(input())
a = input()
b = input()
ans = solve()
print(ans[0], '\n', ans[1], ' ', ans[2], sep = '')
``` | output | 1 | 50,031 | 0 | 100,063 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3. | instruction | 0 | 50,032 | 0 | 100,064 |
Tags: greedy
Correct Solution:
```
xxx = 0
a1=[]
a2=[]
a = int(input())
x = input()
y = input()
of1=[]
of2=[]
a1 = {}
a2 = {}
for i in 'abcdefghijklmnopqrstuvwxyz':
a1[i] = []
a2[i] = []
for i in range(a):
if x[i]!=y[i]:
a1[x[i]].append(i+1)
a2[y[i]].append(i+1)
else:
xxx += 1
for i in 'abcdefghijklmnopqrstuvwxyz':
for j in 'abcdefghijklmnopqrstuvwxyz':
if j != i:
aa1 = a1[i]
bb1 = a2[j]
cc1 = a1[j]
dd1 = a2[i]
ee = set(aa1).intersection(bb1)
ff = set(cc1).intersection(dd1)
if ee!= set() and ff!=set():
print(a-xxx-2)
print(list(ee)[0], list(ff)[0])
quit()
for i in 'abcdefghijklmnopqrstuvwxyz':
for j in 'abcdefghijklmnopqrstuvwxyz':
if j != i:
aa1 = a1[i]
bb1 = a2[j]
cc1 = a1[j]
dd1 = a2[i]
ee = set(aa1).intersection(bb1)
ff = set(cc1).intersection(dd1)
if ee != set():
if cc1 == [] and dd1 == []:
print(a-xxx)
print(-1, -1)
quit()
print(a-xxx-1)
if len(cc1)>0:
print(list(ee)[0], cc1[0])
else:
print(list(ee)[0], dd1[0])
quit()
elif ff != set():
if aa1 == [] and bb1 == []:
print(a-xxx)
print(-1, -1)
quit()
print(a-xxx-1)
if len(aa1)>0:
print(list(ff)[0], aa1[0])
else:
print(list(ff)[0], bb1[0])
quit()
print(a-xxx)
print(-1, -1)
``` | output | 1 | 50,032 | 0 | 100,065 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3. | instruction | 0 | 50,033 | 0 | 100,066 |
Tags: greedy
Correct Solution:
```
n = int(input())
s = input()
t = input()
pair2ind = {}
letters_s = [0] * 26
letters_t = [0] * 26
non_common = set()
cnt = 0
for i in range(n):
if s[i] != t[i]:
pair2ind[(s[i], t[i])] = i + 1
letters_s[ord(s[i]) - ord('a')] = i + 1
letters_t[ord(t[i]) - ord('a')] = i + 1
non_common.add(i + 1)
cnt += 1
sim = -1
for i in range(26):
if letters_s[i] != 0 and letters_t[i] != 0:
sim = letters_s[i]
break
else:
print(cnt)
print(-1, -1)
exit()
for i in range(n):
if s[i] != t[i]:
if (t[i], s[i]) in pair2ind:
print(cnt - 2)
print(pair2ind[(s[i], t[i])], pair2ind[(t[i], s[i])])
exit()
non_common.remove(sim)
print(cnt - 1)
print(sim, letters_t[ord(s[sim-1]) - ord('a')])
exit()
``` | output | 1 | 50,033 | 0 | 100,067 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3.
Submitted Solution:
```
import sys
n = int(input())
s = input()
t = input()
arr = {}
f = 0
for idx in range(n):
if s[idx] != t[idx]:
f += 1
arr[ s[idx] + t[idx] ] = idx
for k in arr.keys():
if k[1] + k[0] in arr:
print(f - 2)
print(str(arr[k] + 1) + ' ' + str(arr[k[1] + k[0]] + 1))
sys.exit(0)
for k in arr.keys():
for l in arr.keys():
if k[0] == l[1] or k[1] == l[0]:
print(f - 1)
print(str(arr[k] + 1) + ' ' + str(arr[l] + 1))
sys.exit(0)
print(f)
print('-1 -1')
``` | instruction | 0 | 50,034 | 0 | 100,068 |
Yes | output | 1 | 50,034 | 0 | 100,069 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3.
Submitted Solution:
```
n = input()
s1,s2 = input(),input()
l2,l3 = [],[]
l1 = [[l2.append((s1[x] + s2[x],x)),l3.append((s2[x] + s1[x],x))] for x in range(len(s1)) if s1[x] != s2[x]]
d1,d2 = dict(l2),dict(l3)
ins = set(d1.keys()) & set(d2.keys())
if ins:
e = ins.pop()
print (len(l1) - 2)
print (d1[e] + 1,d2[e] + 1)
exit(0)
s1,s2 = {y[0][0]:y[1] for y in l2},{y[0][1]:y[1] for y in l2}
ins = set(s1.keys()) & set(s2.keys())
if ins:
e = ins.pop()
print (len(l1) - 1)
print (s1[e] + 1,s2[e] + 1)
exit(0)
print (len(l1))
print (-1,-1)
``` | instruction | 0 | 50,035 | 0 | 100,070 |
Yes | output | 1 | 50,035 | 0 | 100,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3.
Submitted Solution:
```
n,s,t = int(input()),input(),input()
d = {}
wrongs = []
ansD,ansI,ansJ = 0,-1,-1
for i in range(n) :
if s[i]!=t[i] :
ansD+=1
wrongs.append(i)
d[t[i]] = i
perfectSwapped = False
swapped = False
for i in wrongs :
if s[i] in d :
swapped = True
ansI = i+1
j = d[s[i]]
ansJ = j+1
if s[j]==t[i] :
perfectSwapped = True
break
print(ansD-(2 if perfectSwapped else 1 if swapped else 0))
print(ansI, ansJ)
``` | instruction | 0 | 50,036 | 0 | 100,072 |
Yes | output | 1 | 50,036 | 0 | 100,073 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3.
Submitted Solution:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 missingdays <missingdays@missingdays>
#
# Distributed under terms of the MIT license.
"""
"""
n = int(input())
s = input()
t = input()
k, l = 0, 0
state = 0
hd = 0
m = {}
for i in range(n):
if s[i] != t[i]:
hd += 1
cs = s[i]
ct = t[i]
cst = cs + ct
if cst not in m:
m[cst] = i+1
for pair in m:
r = pair[1] + pair[0]
if r in m:
print(hd-2)
print(m[pair], m[r])
exit()
for pair in m:
for p in m:
if pair == p:
continue
if p[0] == pair[1] or p[1] == pair[0]:
print(hd-1)
print(m[pair], m[p])
exit()
print(hd)
print(-1, -1)
``` | instruction | 0 | 50,037 | 0 | 100,074 |
Yes | output | 1 | 50,037 | 0 | 100,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3.
Submitted Solution:
```
def getInput() :
n = int(input())
recup1 = str(input())
recup2 = str(input())
mot1 = []
mot2 = []
for i in range(n) :
mot1.append(recup1[i])
mot2.append(recup2[i])
return n, mot1, mot2
def solve(n, mot1, mot2) :
hammingMinimum = 0
besti = -1
bestj = -1
for a in range(n) :
if mot1[a] != mot2[a] :
hammingMinimum += 1
final = hammingMinimum
for i in range(n) :
compteur = hammingMinimum
for j in range(i+1, n) :
if mot2[i] != mot2[j] :
if mot1[i] == mot2[j] :
compteur -= 1
if mot1[j] == mot2[i] :
compteur -= 1
if compteur < final :
final = compteur
besti = i
bestj = j
print(final)
if besti == -1 :
print(str(-1) + " " + str(-1))
else :
print(str(besti+1) + " " + str(bestj+1))
(n, mot1, mot2) = getInput()
solve(n, mot1, mot2)
``` | instruction | 0 | 50,038 | 0 | 100,076 |
No | output | 1 | 50,038 | 0 | 100,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3.
Submitted Solution:
```
n = int(input())
s, t = input(), input()
d1, d2 = {}, {}
ind = (-1, -1)
for i in range(n):
if s[i] != t[i]:
d1[s[i]] = i
d2[t[i]] = i
if len(d1) > 1:
for x in d1.keys():
if x in d2.keys() and d1[x] != d2[x]:
for y in d1.keys():
if d1[y] == d2[x] and y in d2.keys() and d1[x] == d2[y]:
print(len(d1) - 2)
print(d1[x]+1, d2[x]+1)
exit(0)
else:
ind = (d1[x]+1, d2[x]+1)
if ind == (-1, -1):
print(len(d1))
else:
print(len(d1)-1)
[print(x, end=" ") for x in ind]
``` | instruction | 0 | 50,039 | 0 | 100,078 |
No | output | 1 | 50,039 | 0 | 100,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3.
Submitted Solution:
```
n=int(input())
s=input()
t=input()
ss=[]
tt=[]
i=0
for c in s:
ss.append((c,i))
i=i+1
i=0
for c in t:
tt.append((c,i))
i=i+1
sss=set(ss)
ttt=set(tt)
a1=list(sss-ttt)
a2=list(ttt-sss)
a1=sorted(a1, key=lambda x: x[::-1])
a2=sorted(a2, key=lambda x: x[::-1])
i=0
j=0
x=0
ans=[-2,-2]
for i in range(len(a1)):
for j in range(len(a2)):
if a1[i][0]==a2[j][0] and i!=j:
if a1[j][0]==a2[i][0] and i!=j:
x=2
elif x!=2:
x=1
ans=[a1[i][1],a2[j][1]]
j=j+1
i=i+1
print(len(a1)-x)
print(str(ans[1]+1)+' '+str(ans[0]+1))
``` | instruction | 0 | 50,040 | 0 | 100,080 |
No | output | 1 | 50,040 | 0 | 100,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.
Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.
Help him do this!
Input
The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T.
The second line contains string S.
The third line contains string T.
Each of the lines only contains lowercase Latin letters.
Output
In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.
In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.
If there are multiple possible answers, print any of them.
Examples
Input
9
pergament
permanent
Output
1
4 6
Input
6
wookie
cookie
Output
1
-1 -1
Input
4
petr
egor
Output
2
1 2
Input
6
double
bundle
Output
2
4 1
Note
In the second test it is acceptable to print i = 2, j = 3.
Submitted Solution:
```
n = int(input())
s, t = input(), input()
alpha = "abcdefghijklmnopqrstuvwxyz"
minus = 0
bottom, top = dict(), dict()
a, b = -1, -1
for i in alpha:
bottom[i] = -1
top[i] = -1
#print(len(alpha))
ham = 0
for i in range(n):
if s[i] != t[i]:
if bottom[s[i]] != -1 and s[bottom[s[i]]] == t[i]:
minus = 2
a, b = bottom[s[i]], i
elif bottom[s[i]] != -1 or top[t[i]] != -1:
minus = max(minus, 1)
a, b = bottom[s[i]], i
bottom[t[i]] = i
top[s[i]] = i
ham += 1
if minus == 0:
print(ham)
print(a, b)
else:
print(ham-minus)
print(a+1, b+1)
``` | instruction | 0 | 50,041 | 0 | 100,082 |
No | output | 1 | 50,041 | 0 | 100,083 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire string) and reverse it, paying x coins for it (for example, «0101101» → «0111001»);
* Choose some substring of string a (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying y coins for it (for example, «0101101» → «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input
The first line of input contains integers n, x and y (1 ≤ n ≤ 300 000, 0 ≤ x, y ≤ 10^9) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string a of length n, consisting of zeros and ones.
Output
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print 0, if you do not need to perform any operations.
Examples
Input
5 1 10
01000
Output
11
Input
5 10 1
01000
Output
2
Input
7 2 3
1111111
Output
0
Note
In the first sample, at first you need to reverse substring [1 ... 2], and then you need to invert substring [2 ... 5].
Then the string was changed as follows:
«01000» → «10000» → «11111».
The total cost of operations is 1 + 10 = 11.
In the second sample, at first you need to invert substring [1 ... 1], and then you need to invert substring [3 ... 5].
Then the string was changed as follows:
«01000» → «11000» → «11111».
The overall cost is 1 + 1 = 2.
In the third example, string already consists only of ones, so the answer is 0. | instruction | 0 | 50,249 | 0 | 100,498 |
Tags: brute force, greedy, implementation, math
Correct Solution:
```
import sys
bla, wort, *_ = sys.stdin.read().split('\n')
n, x, y = [int(z) for z in bla.split(' ')]
anz = wort[0] == '0'
for a, b in zip(wort[:-1], wort[1:]):
if b=='0' and a!='0':
anz += 1
if anz==0:
print(0)
else:
print(y + min(x, y)*(anz-1))
``` | output | 1 | 50,249 | 0 | 100,499 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire string) and reverse it, paying x coins for it (for example, «0101101» → «0111001»);
* Choose some substring of string a (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying y coins for it (for example, «0101101» → «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input
The first line of input contains integers n, x and y (1 ≤ n ≤ 300 000, 0 ≤ x, y ≤ 10^9) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string a of length n, consisting of zeros and ones.
Output
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print 0, if you do not need to perform any operations.
Examples
Input
5 1 10
01000
Output
11
Input
5 10 1
01000
Output
2
Input
7 2 3
1111111
Output
0
Note
In the first sample, at first you need to reverse substring [1 ... 2], and then you need to invert substring [2 ... 5].
Then the string was changed as follows:
«01000» → «10000» → «11111».
The total cost of operations is 1 + 10 = 11.
In the second sample, at first you need to invert substring [1 ... 1], and then you need to invert substring [3 ... 5].
Then the string was changed as follows:
«01000» → «11000» → «11111».
The overall cost is 1 + 1 = 2.
In the third example, string already consists only of ones, so the answer is 0. | instruction | 0 | 50,250 | 0 | 100,500 |
Tags: brute force, greedy, implementation, math
Correct Solution:
```
n, x, y = map(int, input().split())
s = input()
lst = -1
cnt = 0
for i in s:
if i == '1':
if lst == 0:
cnt += 1
lst = -1
else:
lst = 0
if s[n - 1] == '0':
cnt += 1
if cnt == 0:
exit(print(0))
ans = 0
if x >= y:
ans = y * cnt
else:
ans = (cnt - 1) * x + y
print(ans)
``` | output | 1 | 50,250 | 0 | 100,501 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire string) and reverse it, paying x coins for it (for example, «0101101» → «0111001»);
* Choose some substring of string a (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying y coins for it (for example, «0101101» → «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input
The first line of input contains integers n, x and y (1 ≤ n ≤ 300 000, 0 ≤ x, y ≤ 10^9) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string a of length n, consisting of zeros and ones.
Output
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print 0, if you do not need to perform any operations.
Examples
Input
5 1 10
01000
Output
11
Input
5 10 1
01000
Output
2
Input
7 2 3
1111111
Output
0
Note
In the first sample, at first you need to reverse substring [1 ... 2], and then you need to invert substring [2 ... 5].
Then the string was changed as follows:
«01000» → «10000» → «11111».
The total cost of operations is 1 + 10 = 11.
In the second sample, at first you need to invert substring [1 ... 1], and then you need to invert substring [3 ... 5].
Then the string was changed as follows:
«01000» → «11000» → «11111».
The overall cost is 1 + 1 = 2.
In the third example, string already consists only of ones, so the answer is 0. | instruction | 0 | 50,251 | 0 | 100,502 |
Tags: brute force, greedy, implementation, math
Correct Solution:
```
n, x, y = map(int, input().split())
s = input()
if '0' not in s:
print(0)
elif '1' not in s:
print(y)
else:
zero_start = s[0] == '0'
zero_end = s[-1] == '0'
ones_groups = 0
i = 0
while i < n:
found = False
while i < n and s[i] == '1':
found = True
i+=1
if found:
ones_groups += 1
i += 1
replace = max(0, (ones_groups - (0 if zero_start else 1) - (0 if zero_end else 1))) * x + y
invert = (ones_groups-1 + (1 if zero_start else 0) + (1 if zero_end else 0)) * y
print(min(replace, invert))
``` | output | 1 | 50,251 | 0 | 100,503 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire string) and reverse it, paying x coins for it (for example, «0101101» → «0111001»);
* Choose some substring of string a (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying y coins for it (for example, «0101101» → «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input
The first line of input contains integers n, x and y (1 ≤ n ≤ 300 000, 0 ≤ x, y ≤ 10^9) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string a of length n, consisting of zeros and ones.
Output
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print 0, if you do not need to perform any operations.
Examples
Input
5 1 10
01000
Output
11
Input
5 10 1
01000
Output
2
Input
7 2 3
1111111
Output
0
Note
In the first sample, at first you need to reverse substring [1 ... 2], and then you need to invert substring [2 ... 5].
Then the string was changed as follows:
«01000» → «10000» → «11111».
The total cost of operations is 1 + 10 = 11.
In the second sample, at first you need to invert substring [1 ... 1], and then you need to invert substring [3 ... 5].
Then the string was changed as follows:
«01000» → «11000» → «11111».
The overall cost is 1 + 1 = 2.
In the third example, string already consists only of ones, so the answer is 0. | instruction | 0 | 50,252 | 0 | 100,504 |
Tags: brute force, greedy, implementation, math
Correct Solution:
```
n,x,y=map(int, input().split())
a=input()
k=0
i=0
if a[i]=='0':
k+=1
while i<n and a[i]=='0':
i+=1
for j in range(i,n-1):
if a[j]=='1' and a[j+1]=='0':
k+=1
if k==0:
print(0)
elif x<y:
print((k-1)*x+y)
else:
print(k*y)
``` | output | 1 | 50,252 | 0 | 100,505 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire string) and reverse it, paying x coins for it (for example, «0101101» → «0111001»);
* Choose some substring of string a (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying y coins for it (for example, «0101101» → «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input
The first line of input contains integers n, x and y (1 ≤ n ≤ 300 000, 0 ≤ x, y ≤ 10^9) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string a of length n, consisting of zeros and ones.
Output
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print 0, if you do not need to perform any operations.
Examples
Input
5 1 10
01000
Output
11
Input
5 10 1
01000
Output
2
Input
7 2 3
1111111
Output
0
Note
In the first sample, at first you need to reverse substring [1 ... 2], and then you need to invert substring [2 ... 5].
Then the string was changed as follows:
«01000» → «10000» → «11111».
The total cost of operations is 1 + 10 = 11.
In the second sample, at first you need to invert substring [1 ... 1], and then you need to invert substring [3 ... 5].
Then the string was changed as follows:
«01000» → «11000» → «11111».
The overall cost is 1 + 1 = 2.
In the third example, string already consists only of ones, so the answer is 0. | instruction | 0 | 50,253 | 0 | 100,506 |
Tags: brute force, greedy, implementation, math
Correct Solution:
```
n, x, y = input().split()
n = int(n)
x = int(x)
y = int(y)
s = input()
count = 0
is_zero = (s[0] == '0')
if is_zero:
count += 1
for i in range(1, n):
if s[i] == '0' and not is_zero:
is_zero = True
count += 1
elif s[i] == '1' and is_zero:
is_zero = False
if y <= x or count == 0:
print(y * count)
else:
print(x * (count - 1) + y)
``` | output | 1 | 50,253 | 0 | 100,507 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones.
Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a.
You can apply the following operations any number of times:
* Choose some substring of string a (for example, you can choose entire string) and reverse it, paying x coins for it (for example, «0101101» → «0111001»);
* Choose some substring of string a (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying y coins for it (for example, «0101101» → «0110001»).
You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.
What is the minimum number of coins you need to spend to get a string consisting only of ones?
Input
The first line of input contains integers n, x and y (1 ≤ n ≤ 300 000, 0 ≤ x, y ≤ 10^9) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).
The second line contains the string a of length n, consisting of zeros and ones.
Output
Print a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print 0, if you do not need to perform any operations.
Examples
Input
5 1 10
01000
Output
11
Input
5 10 1
01000
Output
2
Input
7 2 3
1111111
Output
0
Note
In the first sample, at first you need to reverse substring [1 ... 2], and then you need to invert substring [2 ... 5].
Then the string was changed as follows:
«01000» → «10000» → «11111».
The total cost of operations is 1 + 10 = 11.
In the second sample, at first you need to invert substring [1 ... 1], and then you need to invert substring [3 ... 5].
Then the string was changed as follows:
«01000» → «11000» → «11111».
The overall cost is 1 + 1 = 2.
In the third example, string already consists only of ones, so the answer is 0. | instruction | 0 | 50,254 | 0 | 100,508 |
Tags: brute force, greedy, implementation, math
Correct Solution:
```
n, x, y = map(int, input().split())
u = list(map(int, input()))
d0 = 0
k0 = 0
for i in range(n):
if k0 == 1 and u[i] == 1:
d0 += 1
k0 = 0
elif u[i] == 0:
k0 = 1
if k0 == 1:
d0 += 1
if d0 == 0:
p = 0
else:
p = (d0 - 1) * min(x, y) + y
print(p)
``` | output | 1 | 50,254 | 0 | 100,509 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.