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
|
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
|
instruction
| 0
| 129
| 6
| 258
|
Tags: strings
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
a = list(input())
b = list(input())
ml = []
for i in range(n-1):
if a[i] != b[i]:
if a[i] in a[i+1:]:
ind = i+1+a[i+1:].index(a[i])
b[i], a[ind] = a[ind], b[i]
ml.append((ind+1, i+1))
elif a[i] in b[i+1:]:
ind1 = i+1+b[i+1:].index(a[i])
a[i+1], b[ind1] = b[ind1], a[i+1]
b[i], a[i+1] = a[i+1], b[i]
ml.append((i+2, ind1+1))
ml.append((i+2, i+1))
else:
break
if a == b:
print('Yes')
print(len(ml))
for i in ml:
print(*i)
else:
print("No")
```
|
output
| 1
| 129
| 6
| 259
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
|
instruction
| 0
| 130
| 6
| 260
|
Tags: strings
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, deque
from bisect import bisect_left
from itertools import product
#input = stdin.buffer.readline
T = int(input())
for _ in range(T):
n = int(input())
a, b = list(input()), list(input())
cc = Counter(a+b)
if any([u%2 for u in cc.values()]):
print("No"); continue
res = []
for i in range(n):
if a[i] == b[i]: continue
if a[i] in a[i+1:]:
p = a[i+1:].index(a[i])
b[i], a[i+p+1] = a[i+p+1], b[i]
res.append((i+p+1, i))
else:
p = b[i+1:].index(a[i])
a[i+1], b[i+p+1] = b[i+p+1], a[i+1]
a[i+1], b[i] = b[i], a[i+1]
res.append((i+1, i+p+1))
res.append((i+1, i))
print("Yes")
print(len(res))
for u, v in res:
print(str(u+1)+' '+str(v+1))
```
|
output
| 1
| 130
| 6
| 261
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
|
instruction
| 0
| 131
| 6
| 262
|
Tags: strings
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
na = list(input())
nb = list(input())
k=0
zz = len(na)
ans = []
for i in range(zz):
f = 0
if(na[i]==nb[i]):
f= 1
if(not f):
for j in range(i+1,zz):
if(na[j]==na[i]):
ans.append((j+1,i+1))
na[j] = nb[i]
f = 1
break
if(not f):
for j in range(i+1,zz):
if(na[i]==nb[j]):
ans.append((j+1,j+1))
ans.append((j+1,i+1))
nb[j] = na[j]
na[j] = nb[i]
f = 1
break
#print(na,nb)
if(not f):
k =1
break
if(k):
print("NO")
else:
print("YES")
print(len(ans))
for t in ans:
print(t[0],t[1])
```
|
output
| 1
| 131
| 6
| 263
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
|
instruction
| 0
| 132
| 6
| 264
|
Tags: strings
Correct Solution:
```
T = int(input())
for t in range(T):
N = int(input())
s = list(input())
t = list(input())
i = 0
possible = True
res = []
while i < N:
# print("i : ", i)
# print("res : ", res)
# print("s[i], t[i] : ", s[i], t[i])
if s[i] != t[i]:
# Find index j such that s[i] == s[j] or s[i] == t[j]
# If no such j, then impossible
j = i + 1
found = False
while j < N:
# print("j : ", j)
# Then we just swap sj with ti
if s[i] == s[j]:
res.append((j, i))
s[j], t[i] = t[i], s[j]
found = True
break
# Then we first swap sj with tj
# Then sj with ti
elif s[i] == t[j]:
res.append((j, j))
s[j], t[j] = t[j], s[j]
res.append((j, i))
s[j], t[i] = t[i], s[j]
found = True
break
j += 1
if not (found):
possible = False
break
i += 1
if possible:
print("Yes")
print(len(res))
for i, j in res:
print(i + 1, j + 1)
else:
print("No")
```
|
output
| 1
| 132
| 6
| 265
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
|
instruction
| 0
| 133
| 6
| 266
|
Tags: strings
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
lis=[0]*2
lis[0]=list(input())
lis[1]=list(input())
ans=[]
gg=0
for i in range(n):
a=lis[0][i]
ind=-1
for j in range(i+1,n):
if a==lis[0][j]:
ind=j
break
if ind!=-1:
ans.append([ind+1,i+1])
lis[1][i],lis[0][ind]=lis[0][ind],lis[1][i]
else:
for j in range(i,n):
if a==lis[1][j]:
ind=j
break
if ind!=-1:
ans.append([n,ind+1])
ans.append([n,i+1])
lis[1][ind],lis[0][n-1]=lis[0][n-1],lis[1][ind]
lis[1][i],lis[0][n-1]=lis[0][n-1],lis[1][i]
else:
print("No")
gg=1
break
if gg==0:
print("Yes")
print(len(ans))
for i in range(len(ans)):
print(*ans[i])
```
|
output
| 1
| 133
| 6
| 267
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
|
instruction
| 0
| 134
| 6
| 268
|
Tags: strings
Correct Solution:
```
import sys
for t in range(int(sys.stdin.readline())):
n = int(sys.stdin.readline())
s1 = [ord(c) - 97 for c in sys.stdin.readline().strip()]
s2 = [ord(c) - 97 for c in sys.stdin.readline().strip()]
pl = []
orde = True
for i in range(26):
st1 = {j for j in range(n) if s1[j] == i}
st2 = {j for j in range(n) if s2[j] == i}
if len(st2) > len(st1):
st1, st2 = st2, st1
s1, s2 = s2, s1
orde = not orde
# stb = set()
rml = []
for el in st2:
if el in st1:
rml.append(el)
for el in rml:
st1.remove(el)
st2.remove(el)
tot = len(st1) + len(st2)
if (tot) & 1:
pl = []
break
# op = -1
# for j in range(25):
# if s2[j] != i:
# op = j
# break
# if op == -1:
# continue
# k = len(st1)//2
# for j in range(k):
# k1 = st1.pop()
# k2 = st1.pop()
# op1 = -1
# while len(st1) > 2:
# k1 = st1.pop()
# k2 = st1.pop()
# pl.append((k1, k2) if orde else (k2, k1))
# s1[k1], s2[k2] = s2[k2], s1[k1]
for k in st2:
st1.add(k)
pl.append((k, k))
s1[k], s2[k] = s2[k], s1[k]
for j in range(tot//2):
k1 = st1.pop()
k2 = st1.pop()
pl.append((k1, k2) if orde else (k2, k1))
s1[k1], s2[k2] = s2[k2], s1[k1]
if pl == []:
print("No")
else:
print(f"Yes\n{len(pl)}\n" + "".join([f"{tup[0] + 1} {tup[1] + 1}\n" for tup in pl]))
```
|
output
| 1
| 134
| 6
| 269
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
|
instruction
| 0
| 135
| 6
| 270
|
Tags: strings
Correct Solution:
```
from collections import defaultdict
# input = sys.stdin.readline
def case():
n = int(input())
s = input()
s = [i for i in s]
t = input()
t = [i for i in t]
d= defaultdict(int)
for i in s:
d[i]+=1
for i in t:
d[i]+=1
for i in d.values():
if i%2:
print("NO")
return
ans = []
for i in range(n):
flag = 0
for j in range(i+1, n):
if s[i] == s[j]:
t[i], s[j] = s[j], t[i]
ans.append([j+1, i+1])
flag = 1
break
if flag:
continue
for j in range(i+1, n):
if s[i] == t[j]:
s[j], t[j] = t[j], s[j]
ans.append([j+1, j+1])
t[i], s[j] = s[j], t[i]
ans.append([j+1, i+1])
flag = 1
break
if flag:
continue
print("YES")
print(len(ans))
for i in ans:
print(*i)
for _ in range(int(input())):
case()
```
|
output
| 1
| 135
| 6
| 271
|
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
|
instruction
| 0
| 136
| 6
| 272
|
Tags: strings
Correct Solution:
```
import sys
input = sys.stdin.readline
for q in range(int(input())):
N = int(input())
s = list(input().rstrip())
t = list(input().rstrip())
ans = []
for i in range(N-1):
if s[i] != t[i]:
for j in range(i + 1, N):
if s[j] == s[i]:
ans.append((j + 1, i + 1))
s[j], t[i] = t[i], s[j]
break
if t[j] == s[i]:
ans.append((i + 2, j + 1))
s[i + 1], t[j] = t[j], s[i + 1]
ans.append((i + 2, i + 1))
s[i + 1], t[i] = t[i], s[i + 1]
break
flag = True
for i in range(N):
if s[i] != t[i]: flag = False
if flag and ans:
print("Yes")
print(len(ans))
for u,v in ans:
print(u, v)
else:
print("No")
```
|
output
| 1
| 136
| 6
| 273
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.
Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
Input
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
Output
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
Examples
Input
aba
Output
First
Input
abca
Output
Second
|
instruction
| 0
| 286
| 6
| 572
|
Tags: games, greedy
Correct Solution:
```
from collections import Counter
s=input()
dic=Counter(s)
count=0
for val in dic.values():
if val%2!=0:
count+=1
if count==0:
print("First")
elif count%2==0:
print("Second")
else:
print("First")
```
|
output
| 1
| 286
| 6
| 573
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.
Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
Input
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
Output
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
Examples
Input
aba
Output
First
Input
abca
Output
Second
|
instruction
| 0
| 287
| 6
| 574
|
Tags: games, greedy
Correct Solution:
```
from collections import Counter
def iswin(c):
if c == c[::-1]:
return True, None
else:
co = Counter(c)
ae = 0
k1 = c[0]
for k, v in co.items():
if v%2==0:
ae += 1
k1 = k
if ae == len(co) or len(co)%2==1 and ae == len(co)-1:
return True, None
else:
return False, k1
s = input()
p = True
res = ''
while s:
# print(s)
r, k = iswin(s)
if not r:
i = s.index(k)
s = s[:i] + s[min(i+1, len(s)-1):]
else:
if p:
res = 'First'
else:
res = 'Second'
break
p = not p
print(res)
```
|
output
| 1
| 287
| 6
| 575
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.
Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
Input
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
Output
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
Examples
Input
aba
Output
First
Input
abca
Output
Second
|
instruction
| 0
| 288
| 6
| 576
|
Tags: games, greedy
Correct Solution:
```
if __name__ == '__main__':
s = input()
c = [s.count(x) for x in set(s)]
total = 0
for x in c:
if x % 2 != 0:
total += 1
if total % 2 == 0 and total != 0:
print("Second")
else:
print("First")
```
|
output
| 1
| 288
| 6
| 577
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.
Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
Input
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
Output
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
Examples
Input
aba
Output
First
Input
abca
Output
Second
|
instruction
| 0
| 289
| 6
| 578
|
Tags: games, greedy
Correct Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/276/B
s = input()
d_e = {}
n_o = 0
for c in s:
if c not in d_e:
d_e[c] = 0
d_e[c] += 1
if (d_e[c] % 2 == 1):
n_o += 1
else:
n_o -= 1
if n_o == 0:
print("First")
elif n_o % 2 == 1:
print("First")
else:
print("Second")
```
|
output
| 1
| 289
| 6
| 579
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.
Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
Input
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
Output
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
Examples
Input
aba
Output
First
Input
abca
Output
Second
|
instruction
| 0
| 290
| 6
| 580
|
Tags: games, greedy
Correct Solution:
```
import sys
arr = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def check(d):
w = 0
for i in d:
if(d[i]%2!=0):
w = w+1
return w
def deeznuts(n):
b = []
for i in n :
b.append(n.count(i))
d = dict(zip(n,b))
w = check(d)
if len(n)%2 == 0 and w == 0:
print('First')
if len(n)%2 == 0 and w!= 0:
print('Second')
if len(n)%2 !=0 and (w%2)!=0:
print('First')
if len(n)%2 !=0 and (w%2)==0:
print('Second')
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(str, input.split()))
n = list(data[0])
deeznuts(n)
```
|
output
| 1
| 290
| 6
| 581
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.
Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
Input
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
Output
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
Examples
Input
aba
Output
First
Input
abca
Output
Second
|
instruction
| 0
| 291
| 6
| 582
|
Tags: games, greedy
Correct Solution:
```
s=list(input())
for n in s:
if n==' ':
s.remove(n)
def normalisation(s):
c=[]
b=set()
for letter in s:
if letter in b:
continue
if s.count(letter)%2==1:
c.append(letter)
b.add(letter)
return c
s=normalisation(s)
def check(s,odds,b):
c=len(s)
if c==1 or c==0:
return True
elif c>1 and odds==c and b==c:
return False
letter=s[b]
count=s.count(letter)
if count%2==0:
while count!=0:
s.remove(letter)
count-=1
return check(s,odds,b)
else:
while count!=1:
s.remove(letter)
count-=1
odds+=1
b+=1
return check(s,odds,b)
count=2
while True:
if count%2==0:
player='First'
else:
player='Second'
if check(s,0,0):
print(player)
break
s.pop(0)
count+=1
```
|
output
| 1
| 291
| 6
| 583
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.
Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
Input
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
Output
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
Examples
Input
aba
Output
First
Input
abca
Output
Second
|
instruction
| 0
| 292
| 6
| 584
|
Tags: games, greedy
Correct Solution:
```
s = input()
dict = {}
l = list(s)
total = -1
for i in l:
if i in dict:
continue
else:
c = l.count(i)
dict[i] = c
if c%2:
total += 1
if total == -1:
print("First")
elif total%2:
print("Second")
else:
print("First")
```
|
output
| 1
| 292
| 6
| 585
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.
Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.
Input
The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.
Output
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
Examples
Input
aba
Output
First
Input
abca
Output
Second
|
instruction
| 0
| 293
| 6
| 586
|
Tags: games, greedy
Correct Solution:
```
word = input()
count = 0
for char in set(word):
if word.count(char) & 1:
count += 1
if count == 0 or count&1:
print("First")
else:
print("Second")
```
|
output
| 1
| 293
| 6
| 587
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
|
instruction
| 0
| 1,111
| 6
| 2,222
|
Tags: *special, data structures, implementation
Correct Solution:
```
def cd(where):
for s in where:
if s == "..":
directories.pop()
else:
directories.append(s)
def pwd():
print("/", end="")
for s in directories:
print(s, "/", sep="", end="")
print()
n = int(input())
directories = [] #храним текущий путь от корня
for i in range(n):
com = input()
if com[0] == "p":
pwd()
else:
com, where = com.split()
where = where.split("/")
if (where[0] == ''):
directories = []
where = where[1:]
cd(where)
```
|
output
| 1
| 1,111
| 6
| 2,223
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
|
instruction
| 0
| 1,112
| 6
| 2,224
|
Tags: *special, data structures, implementation
Correct Solution:
```
n = int(input())
cur = list()
for i in range(0,n):
st = str(input())
if st.startswith('pwd'):
ans = '/'
for s in cur :
ans = ans + s
ans = ans + '/'
print(ans)
else :
st = st.strip()
temp = st.split('/')
for s in temp:
if s == '' :continue
elif s == 'cd ': cur.clear()
elif s == '..' or s == 'cd ..' : cur.pop()
else :
if s.startswith('cd') :
t = s.split()
if len(t) > 1 : cur.append(t[1])
else :
cur.append(s)
```
|
output
| 1
| 1,112
| 6
| 2,225
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
|
instruction
| 0
| 1,113
| 6
| 2,226
|
Tags: *special, data structures, implementation
Correct Solution:
```
n = int(input())
dir = []
def pwd(dir):
if len(dir) == 0:
print("/")
else:
for i in dir:
print("/"+i, end="")
print("/")
for i in range(n):
line = input()
#print("##"+line+"##")
if line.startswith("cd"):
dir_line = line.split()[1].strip()
if dir_line[0] == '/':
dir = []
for i in dir_line[1:].split("/"):
if i == "..":
dir.pop()
else:
dir.append(i)
else:
for i in dir_line.split("/"):
if i == "..":
dir.pop()
else:
dir.append(i)
else:
pwd(dir)
```
|
output
| 1
| 1,113
| 6
| 2,227
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
|
instruction
| 0
| 1,114
| 6
| 2,228
|
Tags: *special, data structures, implementation
Correct Solution:
```
def printPath(path):
print('/', end='')
if len(path):
for dir in path:
print(dir + '/', end='')
print()
# Get input data
num_commands = int(input())
commands = []
for i in range(0, num_commands):
commands.append(input())
current_path = []
for command in commands:
if command == 'pwd':
printPath(current_path)
else:
path = command.split()[1]
if path[0] == '/':
current_path = []
path = path[1:]
for directory in path.split('/'):
if directory == '..':
current_path = current_path[:-1]
else:
current_path.append(directory)
```
|
output
| 1
| 1,114
| 6
| 2,229
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
|
instruction
| 0
| 1,115
| 6
| 2,230
|
Tags: *special, data structures, implementation
Correct Solution:
```
n = int(input())
path = []
for _ in range(n):
s = input().strip()
if s == 'pwd':
print('/' + '/'.join(path) + ['', '/'][bool(path)])
else:
s = s.split(' ')[1]
if s[0] == '/':
s = s.lstrip('/')
path = []
if s:
for p in s.split('/'):
if p == '..':
if path:
path.pop()
else:
path.append(p)
```
|
output
| 1
| 1,115
| 6
| 2,231
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
|
instruction
| 0
| 1,116
| 6
| 2,232
|
Tags: *special, data structures, implementation
Correct Solution:
```
n = int(input())
stacc = ["/"]
while n > 0:
line = input()
linesplit = line.split()
if len(linesplit) == 2:
command = linesplit[0]
parameter = linesplit[1]
else:
command = linesplit[0]
if command == "pwd":
print("".join(stacc))
elif command == "cd":
directory = parameter.split("/")
if not directory[0]:
stacc = ["/"]
for folders in directory:
if folders == "..":
stacc.pop()
else:
if folders:
stacc.append(folders + "/")
n = n - 1
```
|
output
| 1
| 1,116
| 6
| 2,233
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
|
instruction
| 0
| 1,117
| 6
| 2,234
|
Tags: *special, data structures, implementation
Correct Solution:
```
n = int(input())
dirs = ['/']
def ins_split(command):
command = command.split('/')
command[:] = [i for i in command if i != ""]
command[:] = [i+'/' for i in command]
return command
def display():
# indexes to remove
count = dirs.count('../')
for _ in range(count):
j = dirs.index('../')
dirs.remove(dirs[j])
dirs.remove(dirs[j-1])
print(''.join(dirs))
while n:
command = input()
if command == 'pwd': display()
else:
# removing cd part
command = command[3:]
# handling absolute path
if command[0] == '/':
command = ins_split(command)
dirs[1:] = command
# handling relative
else:
command = ins_split(command)
dirs += command
n -= 1
```
|
output
| 1
| 1,117
| 6
| 2,235
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
|
instruction
| 0
| 1,118
| 6
| 2,236
|
Tags: *special, data structures, implementation
Correct Solution:
```
def getNext(s):
return s[3:]
lines = int(input())
stack = ["/"]
for x in range(lines):
command = input()
start = command[0]
if start == "p":
print("".join(stack))
elif start == "c":
folders = getNext(command).split("/")
if not folders[0]:
stack = ["/"]
for folder in folders:
if folder == "..":
stack.pop()
else:
if folder:
stack.append(folder + "/")
```
|
output
| 1
| 1,118
| 6
| 2,237
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
Submitted Solution:
```
n = int(input())
stack = []
for i in range(n):
u = input()
if u == "pwd":
if stack:
print("/"+"/".join(stack)+"/")
else:
print("/")
else:
_, d = u.split()
dirs = d.split('/')
if dirs[0] == "":
stack = []
dirs = dirs[1:]
for d in dirs:
if d == "..":
stack.pop()
else:
stack.append(d)
```
|
instruction
| 0
| 1,119
| 6
| 2,238
|
Yes
|
output
| 1
| 1,119
| 6
| 2,239
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
Submitted Solution:
```
# cd-pwd
# http://codeforces.com/contest/158/problem/C
class Stack:
def __init__(self):
self.dirs = []
def isEmpty(self):
return self.dirs == []
def push(self, item):
return self.dirs.append(item)
def pop(self):
return self.dirs.pop()
def peek(self):
return self.dirs[len(self.dirs)-1]
def size(self):
return len(self.dirs)
def show(self):
if self.dirs==[] or self.dirs[0]!='/':
print('/', end='')
for i in range(len(self.dirs)):
if self.dirs[i]!='':
print(self.dirs[i]+'/', end='')
print()
def pwd(self):
print(self.dirs)
def clear(self):
self.dirs = []
def working(inp):
new = inp.split(' ')
#print("new>>", new)
if new[0] == 'cd':
commands = new[1].split('/')
#print("commands>>", commands)
if commands[0]=='':
directories.clear()
for i in range (len(commands)):
if commands[i]!='':
if commands[i] == '..':
directories.pop()
else:
directories.push(commands[i])
#directories.show()
else:
directories.show()
directories = Stack()
#directories.clear()
numberOfCmds = int(input())
for i in range(numberOfCmds):
working(input())
```
|
instruction
| 0
| 1,120
| 6
| 2,240
|
Yes
|
output
| 1
| 1,120
| 6
| 2,241
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
Submitted Solution:
```
n = int(input())
path = []
for i in range(0,n):
c = input().split()
if c[0] == 'cd':
s = c[1].split('/')
if s[0] == '':
path.clear()
s.pop(0)
for d in s:
if d == '..':
path.pop()
else:
path.append(d)
else:
print('/', end='')
for d in path:
print(d, '/', sep='', end='')
print()
```
|
instruction
| 0
| 1,121
| 6
| 2,242
|
Yes
|
output
| 1
| 1,121
| 6
| 2,243
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
Submitted Solution:
```
res = []
for _ in range(int(input())):
comando = input().split()
# print(comando)
if(len(comando) == 1):
aux = ""
for k in res:
aux += "/" + k
aux += "/"
print(aux)
else:
caminho = comando[1].split('/')
for merda in caminho:
if len(merda) == 0:
res = []
elif merda == "..":
if(len(res) > 0):
res.pop()
else:
res.append(merda)
```
|
instruction
| 0
| 1,122
| 6
| 2,244
|
Yes
|
output
| 1
| 1,122
| 6
| 2,245
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
Submitted Solution:
```
#codeforces
gi = lambda : list(map(int,input().strip().split()))
st = []
for k in range(gi()[0]):
l = input()
if l == "/":
st = []
if l == "pwd":
if st:
print("/" + "/".join(st) + "/")
else:
print("/")
else:
l = l[3:].split("/")
if l[0] == "":
l = l[1:]
for e in l:
if e == "..":
st.pop()
else:
st.append(e)
```
|
instruction
| 0
| 1,123
| 6
| 2,246
|
No
|
output
| 1
| 1,123
| 6
| 2,247
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
Submitted Solution:
```
amount = int(input())
current_dir = '/'
for x in range(amount):
command = input()
if command == 'pwd':
print(current_dir)
continue
cd, new_dir_command = command.split()
splitted_dir = new_dir_command.split("/")
if new_dir_command[0] == "/":
current_dir = ''
splitted_dir.pop(0)
for dir_part in splitted_dir:
if dir_part == '..':
current_dir = current_dir[:current_dir.rfind('/')]
else:
current_dir += "/" + dir_part
```
|
instruction
| 0
| 1,124
| 6
| 2,248
|
No
|
output
| 1
| 1,124
| 6
| 2,249
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
Submitted Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 12/30/19
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
d = []
N = int(input())
for i in range(N):
s = input()
if s == 'pwd':
print('/'.join(d) + '/')
else:
s = s.split(' ')[1]
if s.startswith('/'):
d = []
for v in s.split('/'):
if v == '..':
d.pop()
elif v == '.':
pass
else:
d.append(v)
```
|
instruction
| 0
| 1,125
| 6
| 2,250
|
No
|
output
| 1
| 1,125
| 6
| 2,251
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
Input
The first line of the input data contains the single integer n (1 ≤ n ≤ 50) — the number of commands.
Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.
The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.
Directories in the file system can have the same names.
Output
For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.
Examples
Input
7
pwd
cd /home/vasya
pwd
cd ..
pwd
cd vasya/../petya
pwd
Output
/
/home/vasya/
/home/
/home/petya/
Input
4
cd /a/b
pwd
cd ../a/b
pwd
Output
/a/b/
/a/a/b/
Submitted Solution:
```
n = int(input())
cur = []
for _ in range(n):
s = input()
if s[:3] == 'cd ' :
_, path = s.split()
paths = path.split('/')
for direct in paths:
if direct == '':
continue
elif direct == '..':
cur.pop()
else:
cur += [direct]
else:
print('/' + '/'.join(cur))
```
|
instruction
| 0
| 1,126
| 6
| 2,252
|
No
|
output
| 1
| 1,126
| 6
| 2,253
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
|
instruction
| 0
| 1,141
| 6
| 2,282
|
Tags: constructive algorithms
Correct Solution:
```
a, b = input(), input()
ca = a.count('1')
cb = b.count('1')
if ca + ca % 2 >= cb:
print('YES')
else:
print('NO')
```
|
output
| 1
| 1,141
| 6
| 2,283
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
|
instruction
| 0
| 1,142
| 6
| 2,284
|
Tags: constructive algorithms
Correct Solution:
```
ax, bx = 0, 0
for c in input():
if c == '1':
ax += 1
for c in input():
if c == '1':
bx += 1
print("YES" if bx <= ax + ax % 2 else "NO")
```
|
output
| 1
| 1,142
| 6
| 2,285
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
|
instruction
| 0
| 1,143
| 6
| 2,286
|
Tags: constructive algorithms
Correct Solution:
```
a, b = input(), input()
ax = sum([ord(c) - ord('0') for c in a])
bx = sum([ord(c) - ord('0') for c in b])
print("YES" if bx <= ax + ax % 2 else "NO")
```
|
output
| 1
| 1,143
| 6
| 2,287
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
|
instruction
| 0
| 1,144
| 6
| 2,288
|
Tags: constructive algorithms
Correct Solution:
```
a=input()
b=input()
coa=0
cob=0
for i in a:
if i=='1': coa+=1
for i in b:
if i=='1': cob+=1
if coa+(coa&1)>=cob:print('YES')
else:print('NO')
```
|
output
| 1
| 1,144
| 6
| 2,289
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
|
instruction
| 0
| 1,145
| 6
| 2,290
|
Tags: constructive algorithms
Correct Solution:
```
def play(s, t):
count1, count2 = 0, 0
for elem in s:
if elem == '1':
count1 += 1
for elem in t:
if elem == '1':
count2 += 1
if count2 - count1 > 1 or (count2 - count1 == 1 and count1 % 2 == 0):
return "NO"
return "YES"
a = input()
b = input()
print(play(a, b))
```
|
output
| 1
| 1,145
| 6
| 2,291
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
|
instruction
| 0
| 1,146
| 6
| 2,292
|
Tags: constructive algorithms
Correct Solution:
```
print('YES' if input().count('1')+1>>1<<1 >= input().count('1') else 'NO')
```
|
output
| 1
| 1,146
| 6
| 2,293
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
|
instruction
| 0
| 1,147
| 6
| 2,294
|
Tags: constructive algorithms
Correct Solution:
```
a = input()
b = input()
if ((a.count('1') + 1) // 2 * 2) >= b.count('1'):
print("YES")
else:
print("NO")
```
|
output
| 1
| 1,147
| 6
| 2,295
|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:
* Write parity(a) to the end of a. For example, <image>.
* Remove the first character of a. For example, <image>. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
Input
The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
Output
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
Examples
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
Note
In the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
|
instruction
| 0
| 1,148
| 6
| 2,296
|
Tags: constructive algorithms
Correct Solution:
```
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 list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
a = ri()
b = ri()
cnt1, cnt2 = 0,0
cnt1= a.count('1')
cnt2 = b.count('1')
if cnt1%2 == 1:
cnt1+=1
if cnt1 < cnt2:
NO()
else:
YES()
```
|
output
| 1
| 1,148
| 6
| 2,297
|
Provide tags and a correct Python 3 solution for this coding contest problem.
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input
The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.
Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Examples
Input
5
aca
aba
aba
cab
bac
Output
YES
abacaba
Input
4
abc
bCb
cb1
b13
Output
NO
Input
7
aaa
aaa
aaa
aaa
aaa
aaa
aaa
Output
YES
aaaaaaaaa
|
instruction
| 0
| 1,252
| 6
| 2,504
|
Tags: dfs and similar, graphs
Correct Solution:
```
n = int(input())
g = {}
ins = {}
outs = {}
vs = set()
for _ in range(n):
s = input().strip()
left = s[:-1]
right = s[1:]
g.setdefault(left, []).append(right)
outs[left] = outs.get(left, 0) + 1
ins[right] = ins.get(right, 0) + 1
vs.add(left)
vs.add(right)
# print(g)
# print(outs)
# print(ins)
wrong = []
for v in vs:
# print(v, outs.get(v, 0), ins.get(v, 0))
if outs.get(v, 0) != ins.get(v, 0):
wrong.append(v)
# print(wrong)
if len(wrong) not in (0, 2):
print("NO")
exit()
if wrong:
a, b = wrong
if abs(ins.get(a, 0) - outs.get(a, 0)) != 1 or abs(ins.get(b, 0) - outs.get(b, 0)) != 1:
print("NO")
exit()
if ins.get(a, 0) < outs.get(a, 0):
a, b = b, a
stack = [a, b]
else:
stack = [next(iter(g))]
ans = []
while stack:
v = stack[-1]
# print("ON STACK", v)
if not g.get(v, []):
if ans:
ans.append(v[0])
else:
ans.append(v)
# print("TO ANS", v)
stack.pop(-1)
else:
u = g[v].pop()
# print("GO TO", u, g)
stack.append(u)
if wrong:
ans.pop(-1)
ans.reverse()
if len(ans) != n + 1:
print("NO")
else:
print("YES")
print("".join(ans))
```
|
output
| 1
| 1,252
| 6
| 2,505
|
Provide tags and a correct Python 3 solution for this coding contest problem.
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input
The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.
Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Examples
Input
5
aca
aba
aba
cab
bac
Output
YES
abacaba
Input
4
abc
bCb
cb1
b13
Output
NO
Input
7
aaa
aaa
aaa
aaa
aaa
aaa
aaa
Output
YES
aaaaaaaaa
|
instruction
| 0
| 1,253
| 6
| 2,506
|
Tags: dfs and similar, graphs
Correct Solution:
```
# from debug import debug
from collections import defaultdict, Counter, deque
import sys; input = sys.stdin.readline
n = int(input())
graph = defaultdict(list)
d = Counter()
for i in range(n):
s = input().strip()
a, b = s[:2], s[1:3]
if i == 0: e = a
graph[a].append(b)
d[a] += 1
d[b] -= 1
start, stop = -1, -1
for k,v in d.items():
if v>1: print("NO"); sys.exit()
if v == 1 and start == -1: start = k
elif v == 1 and start != -1: print("NO"); sys.exit()
if start == -1: start = e
# debug(g=graph)
# finding eular path
stack = [start]
ans = deque()
while stack:
node = stack[-1]
if graph[node]: stack.append(graph[node].pop())
else: ans.appendleft(stack.pop()[1])
ans.appendleft(start[0])
if len(ans) != n+2: print("NO"); sys.exit()
print("YES")
print(*ans, sep="")
```
|
output
| 1
| 1,253
| 6
| 2,507
|
Provide tags and a correct Python 3 solution for this coding contest problem.
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input
The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.
Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Examples
Input
5
aca
aba
aba
cab
bac
Output
YES
abacaba
Input
4
abc
bCb
cb1
b13
Output
NO
Input
7
aaa
aaa
aaa
aaa
aaa
aaa
aaa
Output
YES
aaaaaaaaa
|
instruction
| 0
| 1,254
| 6
| 2,508
|
Tags: dfs and similar, graphs
Correct Solution:
```
from collections import defaultdict, Counter
def quit():
print('NO')
exit()
def dfs(i): #topological sorting
S = [i]
while S:
s = S[-1]
if graph[s]:
S.append(graph[s].pop())
else:
S.pop()
ans.append(s[-1])
n = int(input())
s = [input() for _ in range(n)]
graph = defaultdict(list)
count = Counter()
start = None
for e in s:
x,y = e[:2], e[1:]
if not start: start = x
count[x]+=1
count[y]-=1
graph[x].append(y)
odd_in, odd_out = 0,0
for key,val in count.items() :
if abs(val)>1:
quit()
if val==-1:
odd_in+=1
if val==1 :
odd_out+=1
start = key
if odd_in!=odd_out or (odd_in+odd_out) not in [0,2]:
quit()
ans = []
dfs(start)
ans.append(start[0])
ans.reverse()
if len(ans)!=n+2:
quit()
print('YES')
print(''.join(ans))
```
|
output
| 1
| 1,254
| 6
| 2,509
|
Provide tags and a correct Python 3 solution for this coding contest problem.
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input
The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.
Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Examples
Input
5
aca
aba
aba
cab
bac
Output
YES
abacaba
Input
4
abc
bCb
cb1
b13
Output
NO
Input
7
aaa
aaa
aaa
aaa
aaa
aaa
aaa
Output
YES
aaaaaaaaa
|
instruction
| 0
| 1,255
| 6
| 2,510
|
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
from string import ascii_lowercase, ascii_uppercase, digits
def hierholzer(N, M, E):
G = [[] for i in range(N)]
deg = [0]*N
rdeg = [0]*N
for a, b in E:
deg[a] += 1
rdeg[b] += 1
G[a].append(b)
s = t = u = -1
for i in range(N):
if deg[i] == rdeg[i] == 0:
continue
df = deg[i] - rdeg[i]
if not -1 <= df <= 1:
return None
if df == 1:
if s != -1:
return None
s = i
elif df == -1:
if t != -1:
return None
t = i
else:
u = i
v0 = (s if s != -1 else u)
res = []
it = [0]*N
st = [v0]
while st:
v = st[-1]
if it[v] == len(G[v]):
res.append(v)
st.pop()
continue
w = G[v][it[v]]
it[v] += 1
st.append(w)
res.reverse()
if len(res) != M+1:
return None
return res
def solve():
N = int(readline())
cs = ascii_lowercase + ascii_uppercase + digits
A = len(cs)
E = []
for i in range(N):
a, b, c = map(cs.index, readline().strip())
v0 = A*a + b
v1 = A*b + c
E.append((v0, v1))
res = hierholzer(A*A, N, E)
if res is None:
write("NO\n")
else:
write("YES\n")
ans = []
for e in res[:N]:
ans.append(cs[e // A])
e = res[N]
ans.append(cs[e // A])
ans.append(cs[e % A])
write("".join(ans))
write("\n")
solve()
```
|
output
| 1
| 1,255
| 6
| 2,511
|
Provide tags and a correct Python 3 solution for this coding contest problem.
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input
The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.
Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Examples
Input
5
aca
aba
aba
cab
bac
Output
YES
abacaba
Input
4
abc
bCb
cb1
b13
Output
NO
Input
7
aaa
aaa
aaa
aaa
aaa
aaa
aaa
Output
YES
aaaaaaaaa
|
instruction
| 0
| 1,256
| 6
| 2,512
|
Tags: dfs and similar, graphs
Correct Solution:
```
def dfs(start_vertex, go_out):
m = 0
last = {}
for key, value in go_out.items():
last[key] = value - 1 # -1for each item from go_out
m += value # And total count of ways
stack = [start_vertex] # Init stack and put first vertex
path = [] # Result path
while stack:
now = stack[-1] # take one vertex
if last[now] == -1: # If all paths have already been gone:
stack.pop() # Delete this vertex from stack...
path.append(now) # And add to the result. Do not forget to reverse the result
continue
# Choosing nex vertex - simply with index las[now]. For this the 2-3 line.
nex = vertexes[now][last[now]]
last[now] -= 1 # This way is gone...
m -= 1 # and here (total count)...
stack.append(nex) # TODO this vertex
return path if m == 0 else [] # If one or more ways have not been gone: path = []
n = int(input())
strings = [input() for _ in range(n)]
parts = set()
# Building vertexes and go_in:
vertexes = {}
for string in strings:
part1 = string[:2]
part2 = string[1:]
parts.add(part1)
parts.add(part2)
try:
vertexes[part1].append(part2)
except Exception:
vertexes[part1] = [part2]
# //////////////////
parts = list(parts)
# Building go_in and go_out:
go_in = {i: 0 for i in parts}
go_out = go_in.copy()
for go_from, go_to in vertexes.items():
go_out[go_from] += len(go_to)
for i in go_to:
go_in[i] += 1
# //////////////////////////
# Serching for vertex with go_out > go_in and for the main answer: YES or NO:
count = 0
start_vertex = 0
for i in range(len(parts)):
if go_out[parts[i]] - go_in[parts[i]] > 1:
count = 3 # Any number > 2
break
if go_out[parts[i]] != go_in[parts[i]]:
count += 1
if go_out[parts[i]] > go_in[parts[i]]:
start_vertex = i
# ////////////////////////////////////////
if count > 2:
print('NO')
else:
path = dfs(parts[start_vertex], go_out)
if path:
# Building result
path.reverse()
result = [path[0][0]]
for item in path:
result.append(item[1])
print('YES')
print(''.join(result))
else:
print('NO')
```
|
output
| 1
| 1,256
| 6
| 2,513
|
Provide tags and a correct Python 3 solution for this coding contest problem.
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input
The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.
Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Examples
Input
5
aca
aba
aba
cab
bac
Output
YES
abacaba
Input
4
abc
bCb
cb1
b13
Output
NO
Input
7
aaa
aaa
aaa
aaa
aaa
aaa
aaa
Output
YES
aaaaaaaaa
|
instruction
| 0
| 1,257
| 6
| 2,514
|
Tags: dfs and similar, graphs
Correct Solution:
```
def out(a):
print('-'*len(a))
for i in range(len(a)):
print(*[a[i][j] for j in range(len(a[0]))])
print('-'*len(a))
def get_point(p):
return len(adj_list[p])
def find_way(p):
if sum(adj_list[p])>0:
for point in range(len(adj_list[p])):
if adj_list[p][point]==1:
if(sum(adj_list[point])):
flag=False
for _ in adj_list:
if _[point]==1:
flag=True
break
if(flag):
return point
else:
continue
return adj_list[p].index(1)
return -1
def obh(a):
while sum(adj_list[a])>0:
#print(a,sum(adj_list[a]),prefix)
b=adj_list[a].index(1)
flag=False
for point in black:
if b==point:
flag=True
break
adj_list[a][b]=0
adj_list[b][a]=0
if(flag):
continue
obh(b)
def conv(a):
return str(a+1)
def euler(g,A,end):
stack=[A]
ans=[]
while stack:
v=stack[-1]
if not g[v]:
ans.append(v)
stack.pop(-1)
else:
d=g[v].pop()
## if d==end:
## for i in range(len(g[v])):
## if(g[v][i]!=end):
## d=i
## del g[v][i]
## g[v].append(end)
## break
stack.append(d)
return ans
n=int(input())
verts={}
averts=[]
g=[]
g_in=[]
for i in range(n):
string=input().strip()
a,b=string[:-1],string[1:]
if(verts.get(a)==None):
verts[a]=len(g)
averts.append(a)
g.append([])
g_in.append([])
if(verts.get(b)==None):
verts[b]=len(g)
averts.append(b)
g.append([])
g_in.append([])
g[verts[a]].append(verts[b])
g_in[verts[b]].append(verts[a])
start=-1
end=-1
for j in range(len(g)):
summ_input=len(g_in[j])
summ_output=len(g[j])
if(summ_input>summ_output):
if(end!=-1 or summ_input!=summ_output+1):
print('NO')
exit()
end=j
elif(summ_input<summ_output):
if(start!=-1 or summ_output!=summ_input+1):
print('NO')
exit()
start=j
if start==-1: start=0
ans=euler(g,start,end)
ans.reverse()
if(len(ans)-1!=n):
print('NO')
exit()
string=''
print('YES')
for _ in range(len(ans)-1):
string+=averts[ans[_]][0]
string+=averts[ans[len(ans)-1]]
print(string)
```
|
output
| 1
| 1,257
| 6
| 2,515
|
Provide tags and a correct Python 3 solution for this coding contest problem.
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input
The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.
Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Examples
Input
5
aca
aba
aba
cab
bac
Output
YES
abacaba
Input
4
abc
bCb
cb1
b13
Output
NO
Input
7
aaa
aaa
aaa
aaa
aaa
aaa
aaa
Output
YES
aaaaaaaaa
|
instruction
| 0
| 1,258
| 6
| 2,516
|
Tags: dfs and similar, graphs
Correct Solution:
```
import collections
def negation() :
print("NO")
exit()
NumberOfCharacters = int(input())
vertex = collections.defaultdict(list)
counterr = collections.Counter()
for i in range(NumberOfCharacters):
value = input()
v1,v2 = value[:2],value[1:3]
if i == 0 : start = v1
vertex[v1].append(v2)
counterr[v1]+=1
counterr[v2]-=1
strt = False
end = False
for key,val in counterr.items() :
if abs(val) > 1 : negation()
if val == 1:
if strt : negation()
strt,start = True,key
if val == -1:
if end : negation()
end = True
if strt != end : negation()
P_val = [start]
result = []
while P_val :
temp = P_val[-1]
if vertex[temp] :
P_val.append(vertex[temp].pop())
else :
P_val.pop(-1)
result.append(temp[1])
result.append(start[0])
result.reverse()
if len(result) == NumberOfCharacters+2 :
print("YES")
print("".join(result))
else : negation()
```
|
output
| 1
| 1,258
| 6
| 2,517
|
Provide tags and a correct Python 3 solution for this coding contest problem.
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
Input
The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.
Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.
Output
If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".
If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.
Examples
Input
5
aca
aba
aba
cab
bac
Output
YES
abacaba
Input
4
abc
bCb
cb1
b13
Output
NO
Input
7
aaa
aaa
aaa
aaa
aaa
aaa
aaa
Output
YES
aaaaaaaaa
|
instruction
| 0
| 1,259
| 6
| 2,518
|
Tags: dfs and similar, graphs
Correct Solution:
```
INT_MAX = int(1e9 + 7)
def dfs(start_vertex, go_out):
m = 0
last = {}
for key, value in go_out.items():
last[key] = value - 1 # -1for each item from go_out
m += value # And total count of ways
stack = [start_vertex] # Init stack and put first vertex
path = [] # Result path
while stack:
now = stack[-1] # take one vertex
if last[now] == -1: # If all paths have already been gone:
stack.pop() # Delete this vertex from stack...
path.append(now) # And add to the result. Do not forget to reverse the result
continue
# Choosing nex vertex - simply with index las[now]. For this the 2-3 line.
nex = vertexes[now][last[now]]
last[now] -= 1 # This way is gone...
m -= 1 # and here (total count)...
stack.append(nex) # TODO this vertex
# print(m)
return path if m == 0 else [] # If one or more ways have not been gone: path = []
n = int(input())
strings = [input() for _ in range(n)]
# print()
parts = set()
# Building vertexes and go_in:
vertexes = {}
for string in strings:
part1 = string[:2]
part2 = string[1:]
parts.add(part1)
parts.add(part2)
try:
vertexes[part1].append(part2)
except Exception:
vertexes[part1] = [part2]
# //////////////////
# And parts from vetexes:
# parts = list(vertexes.keys())
parts = list(parts)
# ///////////////////////
# print('vertexes =', vertexes)
# exit()
# Building go_in and go_out:
go_in = {i: 0 for i in parts}
go_out = go_in.copy()
for go_from, go_to in vertexes.items():
go_out[go_from] += len(go_to)
for i in go_to:
go_in[i] += 1
# //////////////////////////
# print('parts =', parts)
# print('go_in =', go_in)
# print('go_out =', go_out)
# Serching for vertex with go_out > go_in and for the main answer: YES or NO:
count = 0
start_vertex = 0
for i in range(len(parts)):
if go_out[parts[i]] - go_in[parts[i]] > 1:
count = INT_MAX
break
if go_out[parts[i]] != go_in[parts[i]]:
count += 1
if go_out[parts[i]] > go_in[parts[i]]:
start_vertex = i
# ////////////////////////////////////////
# print(count)
if count > 2:
print('NO')
else:
path = dfs(parts[start_vertex], go_out)
# print(path)
if path:
print('YES')
path.reverse()
# print(path)
# exit()
# while m:
# flag = False
# for i in range(len(answer)):
# for new, done in vertexes[answer[i]]:
# if not done:
# answer = answer[:i] + dfs(answer[i]) + answer[i + 1:]
# flag = True
# break
# if flag:
# break
# Building result
result = list(path[0])
for i in range(1, len(path)):
result.append(path[i][1])
print(''.join(result))
else:
print('NO')
```
|
output
| 1
| 1,259
| 6
| 2,519
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 ≤ n ≤ 105, 1 ≤ m, q ≤ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 ≤ t ≤ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
|
instruction
| 0
| 1,363
| 6
| 2,726
|
Tags: data structures, dfs and similar, dp, dsu, graphs
Correct Solution:
```
f = lambda: input().split()
n, m, k = map(int, f())
u = list(range(n + 1))
v = [n] * n
s = {q: i for i, q in zip(u, f())}
p = ['YES'] * m
def g(i):
k = u[i]
while k != u[k]: k = u[k]
while u[i] != k: i, u[i] = u[i], k
return k
for l in range(m):
r, x, y = f()
i, j = s[x], s[y]
a, b = g(i), g(j)
i, j = v[a], v[b]
c, d = g(i), g(j)
if r == '2': b, d = d, b
if a == d: p[l] = 'NO'
elif c == b == n: v[a], v[d] = d, a
elif c == b: p[l] = 'NO'
elif c == n: u[a] = b
elif b == n: u[d] = c
elif d == n: u[b] = a
else: u[a], u[c] = b, d
u = [g(q) for q in u]
v = [u[q] for q in v]
for l in range(k):
x, y = f()
i, j = s[x], s[y]
a, c = u[i], u[j]
p.append(str(3 - 2 * (a == c) - (a == v[c])))
print('\n'.join(p))
```
|
output
| 1
| 1,363
| 6
| 2,727
|
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 ≤ n ≤ 105, 1 ≤ m, q ≤ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 ≤ t ≤ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
|
instruction
| 0
| 1,364
| 6
| 2,728
|
Tags: data structures, dfs and similar, dp, dsu, graphs
Correct Solution:
```
def get_relation(synonyms, antonyms, word1, word2):
if word1 not in synonyms or word2 not in synonyms:
return '3'
group1 = synonyms[word1]
group2 = synonyms[word2]
if group1 == group2:
return '1'
if group1 in antonyms and antonyms[group1] == group2:
return '2'
return '3'
def unify_synonyms(synonyms, groups, group1, group2):
min_group = min(group1, group2)
max_group = max(group1, group2)
max_synonyms = groups[max_group]
for synonym in max_synonyms:
synonyms[synonym] = min_group
update_groups(groups, min_group, max_synonyms)
return min_group, max_group
def make_synonyms(synonyms, antonyms, groups, group1, group2):
min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2)
if group1 in antonyms and group2 in antonyms:
min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2])
del antonyms[min_group1]
del antonyms[max_group1]
del antonyms[min_group2]
del antonyms[max_group2]
antonyms[min_group1] = min_group2
antonyms[min_group2] = min_group1
return min_group1
if max_group1 in antonyms:
antonym_group = antonyms[max_group1]
del antonyms[max_group1]
antonyms[min_group1] = antonym_group
antonyms[antonym_group] = min_group1
return min_group1
def update_groups(groups, group, words):
if group in groups:
groups[group].update(words)
else:
groups.update({group: set(words)})
def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group):
if relation == '1':
if word1 not in synonyms and word2 not in synonyms:
current_group += 1
synonyms[word1] = current_group
synonyms[word2] = current_group
update_groups(groups, current_group, [word1, word2])
return current_group
if word1 not in synonyms:
synonyms[word1] = synonyms[word2]
update_groups(groups, synonyms[word2], [word1])
return current_group
if word2 not in synonyms:
synonyms[word2] = synonyms[word1]
update_groups(groups, synonyms[word1], [word2])
return current_group
group1 = synonyms[word1]
group2 = synonyms[word2]
if group1 != group2:
make_synonyms(synonyms, antonyms, groups, group1, group2)
return current_group
if relation == '2':
if word1 not in synonyms:
current_group += 1
group1 = current_group
synonyms[word1] = group1
update_groups(groups, group1, [word1])
else:
group1 = synonyms[word1]
if word2 not in synonyms:
current_group += 1
group2 = current_group
synonyms[word2] = group2
update_groups(groups, group2, [word2])
else:
group2 = synonyms[word2]
if group1 not in antonyms and group2 not in antonyms:
antonyms[group1] = group2
antonyms[group2] = group1
return current_group
if group1 in antonyms and antonyms[group1] != group2:
antonym_group = antonyms[group1]
group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group)
if group2 in antonyms and antonyms[group2] != group1:
antonym_group = antonyms[group2]
make_synonyms(synonyms, antonyms, groups, group1, antonym_group)
return current_group
def make_relations(relation_no):
synonyms = dict()
antonyms = dict()
groups = dict()
current_group = 0
for relation in range(relation_no):
relation, word1, word2 = input().split()
current_relation = get_relation(synonyms, antonyms, word1, word2)
if current_relation == '2' and relation == '1':
print ('NO')
continue
if current_relation == '1' and relation == '2':
print ('NO')
continue
print ('YES')
current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group)
return synonyms, antonyms
def answer_questions(question_no, synonyms, antonyms):
for question in range(question_no):
word1, word2 = input().split()
print(get_relation(synonyms, antonyms, word1, word2))
def main():
word_no, relation_no, question_no = [int(number) for number in input().split()]
input()
synonyms, antonyms = make_relations(relation_no)
answer_questions(question_no, synonyms, antonyms)
main()
```
|
output
| 1
| 1,364
| 6
| 2,729
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.