message
stringlengths 2
23.4k
| message_type
stringclasses 2
values | message_id
int64 0
1
| conversation_id
int64 129
108k
| cluster
float64 6
6
| __index_level_0__
int64 258
216k
|
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
Submitted Solution:
```
#list(map(int,input().split()))
#list(input().strip().split())
arr=list(input().strip().split())
s1=arr[0]
s2=arr[1]
ans=[s1[0]]
k=1
while k<len(s1):
if s1[k]>=s2[0]:
break
ans.append(s1[k])
k+=1
ans.append(s2[0])
print("".join(ans))
```
|
instruction
| 0
| 11,358
| 6
| 22,716
|
Yes
|
output
| 1
| 11,358
| 6
| 22,717
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
Submitted Solution:
```
a, b = input().split(' ')
for i in a[1:]:
if i >= b[0]:
i = a.find(i)
break
else:
i = None
# print(i)
if i == 0:
print(a[0],b[0], sep='')
else:
print(a[:i], b[0], sep='')
```
|
instruction
| 0
| 11,359
| 6
| 22,718
|
Yes
|
output
| 1
| 11,359
| 6
| 22,719
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
Submitted Solution:
```
a,b=input().split()
s=[]
for i in range(1,len(a)+1):
for j in range(1,len(b)+1):
s.append(a[:i]+b[:j])
s.sort()
print(s[0])
```
|
instruction
| 0
| 11,360
| 6
| 22,720
|
Yes
|
output
| 1
| 11,360
| 6
| 22,721
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
Submitted Solution:
```
#909A
p,s = input().split(" ")
l = p[0]
for i in p[1:]:
if i > s[0]:
break
else:
l += i
print(l + s[0])
```
|
instruction
| 0
| 11,361
| 6
| 22,722
|
No
|
output
| 1
| 11,361
| 6
| 22,723
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
Submitted Solution:
```
f,l = input().split(' ')
ans =''
ans+=f[0]
i = 1
j = 0
while(True):
if(i==len(f)):
ans+=l[j]
break
x = ord(f[i])
y = ord(l[j])
if(x<=y):
ans+=f[i]
i+=1
else:
ans+=l[j]
break
print(ans)
```
|
instruction
| 0
| 11,362
| 6
| 22,724
|
No
|
output
| 1
| 11,362
| 6
| 22,725
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".
Input
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
Output
Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
Examples
Input
harry potter
Output
hap
Input
tom riddle
Output
tomr
Submitted Solution:
```
n = input().strip().split()
minVal = n[0][0]
index = 0
for i in range(1, len(n[0])):
if ord(n[0][i]) < ord(minVal):
minVal = n[0][i]
index = i
output = ''
for j in range(index + 1):
output += n[0][j]
output += n[1][0]
print(output)
```
|
instruction
| 0
| 11,364
| 6
| 22,728
|
No
|
output
| 1
| 11,364
| 6
| 22,729
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
|
instruction
| 0
| 12,130
| 6
| 24,260
|
Tags: implementation, strings
Correct Solution:
```
import sys
s=input()
t=input()
st1=[]
st2=[]
checked=[]
right=[]
for i in range(len(s)):
a=[]
if s[i] in checked and t[i] not in checked:
print('-1')
sys.exit()
if s[i] not in checked and t[i] in checked:
print('-1')
sys.exit()
if s[i] in right and t[i] not in right:
print('-1')
sys.exit()
if s[i] not in right and t[i] in right:
print('-1')
sys.exit()
if s[i] not in st1 and s[i] not in st2:
if t[i] not in st1 and t[i] not in st2:
if s[i]!=t[i]:
checked.append(s[i])
checked.append(t[i])
st1.append(s[i])
st2.append(t[i])
else:
right.append(s[i])
right.append(t[i])
if s[i]==t[i]:
if s[i] in st1 or s[i] in st2:
print('-1')
sys.exit()
elif t[i] in st1 or t[i] in st2:
print('-1')
sys.exit()
if s[i] in st2:
if st1[st2.index(s[i])]!=t[i]:
print('-1')
sys.exit()
if s[i] in right or t[i] in right:
if s[i]!=t[i]:
print('-1')
sys.exit()
print(len(st1))
for i in range(len(st1)):
print(st1[i],end=" ")
print(st2[i])
```
|
output
| 1
| 12,130
| 6
| 24,261
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
|
instruction
| 0
| 12,131
| 6
| 24,262
|
Tags: implementation, strings
Correct Solution:
```
a = input()
b = input()
alph = [0] * 26
for i in range(26):
alph[i] = chr(97 + i)
ans = []
for i in range(len(a)):
if a[i] != alph[ord(b[i]) - 97]:
if (alph[ord(a[i]) - 97] == a[i]) and (alph[ord(b[i]) - 97] == b[i]):
alph[ord(a[i]) - 97] = b[i]
alph[ord(b[i]) - 97] = a[i]
ans.append((a[i], b[i]))
else:
print(-1)
exit()
for i in range(len(b)):
if a[i] != alph[ord(b[i]) - 97]:
print(-1)
exit()
print(len(ans))
for i in range(len(ans)):
print(ans[i][0], ans[i][1])
```
|
output
| 1
| 12,131
| 6
| 24,263
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
|
instruction
| 0
| 12,132
| 6
| 24,264
|
Tags: implementation, strings
Correct Solution:
```
def areBidirectionalDictionaries(s1, s2):
d = {}
other = {}
perfect = set()
for i, j in zip(s1, s2):
if i != j:
if (i in d and d[i] != j) or (j in d and d[j] != i) or (i in perfect) or (j in perfect):
print('-1')
return
if j not in d:
d[i] = j
other[j] = i
elif (i in d) or (i in other):
print('-1')
return
else:
perfect.add(i)
if len(d) != len(set(d.values())):
print('-1')
return
print(len(d))
for i, j in d.items():
print(str(i)+' '+str(j))
s1 = input()
s2 = input()
areBidirectionalDictionaries(s1, s2)
```
|
output
| 1
| 12,132
| 6
| 24,265
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
|
instruction
| 0
| 12,133
| 6
| 24,266
|
Tags: implementation, strings
Correct Solution:
```
s = input()
t = input()
used, ln = set(), 0
for i in range(len(s)):
if (s[i] != t[i]) and (not (tuple(sorted([s[i], t[i]])) in used)):
ln += 1
used.add(tuple(sorted([s[i], t[i]])))
a = [i[0] for i in used]
b = [i[1] for i in used]
if s=='bd' and t=='cc':
print(-1)
elif len(a) != len(set(a)) or len(b) != len(set(b)):
print(-1)
elif len(a) == 0:
print(0)
else:
print(ln)
for i in used:
if i[0] != i[1]:
print(i[0], i[1])
```
|
output
| 1
| 12,133
| 6
| 24,267
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
|
instruction
| 0
| 12,134
| 6
| 24,268
|
Tags: implementation, strings
Correct Solution:
```
def ic(s,t):
"""is correct"""
d=dict()
for c in range(len(s)):
if t[c] not in d or t[c] in d and s[c] not in d[t[c]]:
d.setdefault(s[c],set()).add(t[c])
d.setdefault(t[c],set()).add(s[c])
#print(d)
for k,v in d.items():
if len(v)>1:
return 0,None
d[k]=list(v)[0]
#print(d)
k,v=list(d.keys()),list(d.values())
#print(k,v)
sk,sv=set(k),set(v)
b=len(k)==len(sk) and len(v)==len(sv)
rv=set()
for k,v in d.items():
if k!=v and (v,k) not in rv:
rv.add((k,v))
return b,list(rv)
s,t=[input() for c in range(2)]
b,v=ic(s,t)
if b:
print(len(v))
for c in v:
print(c[0],c[1])
else:
print(-1)
```
|
output
| 1
| 12,134
| 6
| 24,269
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
|
instruction
| 0
| 12,135
| 6
| 24,270
|
Tags: implementation, strings
Correct Solution:
```
def main():
d = {}
for a, b in zip(input(), input()):
if d.get(a, b) != b or d.get(b, a) != a:
print(-1)
return
d[a], d[b] = b, a
res = ['%s %s' % (a, b) for a, b in d.items() if a < b]
print(len(res))
print('\n'.join(res))
if __name__ == '__main__':
main()
```
|
output
| 1
| 12,135
| 6
| 24,271
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
|
instruction
| 0
| 12,136
| 6
| 24,272
|
Tags: implementation, strings
Correct Solution:
```
s1 = input()
s2 = input()
a = [[0]*2 for i in range(29)]
used = [-1]*29
good = 1
c = 0
for i in range(len(s2)):
if good == 0:
break
if s2[i] != s1[i]:
if used[ord(s2[i])- ord('a')] == -1 and used[ord(s1[i])- ord('a')] == -1:
used[ord(s2[i])- ord('a')] = ord(s1[i])- ord('a')
used[ord(s1[i])- ord('a')] = ord(s2[i])- ord('a')
a[c][0] = s1[i]
a[c][1] = s2[i]
c += 1
elif used[ord(s2[i])- ord('a')] != ord(s1[i])- ord('a'):
good = 0
else:
if used[ord(s2[i])- ord('a')] == -1 :
used[ord(s2[i])- ord('a')] = ord(s1[i])- ord('a')
elif used[ord(s2[i])- ord('a')] != ord(s1[i])- ord('a'):
good = 0
if good == 0:
print(-1)
else:
print (c)
for i in range(c):
print(a[i][0], a[i][1])
```
|
output
| 1
| 12,136
| 6
| 24,273
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
|
instruction
| 0
| 12,137
| 6
| 24,274
|
Tags: implementation, strings
Correct Solution:
```
before = input()
after = input()
length = len(before)
stock = {}
answer = []
for l in range(length):
if before[l] != after[l] and stock.get(after[l],0) == 0 and stock.get(before[l],0) == 0:
answer.append(str(before[l]) + " " + str(after[l]))
stock[before[l]] = after[l]
stock[after[l]] = before[l]
elif before[l] != after[l] and (stock.get(after[l],0) == -1 or stock.get(before[l],0) == -1):
print(-1)
break
elif before[l] != after[l]:
if stock.get(before[l],0) != after[l] or stock.get(after[l],0) != before[l]:
print(-1)
break
else:
continue
elif before[l] == after[l] and (stock.get(after[l],0) not in (0,-1) or stock.get(before[l],0) not in (0,-1)):
print(-1)
break
else:
stock[before[l]] = -1
stock[after[l]] = -1
else:
anslen = len(answer)
print(anslen)
for a in answer:
print(a)
```
|
output
| 1
| 12,137
| 6
| 24,275
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
Submitted Solution:
```
s = input()
s1 = input()
mistake = False
d = dict()
ans = []
for i in range(len(s)):
if s[i] != s1[i]:
if s[i] in d and s1[i] in d:
if not (d[s[i]] == s1[i] and d[s1[i]] == s[i]):
mistake = True
break
elif s[i] in d or s1[i] in d:
mistake = True
break
else:
d[s[i]] = s1[i]
d[s1[i]] = s[i]
else:
if s[i] in d and d[s[i]] != s[i]:
mistake = True
break
d[s[i]] = s[i]
if mistake:
print(-1)
else:
ans = []
last = set()
for elem in d:
if elem not in last and elem != d[elem]:
ans.append([elem, d[elem]])
last.add(elem)
last.add(d[elem])
print(len(ans))
for elem in ans:
print(*elem)
```
|
instruction
| 0
| 12,138
| 6
| 24,276
|
Yes
|
output
| 1
| 12,138
| 6
| 24,277
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
Submitted Solution:
```
s1, s2 = input(), input()
n = len(s1)
d = dict()
for i in range(n):
a = s1[i]
b = s2[i]
if b < a:
a, b = b, a
if a not in d and b not in d:
d[a] = b
d[b] = a
elif ((a in d and b not in d) or (a not in d and b in d)):
print(-1)
break
elif d[a] != b or d[b] != a:
print(-1)
break
else:
k = []
for i in d.items():
if i[0] < i[1]:
k.append('{} {}'.format(i[0], i[1]))
print(len(k))
print(*k, sep='\n')
```
|
instruction
| 0
| 12,139
| 6
| 24,278
|
Yes
|
output
| 1
| 12,139
| 6
| 24,279
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
Submitted Solution:
```
s = input()
s1 = input()
q = set()
z =set()
flag=0
for i in range(len(s)):
if(s[i]!=s1[i] and (s1[i],s[i]) not in q and (s[i],s1[i])not in q):
q.add((s[i],s1[i]))
if(s[i] in z or s1[i] in z):
flag = 1
z.add(s[i])
z.add(s1[i])
for i in range(len(s)):
if(s[i]==s1[i] and s[i] in z):
flag = 1
if(flag):
print(-1)
else:
print(len(q))
for item in q:
print(item[0],item[1])
```
|
instruction
| 0
| 12,140
| 6
| 24,280
|
Yes
|
output
| 1
| 12,140
| 6
| 24,281
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
Submitted Solution:
```
#k=int(input())
#n,m=map(int,input().split())
#a=list(map(int,input().split()))
#b=list(map(int,input().split()))
a=input()
b=input()
l=len(a)
d=set()
d2=set()
deg=dict()
for i in range(l):
if a[i]==b[i]:
d2.add(a[i])
deg[a[i]]=0
deg[b[i]]=0
for i in range(l):
if a[i]!=b[i]:
if a[i] in d2 or b[i] in d2:
print("-1")
quit()
if (not (a[i],b[i]) in d and not (b[i],a[i]) in d):
d.add((a[i],b[i]))
deg[a[i]]+=1
deg[b[i]]+=1
for i in d:
if deg[i[0]]>1 or deg[i[1]]>1:
print("-1")
quit()
print(len(d))
for i in d:
print(str(i[0]),'',str(i[1]))
```
|
instruction
| 0
| 12,141
| 6
| 24,282
|
Yes
|
output
| 1
| 12,141
| 6
| 24,283
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
Submitted Solution:
```
s=input()
t=input()
num=len(s)
pair1=[0]*num
for i in range (num):
pair1[i]=[0]*2
def check(s,t,num):
arr=[0]*256
count=0
countie=0
for i in range (num):
if s[i] !=t[i]:
if (arr[ord(s[i])]>0 or arr[ord(t[i])]>0):
yy=0
for k in range (num):
if (pair1[k][0]==s[i] and pair1[k][1]==t[i]) or (pair1[k][1]==s[i] and pair1[k][0]==t[i]):
yy+=1
if yy==0:
return (-1)
else:
arr[ord(s[i])]+=1
arr[ord(t[i])]+=1
pair1[count][0]=s[i]
pair1[count][1]=t[i]
count+=1
countie+=1
return (countie)
ans=check(s,t,num)
if ans==-1 or ans==0:
print (ans)
else:
print (ans)
for p in range (ans):
print (pair1[p][0],pair1[p][1])
```
|
instruction
| 0
| 12,142
| 6
| 24,284
|
No
|
output
| 1
| 12,142
| 6
| 24,285
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
Submitted Solution:
```
s = input()
t = input()
d = {}
p = {}
end = 0
for i in range(len(s)) :
if s[i] != t[i] :
if (s[i] in p ) or (t[i] in p) :
end = 1
else :
test = 0
for el in d :
if (el[0] == s[i] and el[1] == t[i]) or (el[1] == s[i] and el[0] == t[i]) :
test = 1
break
elif (s[i] == el[0] and t[i] != el[1]) or (t[i] == el[1] and s[i] != el[0]) or( (s[i] == el[1] and t[i] != el[0])) or (t[i] == el[0] and s[i] != el[1]) :
test = 1
end = 1
break
if test == 0 :
d[(s[i],t[i])] = 1
else :
p[s[i]] = 1
if end == 1 :
break
if end == 1 :
print(-1)
else :
print(len(d))
for el in d :
print(*[el[0],el[1]],sep =' ')
```
|
instruction
| 0
| 12,143
| 6
| 24,286
|
No
|
output
| 1
| 12,143
| 6
| 24,287
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
Submitted Solution:
```
import traceback
import math
from collections import defaultdict
from functools import lru_cache
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def geti():
return int(input())
def gets():
return input()
def getil():
return list(map(int, input().split()))
def getsl():
return input().split()
def get2d(nrows, ncols, n=0):
return [[n] * ncols for r in range(nrows)]
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
inf = float('inf')
mod = 10 ** 9 + 7
def main():
T = gets()
S = gets()
pairs = {}
ans = []
for s, t in zip(S, T):
if s == t:
if s in pairs:
return -1
elif s in pairs:
if s != pairs[t]: return -1
else:
pairs[s] = t
pairs[t] = s
ans.append([s, t])
return ans
try:
ans = main()
if ans == -1:
print(-1)
else:
print(len(ans))
# ans = 'Yes' if ans else 'No'
for i in ans:
print(*i)
except Exception as e:
traceback.print_exc()
```
|
instruction
| 0
| 12,144
| 6
| 24,288
|
No
|
output
| 1
| 12,144
| 6
| 24,289
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
Submitted Solution:
```
# cook your dish here
import sys
s=input()
t=input()
set1=[]
set2=[]
right=[]
for i in range(len(s)):
if s[i]==t[i]:
right.append(s[i])
else:
if s[i] in set1 and t[i] in set2:
if set1.index(s[i])==set2.index(t[i]):
pass
else:
print('-1')
sys.exit()
elif s[i] in set1 and t[i] not in set2:
print(-1)
sys.exit()
elif s[i] not in set1 and t[i] in set2:
print('-1')
sys.exit()
else:
if s[i] not in set1 and s[i] not in set2:
if t[i] not in set1 and t[i] not in set2:
set1.append(s[i])
set2.append(t[i])
else:
print(-1)
sys.exit()
if s[i] in right or t[i] in right:
print(-1)
sys.exit()
print(len(set1))
for i in range(len(set1)):
print(set1[i],end=" ")
print(set2[i])
```
|
instruction
| 0
| 12,145
| 6
| 24,290
|
No
|
output
| 1
| 12,145
| 6
| 24,291
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, …, p_k (k ≥ 1; 1 ≤ p_i ≤ n; p_i ≠ p_j if i ≠ j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≤ i ≤ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10) — the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b → \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} → b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc → \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c → t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} → ts\color{blue}{r}).
|
instruction
| 0
| 12,618
| 6
| 25,236
|
Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers
Correct Solution:
```
"""Template for Python Competitive Programmers prepared by pajengod and many others """
# ////////// SHUBHAM SHARMA \\\\\\\\\\\\\
# to use the print and division function of Python3
from __future__ import division, print_function
"""value of mod"""
MOD = 998244353
mod = 10 ** 9 + 7
"""use resource"""
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
"""for factorial"""
def prepare_factorial():
fact = [1]
for i in range(1, 100005):
fact.append((fact[-1] * i) % mod)
ifact = [0] * 100005
ifact[100004] = pow(fact[100004], mod - 2, mod)
for i in range(100004, 0, -1):
ifact[i - 1] = (i * ifact[i]) % mod
return fact, ifact
"""uncomment next 4 lines while doing recursion based question"""
# import threading
# threading.stack_size(1<<27)
import sys
# sys.setrecursionlimit(10000)
"""uncomment modules according to your need"""
from bisect import bisect_left, bisect_right, insort
# from itertools import repeat
from math import floor, ceil, sqrt, degrees, atan, pi, log, sin, radians
from heapq import heappop, heapify, heappush
# from random import randint as rn
# from Queue import Queue as Q
from collections import Counter, defaultdict, deque
# from copy import deepcopy
# from decimal import *
# import re
# import operator
def modinv(n, p):
return pow(n, p - 2, p)
def ncr(n, r, fact, ifact): # for using this uncomment the lines calculating fact and ifact
t = (fact[n] * (ifact[r] * ifact[n - r]) % mod) % mod
return t
def intarray(): return map(int, sys.stdin.readline().strip().split())
def array(): return list(map(int, sys.stdin.readline().strip().split()))
def input(): return sys.stdin.readline().strip()
"""*****************************************************************************************"""
def GCD(x, y):
while y:
x, y = y, x % y
return x
def lcm(x, y):
return (x * y) // (GCD(x, y))
def get_xor(n):
return [n, 1, n + 1, 0][n % 4]
def fast_expo(a, b):
res = 1
while b:
if b & 1:
res = (res * a)
res %= MOD
b -= 1
else:
a = (a * a)
a %= MOD
b >>= 1
res %= MOD
return res
def get_n(P): # this function returns the maximum n for which Summation(n) <= Sum
ans = (-1 + sqrt(1 + 8 * P)) // 2
return ans
""" ********************************************************************************************* """
"""
array() # for araay
intarray() # for map array
SAMPLE INPUT HERE
5
2
01
10
5
01011
11100
2
01
01
10
0110011011
1000110100
1
0
1
"""
""" OM SAI RAM """
def solve():
n= int(input())
a= list(input())
b= input()
ans= 0
for i in range(20):
x ='z'
for j in range(n):
if a[j]==chr(97+i):
if a[j]>b[j]:
flag = 0
print(-1)
return
elif a[j]==b[j]:
continue
else:
x = min(x,b[j])
if x=='z':
continue
for k in range(n):
if a[k]==chr(97+i) and a[k]!=b[k]:
a[k] = x
ans+=1
print(ans)
return
def main():
T = int(input())
while T:
solve()
T -= 1
"""OM SAI RAM """
""" -------- Python 2 and 3 footer by Pajenegod and c1729 ---------"""
py2 = round(0.5)
if py2:
from future_builtins import ascii, filter, hex, map, oct, zip
range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192
class FastIO(BytesIO):
newlines = 0
def __init__(self, file):
self._file = file
self._fd = file.fileno()
self.writable = "x" in file.mode or "w" in file.mode
self.write = super(FastIO, self).write if self.writable else None
def _fill(self):
s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
return s
def read(self):
while self._fill(): pass
return super(FastIO, self).read()
def readline(self):
while self.newlines == 0:
s = self._fill();
self.newlines = s.count(b"\n") + (not s)
self.newlines -= 1
return super(FastIO, self).readline()
def flush(self):
if self.writable:
os.write(self._fd, self.getvalue())
self.truncate(0), self.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
if py2:
self.write = self.buffer.write
self.read = self.buffer.read
self.readline = self.buffer.readline
else:
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
""" main function"""
if __name__ == '__main__':
main()
# threading.Thread(target=main).start()
```
|
output
| 1
| 12,618
| 6
| 25,237
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, …, p_k (k ≥ 1; 1 ≤ p_i ≤ n; p_i ≠ p_j if i ≠ j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≤ i ≤ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10) — the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b → \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} → b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc → \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c → t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} → ts\color{blue}{r}).
|
instruction
| 0
| 12,619
| 6
| 25,238
|
Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
class UnionFind:
def __init__(self, n):
self.parent = [-1] * n
self.cnt = n
def root(self, x):
if self.parent[x] < 0:
return x
else:
self.parent[x] = self.root(self.parent[x])
return self.parent[x]
def merge(self, x, y):
x = self.root(x)
y = self.root(y)
if x == y:
return
if self.parent[x] > self.parent[y]:
x, y = y, x
self.parent[x] += self.parent[y]
self.parent[y] = x
self.cnt -= 1
def is_same(self, x, y):
return self.root(x) == self.root(y)
def get_size(self, x):
return -self.parent[self.root(x)]
def get_cnt(self):
return self.cnt
t = int(input())
alph = "abcdefghijklmnopqrstuvwxyz"
to_ind = {char: i for i, char in enumerate(alph)}
for _ in range(t):
n = int(input())
a = list(input())
b = list(input())
flag = False
for i in range(n):
if a[i] > b[i]:
print(-1)
flag = True
break
if flag:
continue
uf = UnionFind(26)
for i in range(n):
u = to_ind[a[i]]
v = to_ind[b[i]]
uf.merge(u, v)
print(26 - uf.get_cnt())
```
|
output
| 1
| 12,619
| 6
| 25,239
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, …, p_k (k ≥ 1; 1 ≤ p_i ≤ n; p_i ≠ p_j if i ≠ j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≤ i ≤ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10) — the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b → \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} → b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc → \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c → t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} → ts\color{blue}{r}).
|
instruction
| 0
| 12,620
| 6
| 25,240
|
Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
def find(x):
while x!=p[x]:
x=p[x]
return x
def union(a,b):
x=find(a)
y=find(b)
if x!=y:
p[y]=p[x]=min(x,y)
r[min(x,y)]+=r[max(x,y)]
t,=I()
for _ in range(t):
n,=I()
a=input().strip()
b=input().strip()
p=[i for i in range(20)]
r=[1]*20
pos=1
for i in range(n):
if a[i]<b[i]:
union(ord(a[i])-97,ord(b[i])-97)
elif a[i]!=b[i]:
pos=0
break
if pos:
an=0
for i in range(20):
if p[i]==i:
an+=r[i]-1
print(an)
else:
print(-1)
```
|
output
| 1
| 12,620
| 6
| 25,241
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, …, p_k (k ≥ 1; 1 ≤ p_i ≤ n; p_i ≠ p_j if i ≠ j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≤ i ≤ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10) — the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b → \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} → b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc → \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c → t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} → ts\color{blue}{r}).
|
instruction
| 0
| 12,621
| 6
| 25,242
|
Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers
Correct Solution:
```
y=lambda s:ord(s)-97
z=lambda:list(map(y,input()))
for _ in range(int(input())):
n=int(input())
a,b=z(),z()
f,c=0,0
for i in range(20):
m=20
l=[]
for j in range(n):
if a[j]==i:
if b[j]<i:
f=1
break
elif b[j]>i:
m=min(m,b[j])
l.append(j)
if f:break
if m==20:continue
else:
c+=1
for j in l:a[j]=m
if f:print(-1)
else:print(c)
```
|
output
| 1
| 12,621
| 6
| 25,243
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, …, p_k (k ≥ 1; 1 ≤ p_i ≤ n; p_i ≠ p_j if i ≠ j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≤ i ≤ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10) — the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b → \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} → b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc → \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c → t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} → ts\color{blue}{r}).
|
instruction
| 0
| 12,622
| 6
| 25,244
|
Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers
Correct Solution:
```
from collections import defaultdict
import string
T = int(input())
for t in range(T):
n = int(input())
source = input()
target = input()
exit_flag = False
for i in range(n): # feasibility test
if target[i] < source[i]:
print(-1)
exit_flag = True
break
if exit_flag:
continue
d = defaultdict(set)
for i in range(n):
if source[i] != target[i]:
d[source[i]].add(target[i]) # need to process this
ans = 0
for i in string.ascii_lowercase:
if i in d:
if d[i]:
smallest_e = min(d[i])
d[min(d[i])] |= set([j for j in d[i] if j!= smallest_e])
ans += 1
print(ans)
```
|
output
| 1
| 12,622
| 6
| 25,245
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, …, p_k (k ≥ 1; 1 ≤ p_i ≤ n; p_i ≠ p_j if i ≠ j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≤ i ≤ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10) — the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b → \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} → b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc → \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c → t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} → ts\color{blue}{r}).
|
instruction
| 0
| 12,623
| 6
| 25,246
|
Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers
Correct Solution:
```
import sys
import math
def II():
return int(sys.stdin.readline())
def LI():
return list(map(int, sys.stdin.readline().split()))
def MI():
return map(int, sys.stdin.readline().split())
def SI():
return sys.stdin.readline().strip()
t = II()
for q in range(t):
n = II()
a = SI()
b = SI()
d = [[] for i in range(20)]
boo = True
for i in range(n):
if a[i]>b[i]:
boo = False
break
d[ord(a[i])-97].append(ord(b[i])-97)
d[ord(b[i])-97].append(ord(a[i])-97)
if boo == False:
print(-1)
else:
v = [0]*20
def dfs(ind):
v[ind] = 1
for i in d[ind]:
if v[i] == 0:
dfs(i)
ans = 20
for i in range(20):
if v[i] == 0:
dfs(i)
ans-=1
print(ans)
```
|
output
| 1
| 12,623
| 6
| 25,247
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, …, p_k (k ≥ 1; 1 ≤ p_i ≤ n; p_i ≠ p_j if i ≠ j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≤ i ≤ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10) — the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b → \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} → b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc → \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c → t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} → ts\color{blue}{r}).
|
instruction
| 0
| 12,624
| 6
| 25,248
|
Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers
Correct Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
a=list(input())
b=list(input())
count=[[0 for i in range(20)] for i in range(20)]
flag=1
for i in range(n):
if(ord(a[i])>ord(b[i])):
flag=0
print(-1)
break
if(flag==0):
continue
ans=0
count=[[0 for i in range(20)] for i in range(20)]
for i in range(n):
count[ord(b[i])-97][ord(a[i])-97]+=1
#print(count)
for i in range(1,20):
counter=set()
for j in range(i):
if(count[i][j]>0):
counter.add(j)
ans+=1
for j in range(20):
jem=0
for k in range(i):
if(k in counter):
jem+=count[j][k]
count[j][k]=0
count[j][i]+=jem
#print(counter)
#print(count)
print(ans)
```
|
output
| 1
| 12,624
| 6
| 25,249
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter y Koa selects must be strictly greater alphabetically than x (read statement for better understanding). You can make hacks in these problems independently.
Koa the Koala has two strings A and B of the same length n (|A|=|B|=n) consisting of the first 20 lowercase English alphabet letters (ie. from a to t).
In one move Koa:
1. selects some subset of positions p_1, p_2, …, p_k (k ≥ 1; 1 ≤ p_i ≤ n; p_i ≠ p_j if i ≠ j) of A such that A_{p_1} = A_{p_2} = … = A_{p_k} = x (ie. all letters on this positions are equal to some letter x).
2. selects a letter y (from the first 20 lowercase letters in English alphabet) such that y>x (ie. letter y is strictly greater alphabetically than x).
3. sets each letter in positions p_1, p_2, …, p_k to letter y. More formally: for each i (1 ≤ i ≤ k) Koa sets A_{p_i} = y.
Note that you can only modify letters in string A.
Koa wants to know the smallest number of moves she has to do to make strings equal to each other (A = B) or to determine that there is no way to make them equal. Help her!
Input
Each test contains multiple test cases. The first line contains t (1 ≤ t ≤ 10) — the number of test cases. Description of the test cases follows.
The first line of each test case contains one integer n (1 ≤ n ≤ 10^5) — the length of strings A and B.
The second line of each test case contains string A (|A|=n).
The third line of each test case contains string B (|B|=n).
Both strings consists of the first 20 lowercase English alphabet letters (ie. from a to t).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case:
Print on a single line the smallest number of moves she has to do to make strings equal to each other (A = B) or -1 if there is no way to make them equal.
Example
Input
5
3
aab
bcc
4
cabc
abcb
3
abc
tsr
4
aabd
cccd
5
abcbd
bcdda
Output
2
-1
3
2
-1
Note
* In the 1-st test case Koa:
1. selects positions 1 and 2 and sets A_1 = A_2 = b (\color{red}{aa}b → \color{blue}{bb}b).
2. selects positions 2 and 3 and sets A_2 = A_3 = c (b\color{red}{bb} → b\color{blue}{cc}).
* In the 2-nd test case Koa has no way to make string A equal B.
* In the 3-rd test case Koa:
1. selects position 1 and sets A_1 = t (\color{red}{a}bc → \color{blue}{t}bc).
2. selects position 2 and sets A_2 = s (t\color{red}{b}c → t\color{blue}{s}c).
3. selects position 3 and sets A_3 = r (ts\color{red}{c} → ts\color{blue}{r}).
|
instruction
| 0
| 12,625
| 6
| 25,250
|
Tags: dsu, graphs, greedy, sortings, strings, trees, two pointers
Correct Solution:
```
import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict
# available on Google, not available on Codeforces
# import numpy as np
# import scipy
def solve(arr,brr): # fix inputs here
console("----- solving ------")
console(arr)
console(brr)
abc = dict((ab, idx) for idx,ab in enumerate("abcdefghijklmnopqrst"))
crr = []
drr = []
for a,b in zip(arr,brr):
if a > b:
return -1
if a != b:
crr.append(abc[a])
drr.append(abc[b])
console(crr)
console(drr)
if len(crr) == 0:
return 0
d = defaultdict(set)
for a,b in zip(crr,drr):
d[a].add(b)
d[b].add(a)
console(d)
visited = [False for _ in range(len(abc))]
idx = 1
for k in [x for x in d.keys()]:
if visited[k]:
continue
idx += 1
visited[k] = idx
stack = [x for x in d[k]]
while stack:
cur = stack.pop()
visited[cur] = idx
# if not cur in d:
# continue
for nex in d[cur]:
if visited[nex]:
continue
visited[nex] = idx
stack.append(nex)
console(d)
console(visited)
return sum([a-1 for a in Counter([x for x in visited if x]).values()])
def console(*args): # the judge will not read these print statement
# print('\033[36m', *args, '\033[0m', file=sys.stderr)
return
# fast read all
# sys.stdin.readlines()
for case_num in range(int(input())):
# read line as a string
# strr = input()
# read line as an integer
_ = int(input())
a = input()
b = input()
# read one line and parse each word as a string
# lst = input().split()
# read one line and parse each word as an integer
# lst = list(map(int,input().split()))
# read matrix and parse as integers (after reading read nrows)
# lst = list(map(int,input().split()))
# nrows = lst[0] # index containing information, please change
# grid = []
# for _ in range(nrows):
# grid.append(list(map(int,input().split())))
res = solve(a,b) # please change
# Google - case number required
# print("Case #{}: {}".format(case_num+1, res))
# Codeforces - no case number required
print(res)
```
|
output
| 1
| 12,625
| 6
| 25,251
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1
|
instruction
| 0
| 12,780
| 6
| 25,560
|
Tags: shortest paths
Correct Solution:
```
import sys, string
import itertools
s, t = input().strip(), input().strip()
if len(s) != len(t):
print(-1)
sys.exit()
vertices = string.ascii_lowercase
g = { c: { c: 0 } for c in vertices }
n = int(input())
for i in range(n):
u, v, cost = input().split()
cost = int(cost)
if v not in g[u] or g[u][v] > cost:
g[u][v] = cost
for p in vertices:
for u in vertices:
if p not in g[u]:
continue
for v in vertices:
if v not in g[p]:
continue
if v not in g[u] or g[u][v] > g[u][p] + g[p][v]:
g[u][v] = g[u][p] + g[p][v]
best_costs = { c: { c: 0 } for c in vertices }
best_chars = { c: { c: c } for c in vertices }
for a, b in itertools.product(vertices, vertices):
if a == b:
continue
best_cost = None
best_char = None
for c in vertices:
if c in g[a] and c in g[b]:
if best_cost == None or best_cost > g[a][c] + g[b][c]:
best_cost = g[a][c] + g[b][c]
best_char = c
if b in g[a] and (best_cost == None or best_cost > g[a][b]):
best_cost = g[a][b]
best_char = b
if a in g[b] and (best_cost == None or best_cost > g[b][a]):
best_cost = g[b][a]
best_char = a
if best_cost == None:
continue
best_costs[a][b] = best_cost
best_chars[a][b] = best_char
total_cost = 0
chars = []
for a, b in zip(s, t):
if b not in best_costs[a]:
print(-1)
sys.exit()
total_cost += best_costs[a][b]
chars.append(best_chars[a][b])
print(total_cost)
print(''.join(chars))
```
|
output
| 1
| 12,780
| 6
| 25,561
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1
|
instruction
| 0
| 12,781
| 6
| 25,562
|
Tags: shortest paths
Correct Solution:
```
import sys
large = 10000000
def solve():
s = input()
t = input()
if len(s) != len(t):
print(-1)
return
n = int(input())
mem = [[large] * 26 for _ in range(26)]
for i in range(26):
mem[i][i] = 0
for i in range(n):
chra, chrb, strcost = input().split()
a = ord(chra) - ord('a')
b = ord(chrb) - ord('a')
cost = int(strcost)
mem[a][b] = min(mem[a][b], cost)
for start in range(26):
for end in range(26):
mem[start][end] = min(mem[start][end], mem[start][a] + mem[a][b] + mem[b][end])
cost = 0
res = [None] * len(s)
for i in range(len(s)):
mid = -1
midcost = large
a = ord(s[i]) - ord('a')
b = ord(t[i]) - ord('a')
for j in range(26):
if mem[a][j] != -1 and mem[b][j] != -1:
thiscost = mem[a][j] + mem[b][j]
if thiscost < midcost:
midcost = thiscost
mid = j
res[i] = chr(ord('a') + mid)
cost += midcost
if cost >= large:
print(-1)
return
print(cost)
print(''.join(map(str, res)))
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
```
|
output
| 1
| 12,781
| 6
| 25,563
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1
|
instruction
| 0
| 12,782
| 6
| 25,564
|
Tags: shortest paths
Correct Solution:
```
# http://codeforces.com/problemset/problem/33/B
# 33b: String Problem.
#input = raw_input
def build_graph(a):
w = [[float('inf') for col in range(26)] for row in range(26)]
for i in range(26):
w[i][i] = 0
for b in a:
if w[ord(b[0]) - 97][ord(b[1]) - 97] > b[2]:
w[ord(b[0]) - 97][ord(b[1]) - 97] = b[2]
for k in range(26):
for i in range(26):
for j in range(26):
if w[i][j] > w[i][k] + w[k][j]:
w[i][j] = w[i][k] + w[k][j]
return w
def test_build_graph():
a = [['a', 'b', 2], ['a', 'c', 6], ['b', 'm', 5], ['c', 'm', 3]]
m = build_graph(a)
print(m)
print(m[ord('a') - 97][ord('m') - 97])
print(m[ord('a') - 97][ord('b') - 97])
def transfer(s, t, a):
if len(s) != len(t):
return -1
r = ''
z = 0
w = build_graph(a)
for d, p in zip(s, t):
if d == p:
r += d
else:
c = float('inf')
q = ''
i = ord(d) - 97
j = ord(p) - 97
for k in range(26):
v = w[i][k] + w[j][k]
if c > v:
c = v
q = chr(k + 97)
if c == float('inf'):
return -1
z += c
r += q
r = str(z) + '\n' + r
return r
def test_transfer():
s = 'uayd'
t = 'uxxd'
a = [['a', 'x', 8], ['x', 'y', 13], ['d', 'c', 3]]
assert transfer(s, t, a) == '21\nuxyd'
s1 = 'a'
t1 = 'b'
a1 = [['a', 'b', 2], ['a', 'b', 3], ['b', 'a', 5]]
assert transfer(s1, t1, a1) == '2\nb'
s2 = 'abc'
t2 = 'ab'
a2 = [['a', 'b', 4], ['a', 'b', 7], ['b', 'a', 8], ['c', 'b', 11], ['c', 'a', 3], ['a', 'c', 0]]
assert transfer(s2, t2, a2) == -1
s3 = 'abcd'
t3 = 'acer'
a3 = [['b', 'c', 100], ['c', 'b', 10], ['c', 'x', 1], ['e', 'x', 3], ['c', 'e', 7], ['r', 'd', 11]]
assert transfer(s3, t3, a3) == '25\nabxd'
def fun():
s = input()
t = input()
n = int(input())
a = []
for c in range(n):
x, y, z = map(str, input().split())
a.append([x, y, int(z)])
print(transfer(s, t, a))
#test_build_graph()
#test_transfer()
fun()
```
|
output
| 1
| 12,782
| 6
| 25,565
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1
|
instruction
| 0
| 12,783
| 6
| 25,566
|
Tags: shortest paths
Correct Solution:
```
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz/'
M=1000000007
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
s=list(input())
t=list(input())
n=int(input())
dic={}
adj=[[] for x in range(26)]
for x in range(n):
aa,bb,cost=input().split(" ")
cost=int(cost)
a=ord(aa)-ord('a')
b=ord(bb)-ord('a')
chk=False
for y in range(len(adj[a])):
if adj[a][y][0]==b:
adj[a][y][1]=min(cost,adj[a][y][1])
chk=True
if chk==False:
adj[a].append([b,cost])
ans=[]
vis=[False for x in range(26)]
def dfs(x,start,cnt):
temp=chr(start+97)+chr(x+97)
if temp in dic.keys() and cnt>=dic[temp]:
return
else:
vis[x]=True
temp=chr(start+97)+chr(x+97)
if temp in dic.keys():
dic[temp]=min(dic[temp],cnt)
else:
dic[temp]=cnt
for z in adj[x]:
dfs(z[0],start,cnt+z[1])
for x in range(26):
adj[x].sort(key=lambda x:x[1])
for x in range(26):
dfs(x,x,0)
for x in range(ord('a'),ord('z')+1):
temp=chr(x)+chr(x)
if temp in dic.keys():
dic[temp]=0
else:
dic[temp]=0
chk=1
spend=0
if len(s)!=len(t):
print(-1)
else:
for x in range(len(s)):
if s[x]==t[x]:
ans.append(s[x])
else:
notfound=True
spendhere=int(1e100)
thechar='a'
for y in range(ord('a'),ord('z')+1):
temp=s[x]+chr(y)
retemp=t[x]+chr(y)
if temp in dic.keys() and retemp in dic.keys():
notfound=False
if spendhere>dic[temp]+dic[retemp]:
thechar=chr(y)
spendhere=dic[temp]+dic[retemp]
if notfound:
chk=0
break
else:
ans.append(thechar)
spend+=spendhere
if chk==0:
print(-1)
else:
print(spend)
print(*ans,sep="")
```
|
output
| 1
| 12,783
| 6
| 25,567
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1
|
instruction
| 0
| 12,784
| 6
| 25,568
|
Tags: shortest paths
Correct Solution:
```
s = input()
t = input()
if(len(s) != len(t)):
print(-1)
exit()
dist = [[10**15 for j in range(26)] for i in range(26)]
for i in range(26):
dist[i][i] = 0
n = int(input())
for i in range(n):
a = input().split()
x = ord(a[0]) - 97
y = ord(a[1]) - 97
w = int(a[-1])
dist[x][y] = min(dist[x][y], w)
for k in range(26):
for i in range(26):
for j in range(26):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
ans = ''
res = 0
n = len(s)
for i in range(n):
if(s[i] == t[i]):
ans += s[i]
continue
cost = 10**15
pos = -1
x = ord(s[i]) - 97
y = ord(t[i]) - 97
for j in range(26):
if(dist[x][j] + dist[y][j] < cost):
cost = dist[x][j] + dist[y][j]
pos = j
if(pos == -1):
print(-1)
exit()
res += cost
ans += chr(pos + 97)
print(res)
print(ans)
```
|
output
| 1
| 12,784
| 6
| 25,569
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1
|
instruction
| 0
| 12,785
| 6
| 25,570
|
Tags: shortest paths
Correct Solution:
```
def code(c):
return ord(c) - ord('a')
def main():
a = input()
b = input()
m = int(input())
n = 26
d = [[10 ** 9 for i in range(n)] for j in range(n)]
for i in range(n):
d[i][i] = 0
for i in range(m):
s, t, w = input().split()
w = int(w)
s = code(s)
t = code(t)
d[s][t] = min(d[s][t], w)
for k in range(n):
for i in range(n):
for j in range(n):
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
if len(a) != len(b):
print(-1)
else:
ans = 0
res = []
for i in range(len(a)):
x = code(a[i])
y = code(b[i])
min_c = 'a'
min_cost = 10 ** 9
for j in range(n):
cur = d[x][j] + d[y][j]
if cur < min_cost:
min_cost = cur
min_c = chr(j + ord('a'))
res.append(min_c)
ans += min_cost
if ans >= 10 ** 9:
print(-1)
else:
print(ans)
for j in res:
print(j, end='')
print()
main()
```
|
output
| 1
| 12,785
| 6
| 25,571
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1
|
instruction
| 0
| 12,786
| 6
| 25,572
|
Tags: shortest paths
Correct Solution:
```
# http://codeforces.com/problemset/problem/33/B
# 33b: String Problem.
#input = raw_input
def calc_path(a):
'''
this function uses floyd-warshall alg to compute all pairs shortest path weight among alphabet characters.
input:
a: a 2d list which gives the weighted edge data. e.g., a = [['a', 'x', 42]]: only one edge, ('a', 'x'), with weight 42.
result:
all pairs shortest path weight matrix, a 26-length 2d list. w[i][i] == 0; for i != j, w[i][j] == infinite indicates there's no path between i and j.
'''
w = [[float('inf') for col in range(26)] for row in range(26)]
for i in range(26):
w[i][i] = 0
for b in a:
if w[ord(b[0]) - 97][ord(b[1]) - 97] > b[2]:
w[ord(b[0]) - 97][ord(b[1]) - 97] = b[2]
for k in range(26):
for i in range(26):
for j in range(26):
if w[i][j] > w[i][k] + w[k][j]:
w[i][j] = w[i][k] + w[k][j]
return w
def test_calc_path():
a = [['a', 'b', 2], ['a', 'c', 6], ['b', 'm', 5], ['c', 'm', 3]]
m = calc_path(a)
print(m)
print(m[ord('a') - 97][ord('m') - 97])
print(m[ord('a') - 97][ord('b') - 97])
def transfer(s, t, a):
'''
this function firstly invokes calc_path to compute all pairs shortest path among alphabet characters, and then computes the minimum transformation position by position of s and t. finally, a minimal transformation weight and outcome is returned.
input:
s, t: the input string to be transformed.
a: the character transformation cost list, 2d. e.g., a = [['a', 'x', 42], ['u', 'v', 8]]: a => x costs 42; u => v costs 8.
result:
-1 if transformation is not possible; otherwise, the minimal transformation cost and result, e.g. '12\nabc'.
'''
if len(s) != len(t):
return -1
r = ''
z = 0
w = calc_path(a)
for d, p in zip(s, t):
if d == p:
r += d
else:
c = float('inf')
q = ''
i = ord(d) - 97
j = ord(p) - 97
for k in range(26):
v = w[i][k] + w[j][k]
if c > v:
c = v
q = chr(k + 97)
if c == float('inf'):
return -1
z += c
r += q
r = str(z) + '\n' + r
return r
def test_transfer():
s = 'uayd'
t = 'uxxd'
a = [['a', 'x', 8], ['x', 'y', 13], ['d', 'c', 3]]
assert transfer(s, t, a) == '21\nuxyd'
s1 = 'a'
t1 = 'b'
a1 = [['a', 'b', 2], ['a', 'b', 3], ['b', 'a', 5]]
assert transfer(s1, t1, a1) == '2\nb'
s2 = 'abc'
t2 = 'ab'
a2 = [['a', 'b', 4], ['a', 'b', 7], ['b', 'a', 8], ['c', 'b', 11], ['c', 'a', 3], ['a', 'c', 0]]
assert transfer(s2, t2, a2) == -1
s3 = 'abcd'
t3 = 'acer'
a3 = [['b', 'c', 100], ['c', 'b', 10], ['c', 'x', 1], ['e', 'x', 3], ['c', 'e', 7], ['r', 'd', 11]]
assert transfer(s3, t3, a3) == '25\nabxd'
def fun():
s = input()
t = input()
n = int(input())
a = []
for c in range(n):
x, y, z = map(str, input().split())
a.append([x, y, int(z)])
print(transfer(s, t, a))
#test_calc_path()
#test_transfer()
fun()
```
|
output
| 1
| 12,786
| 6
| 25,573
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
Input
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
Output
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
Examples
Input
uayd
uxxd
3
a x 8
x y 13
d c 3
Output
21
uxyd
Input
a
b
3
a b 2
a b 3
b a 5
Output
2
b
Input
abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0
Output
-1
|
instruction
| 0
| 12,787
| 6
| 25,574
|
Tags: shortest paths
Correct Solution:
```
# http://codeforces.com/problemset/problem/33/B
# 33b: String Problem.
# 象道, montreal, quebec, canada.
#input = raw_input
def calc_path(a):
'''
this function uses floyd-warshall alg to compute all pairs shortest path weight among alphabet characters.
input:
a: a 2d list which gives the weighted edge data. e.g., a = [['a', 'x', 42]]: only one edge, ('a', 'x'), with weight 42.
result:
all pairs shortest path weight matrix, a 26-length 2d list. w[i][i] == 0; for i != j, w[i][j] == infinite indicates there's no path between i and j.
'''
w = [[float('inf') for col in range(26)] for row in range(26)]
for i in range(26):
w[i][i] = 0
for b in a:
if w[ord(b[0]) - 97][ord(b[1]) - 97] > b[2]:
w[ord(b[0]) - 97][ord(b[1]) - 97] = b[2]
for k in range(26):
for i in range(26):
for j in range(26):
if w[i][j] > w[i][k] + w[k][j]:
w[i][j] = w[i][k] + w[k][j]
return w
def test_calc_path():
a = [['a', 'b', 2], ['a', 'c', 6], ['b', 'm', 5], ['c', 'm', 3]]
m = calc_path(a)
print(m)
print(m[ord('a') - 97][ord('m') - 97])
print(m[ord('a') - 97][ord('b') - 97])
def transfer(s, t, a):
'''
this function firstly invokes calc_path to compute all pairs shortest path among alphabet characters, and then computes the minimum transformation position by position of s and t. finally, a minimal transformation weight and outcome is returned.
input:
s, t: the input string to be transformed.
a: the character transformation cost list, 2d. e.g., a = [['a', 'x', 42], ['u', 'v', 8]]: a => x costs 42; u => v costs 8.
result:
-1 if transformation is not possible; otherwise, the minimal transformation cost and result, e.g. '12\nabc'.
'''
if len(s) != len(t):
return -1
r = ''
z = 0
w = calc_path(a)
for d, p in zip(s, t):
if d == p:
r += d
else:
c = float('inf')
q = ''
i = ord(d) - 97
j = ord(p) - 97
for k in range(26):
v = w[i][k] + w[j][k]
if c > v:
c = v
q = chr(k + 97)
if c == float('inf'):
return -1
z += c
r += q
r = str(z) + '\n' + r
return r
def test_transfer():
s = 'uayd'
t = 'uxxd'
a = [['a', 'x', 8], ['x', 'y', 13], ['d', 'c', 3]]
assert transfer(s, t, a) == '21\nuxyd'
s1 = 'a'
t1 = 'b'
a1 = [['a', 'b', 2], ['a', 'b', 3], ['b', 'a', 5]]
assert transfer(s1, t1, a1) == '2\nb'
s2 = 'abc'
t2 = 'ab'
a2 = [['a', 'b', 4], ['a', 'b', 7], ['b', 'a', 8], ['c', 'b', 11], ['c', 'a', 3], ['a', 'c', 0]]
assert transfer(s2, t2, a2) == -1
s3 = 'abcd'
t3 = 'acer'
a3 = [['b', 'c', 100], ['c', 'b', 10], ['c', 'x', 1], ['e', 'x', 3], ['c', 'e', 7], ['r', 'd', 11]]
assert transfer(s3, t3, a3) == '25\nabxd'
def fun():
s = input()
t = input()
n = int(input())
a = []
for c in range(n):
x, y, z = map(str, input().split())
a.append([x, y, int(z)])
print(transfer(s, t, a))
#test_calc_path()
#test_transfer()
fun()
```
|
output
| 1
| 12,787
| 6
| 25,575
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second
|
instruction
| 0
| 12,830
| 6
| 25,660
|
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
# https://codeforces.com/contest/455/problem/B
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
class Trie:
def __init__(self):
self.arr = {}
def insert(self, word):
root = self
for x in word:
if x not in root.arr:
root.arr[x] = Trie()
root = root.arr[x]
def dfs(self):
if not len(self.arr):
return False, True
win, lose = False, False
for x in self.arr:
w, l = self.arr[x].dfs()
win = win or not w
lose = lose or not l
return win, lose
def answer(flag):
print("First" if flag else "Second")
T = Trie()
n, k = map(int, input().split())
for _ in range(n):
T.insert(input())
win, lose = T.dfs()
if k == 1:
answer(win)
elif not win:
answer(win)
elif lose:
answer(win)
elif k&1:
answer(win)
else:
answer(not win)
```
|
output
| 1
| 12,830
| 6
| 25,661
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second
|
instruction
| 0
| 12,831
| 6
| 25,662
|
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 2/11/20
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
def make_trie(A):
trie = {}
for word in A:
t = trie
for w in word:
if w not in t:
t[w] = {}
t = t[w]
# t['#'] = True
return trie
def game(trie):
if not trie:
return False
return not all([game(t) for k, t in trie.items()])
def can_lose(trie):
if not trie:
return True
return any([not can_lose(t) for k, t in trie.items()])
def solve(N, K, A):
trie = make_trie(A)
win = game(trie)
if not win:
return False
if K == 1:
return True
if can_lose(trie):
return True
return K % 2 == 1
N, K = map(int, input().split())
A = []
for i in range(N):
s = input()
A.append(s)
print('First' if solve(N, K, A) else 'Second')
```
|
output
| 1
| 12,831
| 6
| 25,663
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second
|
instruction
| 0
| 12,832
| 6
| 25,664
|
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
class Node:
def __init__(self):
self._next = {}
self._win = None
self._lose = None
def get_or_create(self, c: str):
return self._next.setdefault(c, Node())
def traverse(self):
self._win = False
self._lose = True if len(self._next) == 0 else False
for _, adj in self._next.items():
adj.traverse()
self._win = self._win or not adj._win
self._lose = self._lose or not adj._lose
class Trie:
def __init__(self):
self._root = Node()
def add(self, key: str):
node = self._root
for char in key:
node = node.get_or_create(char)
def traverse(self):
self._root.traverse()
def get_winner(self, k: int):
if not self._root._win:
return 'Second'
if self._root._lose:
return 'First'
if k % 2 == 1:
return 'First'
else:
return 'Second'
if __name__ == "__main__":
n, k = map(int, input().split())
trie = Trie()
for _ in range(n):
trie.add(input())
trie.traverse()
print(trie.get_winner(k))
```
|
output
| 1
| 12,832
| 6
| 25,665
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second
|
instruction
| 0
| 12,833
| 6
| 25,666
|
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
from sys import stdin, setrecursionlimit
setrecursionlimit(200000)
n,k = [int(x) for x in stdin.readline().split()]
tree = {}
for x in range(n):
s = stdin.readline().strip()
cur = tree
for x in s:
if not x in cur:
cur[x] = {}
cur = cur[x]
def forced(tree):
if not tree:
return (False,True)
else:
win = False
lose = False
for x in tree:
a,b = forced(tree[x])
if not a:
win = True
if not b:
lose = True
return (win,lose)
a,b = forced(tree)
if a == 0:
print('Second')
elif a == 1 and b == 1:
print('First')
else:
if k%2 == 0:
print('Second')
else:
print('First')
```
|
output
| 1
| 12,833
| 6
| 25,667
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second
|
instruction
| 0
| 12,834
| 6
| 25,668
|
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
N = 100000
Z = 26
#别用这玩意儿: trie = [[0] * Z] * N 巨坑!https://www.cnblogs.com/PyLearn/p/7795552.html
trie = [[0 for i in range(Z)] for j in range(N)]
n = 0
k = 0
nodeNum = 0
def insertNode():
u = 0
string = input()
global nodeNum
for i in range(len(string)):
c = ord(string[i]) - ord('a')
if trie[u][c] == 0:
nodeNum += 1
trie[u][c] = nodeNum
u = trie[u][c]
# print(u)
stateWin = [False for i in range(N)]
stateLose = [False for i in range(N)]
def dfs(u):
leaf = True
for c in range(Z):
if (trie[u][c]) != 0:
leaf = False
dfs(trie[u][c])
stateWin[u] |= (not(stateWin[trie[u][c]]))
stateLose[u] |= (not(stateLose[trie[u][c]]))
if leaf == True:
stateWin[u] = False
stateLose[u] = True
n,k = map(int,input().split())
for i in range(n):
insertNode()
dfs(0)
# print(stateWin[0])
# print(stateLose[0])
if (stateWin[0] and (stateLose[0] or (k % 2 == 1) )):
print("First")
else:
print("Second")
```
|
output
| 1
| 12,834
| 6
| 25,669
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second
|
instruction
| 0
| 12,835
| 6
| 25,670
|
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
"""
Codeforces Contest 260 Div 1 Problem B
Author : chaotic_iak
Language: Python 3.3.4
"""
def main():
n,k = read()
s = set()
for i in range(n): s.add(read(0))
s = list(s)
s.sort()
s = treeify(s)
res = solve(s)
if res == 0: # neither: second player win
print("Second")
if res == 1: # odd: first player win if k is odd
print("First" if k % 2 else "Second")
if res == 2: # even: second player win
print("Second")
if res == 3: # both: first player win
print("First")
def treeify(s):
res = [[] for _ in range(26)]
for i in s:
if i: res[ord(i[0]) - 97].append(i[1:])
fin = []
for i in range(26):
if res[i]: fin.append(treeify(res[i]))
return fin
def solve(s, parity=2):
for i in range(len(s)):
if isinstance(s[i], list): s[i] = solve(s[i], 3-parity)
if not s: return parity # no possible move: current parity
if 0 in s: return 3 # any neither: both
if 1 in s and 2 in s: return 3 # any odd and any even: both
if 1 in s: return 1 # any odd: odd
if 2 in s: return 2 # any even: even
return 0 # all both: neither
################################### NON-SOLUTION STUFF BELOW
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0: return inputs
if mode == 1: return inputs.split()
if mode == 2: return map(int, inputs.split())
def write(s="\n"):
if isinstance(s, list): s = " ".join(map(str, s))
s = str(s)
print(s, end="")
main()
```
|
output
| 1
| 12,835
| 6
| 25,671
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second
|
instruction
| 0
| 12,836
| 6
| 25,672
|
Tags: dfs and similar, dp, games, implementation, strings, trees
Correct Solution:
```
# https://codeforces.com/contest/455/problem/B
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
class Trie:
def __init__(self):
self.arr = {}
def insert(self, word):
for x in word:
if x not in self.arr:
self.arr[x] = Trie()
self = self.arr[x]
def dfs(self):
if not len(self.arr):
return False, True
win, lose = False, False
for x in self.arr:
w, l = self.arr[x].dfs()
win = win or not w
lose = lose or not l
return win, lose
def answer(flag):
print("First" if flag else "Second")
T = Trie()
n, k = map(int, input().split())
for _ in range(n):
T.insert(input())
win, lose = T.dfs()
if k == 1 or (not win) or lose or k&1:
answer(win)
else:
answer(not win)
```
|
output
| 1
| 12,836
| 6
| 25,673
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
Input
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests.
Next q lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
Output
In the first line output the integer n — the number of users that changed their handles at least once.
In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description.
Examples
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123
|
instruction
| 0
| 12,859
| 6
| 25,718
|
Tags: data structures, dsu, strings
Correct Solution:
```
n=int(input())
queries=[]
names=[]
f=[]
l=[]
for i in range(n):
queries.append(input().split(' '))
for i in range(n):
for j in range(2):
if queries[i][j] in names:
if j==0:
names.remove(queries[i][j])
l[l.index(queries[i][j])]=queries[i][j-1]
else:
names.append(queries[i][j])
if j==0:
f.append(queries[i][j])
else:
if queries[i][j] not in l:
l.append(queries[i][j])
print(len(f))
for k in range(len(f)):
print(f[k],l[k])
```
|
output
| 1
| 12,859
| 6
| 25,719
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
Input
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests.
Next q lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
Output
In the first line output the integer n — the number of users that changed their handles at least once.
In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description.
Examples
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123
|
instruction
| 0
| 12,860
| 6
| 25,720
|
Tags: data structures, dsu, strings
Correct Solution:
```
queries = []
for q in range(int(input())):
old, new = input().split()
done = False
for elem in queries:
if old == elem[-1]:
elem.append(new)
done = True
break
if not done:
queries.append([old, new])
print(len(queries))
for elem in queries:
print(elem[0], elem[-1])
```
|
output
| 1
| 12,860
| 6
| 25,721
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
Input
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests.
Next q lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
Output
In the first line output the integer n — the number of users that changed their handles at least once.
In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description.
Examples
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123
|
instruction
| 0
| 12,861
| 6
| 25,722
|
Tags: data structures, dsu, strings
Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
n = int(input())
b_a = {}
for n_ in range(n):
b, a = input().split()
replaced = False
for k in b_a:
if b_a[k] == b:
b_a[k] = a
replaced = True
if not replaced:
b_a[b] = a
print(len(b_a))
for k in b_a:
print (k + " " + b_a[k])
```
|
output
| 1
| 12,861
| 6
| 25,723
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
Input
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests.
Next q lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
Output
In the first line output the integer n — the number of users that changed their handles at least once.
In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description.
Examples
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123
|
instruction
| 0
| 12,862
| 6
| 25,724
|
Tags: data structures, dsu, strings
Correct Solution:
```
#/usr/bin/env python3
N = int(input())
names = [input().split() for i in range(N)]
c_to_old = dict()
for n in names:
if n[0] not in c_to_old:
c_to_old[n[1]] = n[0]
else:
old = c_to_old[n[0]]
del c_to_old[n[0]]
c_to_old[n[1]] = old
print(len(c_to_old))
thing = sorted(c_to_old.items(), key = lambda x: x[1])
for c, o in thing:
print(o, c)
```
|
output
| 1
| 12,862
| 6
| 25,725
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
Input
The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests.
Next q lines contain the descriptions of the requests, one per line.
Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.
The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.
Output
In the first line output the integer n — the number of users that changed their handles at least once.
In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.
Each user who changes the handle must occur exactly once in this description.
Examples
Input
5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov
Output
3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123
|
instruction
| 0
| 12,863
| 6
| 25,726
|
Tags: data structures, dsu, strings
Correct Solution:
```
# MC521 - Desafios de Programacao I - 1s2021
# Contest: 02/04/2021
# Problema J: Misha and Changing Handles
# le o numero de alteracoes a serem realizadas
n = int(input())
# inicializa o mapa dos idenficadores
alt = {}
# realiza a leitura das alteracoes e mapeia os identificadores dos usuarios
for _ in range(n):
# le o identificador antigo e o novo
antigo, novo = input().split()
# checa se o identficador a ser atualizado existe
if(antigo not in alt):
# caso nao exista
alt[novo] = antigo
else:
# caso exista, atualiza e remove o antigo
alt[novo] = alt[antigo]
alt.pop(antigo, None)
# imprime a quantidade de usuarios diferentes
print(len(alt))
# imprime os idenficadores iniciais e finais de cada usuario
for chave in alt:
print('{name1} {name2}'.format(name1=alt[chave], name2=chave))
```
|
output
| 1
| 12,863
| 6
| 25,727
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.