text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Submitted Solution:
```
import sys
from itertools import permutations, takewhile
from collections import deque, defaultdict
from functools import lru_cache, reduce
@lru_cache(maxsize=128)
def node_successors(tree, seed):
count = 0
stack = [seed]
while stack:
node = stack.pop()
count += len(tree[node])
stack += tree[node]
return count
def proc(tree):
dist = [None]*len(tree)
dist[0] = 1
q = deque([0])
while q:
node = q.popleft()
#tnode - ΡΠ·Π΅Π», Π΄Π»Ρ ΠΊΠΎΡΠΎΡΠΎΠ³ΠΎ ΡΡΠΈΡΠ°Π΅ΠΌ ΠΌΠ°Ρ ΠΎΠΆΠΈΠ΄Π°Π½ΠΈΠ΅
for tnode in tree[node]:
ndist, tdists = 0, defaultdict(int)
for perm in permutations(tree[node]):
pdist = 1 + sum(1+node_successors(tree, n) for n in takewhile(lambda x: x != tnode, perm))
tdists[pdist] += 1
ndist += 1
dist[tnode] = sum(d*c/ndist for d,c in tdists.items()) + dist[node]
q.append(tnode)
return dist
def read_tree(f):
n = int(f.readline())
tree = [[] for _ in range(n)]
for i, k in enumerate(map(int, f.readline().split())):
tree[k-1].append(i+1)
return tuple(map(tuple, tree))
if __name__ == "__main__":
tree = read_tree(sys.stdin)
print(proc(tree))
```
No
| 108,300 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Submitted Solution:
```
n=int(input())
x=input().split(' ')
x.insert(0, 0)
x.insert(0, 0)
print(x)
for i in range(len(x)): x[i]=int(x[i])
print(x, '\n')
C=[[] for i in range(n+1)]
w=2
for i in x[2:]:
C[i].append(w)
w+=1
print(C)
E=[0, 1]+[0 for i in range(n-1)]
ch=[0 for i in range (n+1)]
for i in range(1, n+1):
k=i
while k!=0:
ch[k]+=1
k=x[k]
print (ch)
def make(w):
for i in C[w]:
E[i]=E[w]+(ch[w]-ch[i]+1)/2
make(i)
make(1)
for i in range(n+1): E[i]=str(E[i])
print(' '.join(E[1:]))
```
No
| 108,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha has an array of integers a1, a2, ..., an. You have to perform m queries. There might be queries of two types:
1. 1 l r x β increase all integers on the segment from l to r by values x;
2. 2 l r β find <image>, where f(x) is the x-th Fibonacci number. As this number may be large, you only have to find it modulo 109 + 7.
In this problem we define Fibonacci numbers as follows: f(1) = 1, f(2) = 1, f(x) = f(x - 1) + f(x - 2) for all x > 2.
Sasha is a very talented boy and he managed to perform all queries in five seconds. Will you be able to write the program that performs as well as Sasha?
Input
The first line of the input contains two integers n and m (1 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of elements in the array and the number of queries respectively.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Then follow m lines with queries descriptions. Each of them contains integers tpi, li, ri and may be xi (1 β€ tpi β€ 2, 1 β€ li β€ ri β€ n, 1 β€ xi β€ 109). Here tpi = 1 corresponds to the queries of the first type and tpi corresponds to the queries of the second type.
It's guaranteed that the input will contains at least one query of the second type.
Output
For each query of the second type print the answer modulo 109 + 7.
Examples
Input
5 4
1 1 2 1 1
2 1 5
1 2 4 2
2 2 4
2 1 5
Output
5
7
9
Note
Initially, array a is equal to 1, 1, 2, 1, 1.
The answer for the first query of the second type is f(1) + f(1) + f(2) + f(1) + f(1) = 1 + 1 + 1 + 1 + 1 = 5.
After the query 1 2 4 2 array a is equal to 1, 3, 4, 3, 1.
The answer for the second query of the second type is f(3) + f(4) + f(3) = 2 + 3 + 2 = 7.
The answer for the third query of the second type is f(1) + f(3) + f(4) + f(3) + f(1) = 1 + 2 + 3 + 2 + 1 = 9.
Submitted Solution:
```
fibs, prev = [0, 1], 1
def fib_to(new):
global prev, fibs
if new > prev:
for i in range(prev+1, new+1):
fibs.append(fibs[i-1] + fibs[i-2])
prev = new
return fibs[new]
n, m = map(int, input().split())
omg = list(map(int, input().split()))
#print(omg)
for i in range(m):
q = list(map(int, input().split()))
if q[0] == 1:
l, r, x = q[1], q[2], q[3]
for j in range(l-1, r):
omg[j] += x
#print(omg)
else:
l, r = q[1], q[2]
s = 0
for j in range(l-1, r):
s += fib_to(omg[j])
print(s)
```
No
| 108,302 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha has an array of integers a1, a2, ..., an. You have to perform m queries. There might be queries of two types:
1. 1 l r x β increase all integers on the segment from l to r by values x;
2. 2 l r β find <image>, where f(x) is the x-th Fibonacci number. As this number may be large, you only have to find it modulo 109 + 7.
In this problem we define Fibonacci numbers as follows: f(1) = 1, f(2) = 1, f(x) = f(x - 1) + f(x - 2) for all x > 2.
Sasha is a very talented boy and he managed to perform all queries in five seconds. Will you be able to write the program that performs as well as Sasha?
Input
The first line of the input contains two integers n and m (1 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of elements in the array and the number of queries respectively.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Then follow m lines with queries descriptions. Each of them contains integers tpi, li, ri and may be xi (1 β€ tpi β€ 2, 1 β€ li β€ ri β€ n, 1 β€ xi β€ 109). Here tpi = 1 corresponds to the queries of the first type and tpi corresponds to the queries of the second type.
It's guaranteed that the input will contains at least one query of the second type.
Output
For each query of the second type print the answer modulo 109 + 7.
Examples
Input
5 4
1 1 2 1 1
2 1 5
1 2 4 2
2 2 4
2 1 5
Output
5
7
9
Note
Initially, array a is equal to 1, 1, 2, 1, 1.
The answer for the first query of the second type is f(1) + f(1) + f(2) + f(1) + f(1) = 1 + 1 + 1 + 1 + 1 = 5.
After the query 1 2 4 2 array a is equal to 1, 3, 4, 3, 1.
The answer for the second query of the second type is f(3) + f(4) + f(3) = 2 + 3 + 2 = 7.
The answer for the third query of the second type is f(1) + f(3) + f(4) + f(3) + f(1) = 1 + 2 + 3 + 2 + 1 = 9.
Submitted Solution:
```
def myround(x):
return int(x) if (x - int(x) == 0) else int(x) + 1
raw = input().split()
n = int(raw[0])
m = int(raw[1])
struct = []
tmpn = n
while (True):
struct.append([0 for j in range(tmpn)])
if tmpn == 1: break
tmpn = myround(tmpn / 2)
raw = input().split()
for i in range(n):
struct[0][i] = int(raw[i])
divider = [1000000007]
def show(struct):
for a in struct:
for x in a:
print(x, end=' ')
print()
def isStarts(depth, l):
return (l % (1 << depth)) == 0
def inBounds(depth, l, r):
# print(depth)
return (1 << depth) <= (r - l + 1)
def isEnds(depth, r):
return ((l + 1) % (1 << depth)) == 0
def add(struct, depth, l, dx):
# print('add')
struct[depth][l // (1 << depth)] += dx
def get(struct, start):
res = 0
for i in range(len(struct)):
res += struct[i][start - 1]
start = myround(start / 2)
# print('start = ' + str(start))
return res
def mypow(i):
if i == 1:
return [[0, 1], [1, 1]]
elif i > 1:
mat = mypow(i // 2)
if i % 2 == 0:
return mult(mat, mat)
else:
return mult(mult(mat, mat), mypow(1))
def mult(mat1, mat2):
return [[(mat1[0][0]% divider[0] * mat2[0][0]% divider[0])% divider[0] + (mat1[0][1]% divider[0] * mat2[1][0]% divider[0])% divider[0],
(mat1[1][0]% divider[0] * mat2[0][0]% divider[0])% divider[0] + (mat1[1][1]% divider[0] * mat2[1][0]% divider[0])% divider[0]],
[(mat1[0][0]% divider[0] * mat2[0][1]% divider[0])% divider[0] + (mat1[0][1]% divider[0] * mat2[1][1]% divider[0])% divider[0],
(mat1[1][0]% divider[0] * mat2[0][1]% divider[0])% divider[0] + (mat1[1][1]% divider[0] * mat2[1][1]% divider[0])% divider[0]]]
def countFib(i):
mat = mypow(i)
if mat != None:
return(mat[0][1] % divider[0])
for i in range(m):
raw = input().split()
l = int(raw[1]) - 1
r = int(raw[2]) - 1
if raw[0] == '1':
dx = int(raw[3])
depth = 0
while l <= r:
while inBounds(depth, l, r):
if isStarts(depth + 1, l):
depth += 1
else:
add(struct, depth, l, dx)
l += (1 << depth)
depth = max(depth - 1, 0)
if inBounds(depth, l, r) and isStarts(depth, l):
add(struct, depth, l, dx)
l += (1 << depth)
else:
depth = 0
# print('l = ' + str(l))
# print('r = ' + str(r))
# while (inBounds(depth, l, r)):
# if isEnds(depth, r):
# break
# depth -= 1
# break
# show(struct)
else:
sum = 0
for i in range(l, r + 1):
x = get(struct, i + 1)
# print('x = ' + str(x))
sum += countFib(x)
sum % divider[0]
print(sum)
```
No
| 108,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha has an array of integers a1, a2, ..., an. You have to perform m queries. There might be queries of two types:
1. 1 l r x β increase all integers on the segment from l to r by values x;
2. 2 l r β find <image>, where f(x) is the x-th Fibonacci number. As this number may be large, you only have to find it modulo 109 + 7.
In this problem we define Fibonacci numbers as follows: f(1) = 1, f(2) = 1, f(x) = f(x - 1) + f(x - 2) for all x > 2.
Sasha is a very talented boy and he managed to perform all queries in five seconds. Will you be able to write the program that performs as well as Sasha?
Input
The first line of the input contains two integers n and m (1 β€ n β€ 100 000, 1 β€ m β€ 100 000) β the number of elements in the array and the number of queries respectively.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Then follow m lines with queries descriptions. Each of them contains integers tpi, li, ri and may be xi (1 β€ tpi β€ 2, 1 β€ li β€ ri β€ n, 1 β€ xi β€ 109). Here tpi = 1 corresponds to the queries of the first type and tpi corresponds to the queries of the second type.
It's guaranteed that the input will contains at least one query of the second type.
Output
For each query of the second type print the answer modulo 109 + 7.
Examples
Input
5 4
1 1 2 1 1
2 1 5
1 2 4 2
2 2 4
2 1 5
Output
5
7
9
Note
Initially, array a is equal to 1, 1, 2, 1, 1.
The answer for the first query of the second type is f(1) + f(1) + f(2) + f(1) + f(1) = 1 + 1 + 1 + 1 + 1 = 5.
After the query 1 2 4 2 array a is equal to 1, 3, 4, 3, 1.
The answer for the second query of the second type is f(3) + f(4) + f(3) = 2 + 3 + 2 = 7.
The answer for the third query of the second type is f(1) + f(3) + f(4) + f(3) + f(1) = 1 + 2 + 3 + 2 + 1 = 9.
Submitted Solution:
```
def myround(x):
return int(x) if (x - int(x) == 0) else int(x) + 1
raw = input().split()
n = int(raw[0])
m = int(raw[1])
struct = []
tmpn = n
while (True):
struct.append([0 for j in range(tmpn)])
if tmpn == 1: break
tmpn = myround(tmpn / 2)
raw = input().split()
for i in range(n):
struct[0][i] = int(raw[i])
divider = [1000000007]
def show(struct):
for a in struct:
for x in a:
print(x, end=' ')
print()
def isStarts(depth, l):
return (l % (1 << depth)) == 0
def inBounds(depth, l, r):
# print(depth)
return (1 << depth) <= (r - l + 1)
def isEnds(depth, r):
return ((l + 1) % (1 << depth)) == 0
def add(struct, depth, l, dx):
# print('add')
struct[depth][l // (1 << depth)] += dx
def get(struct, start):
res = 0
for i in range(len(struct)):
res += struct[i][start - 1]
start = myround(start / 2)
# print('start = ' + str(start))
return res
def mypow(i):
if i == 1:
return [[0, 1], [1, 1]]
elif i > 1:
mat = mypow(i // 2)
if i % 2 == 0:
return mult(mat, mat)
else:
return mult(mult(mat, mat), mypow(1))
def mult(mat1, mat2):
return [[(mat1[0][0] * mat2[0][0] + mat1[0][1] * mat2[1][0]) % divider[0],
(mat1[1][0] * mat2[0][0] + mat1[1][1] * mat2[1][0]) % divider[0]],
[(mat1[0][0] * mat2[0][1] + mat1[0][1] * mat2[1][1]) % divider[0],
(mat1[1][0] * mat2[0][1] + mat1[1][1] * mat2[1][1]) % divider[0]]]
def countFib(i):
mat = mypow(i)
if mat != None:
return(mat[0][1] % divider[0])
for i in range(m):
raw = input().split()
l = int(raw[1]) - 1
r = int(raw[2]) - 1
if raw[0] == '1':
dx = int(raw[3])
depth = 0
while l <= r:
while inBounds(depth, l, r):
if isStarts(depth + 1, l):
depth += 1
else:
add(struct, depth, l, dx)
l += (1 << depth)
depth = max(depth - 1, 0)
if inBounds(depth, l, r) and isStarts(depth, l):
add(struct, depth, l, dx)
l += (1 << depth)
else:
depth = 0
# print('l = ' + str(l))
# print('r = ' + str(r))
# while (inBounds(depth, l, r)):
# if isEnds(depth, r):
# break
# depth -= 1
# break
# show(struct)
else:
sum = 0
for i in range(l, r + 1):
x = get(struct, i + 1)
# print('x = ' + str(x))
sum += countFib(x)
sum % divider[0]
print(sum)
```
No
| 108,304 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game!
n racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to n-th (no two racers share the same place) and first m places are awarded. Racer gains bi points for i-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer i is ai points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order.
Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship.
Input
The first line contains number n (1 β€ n β€ 105) β number of racers. Each of the next n lines contains si and ai β nick of the racer (nonempty string, which consist of no more than 20 lowercase Latin letters) and the racer's points (0 β€ ai β€ 106). Racers are given in the arbitrary order.
The next line contains the number m (0 β€ m β€ n). Then m nonnegative integer numbers bi follow. i-th number is equal to amount of points for the i-th awarded place (0 β€ bi β€ 106).
The last line contains Vasya's racer nick.
Output
Output two numbers β the highest and the lowest place Vasya can take up as a result of the championship.
Examples
Input
3
teama 10
teamb 20
teamc 40
2
10 20
teama
Output
2 3
Input
2
teama 10
teamb 10
2
10 10
teamb
Output
2 2
Tags: binary search, greedy, sortings
Correct Solution:
```
class Racer:
def __init__(self, name, points):
self.name = name
self.points = points
def __str__(self):
return '%s %d' % (self.name, self.points)
n = int(input())
best = n * [ None ]
worst = n * [ None ]
for i in range(n):
name, points = input().split()
points = int(points)
best[i] = Racer(name, points)
worst[i] = Racer(name, points)
m = int(input())
place_bonus = list(reversed(sorted(map(int, input().split()))))
your_name = input().strip()
debugging = False
def debug_print(s):
if debugging:
print(s)
def find(racers, name):
for i in range(n):
if racers[i].name == name:
return i
def sort_racers(racers):
racers.sort(key=lambda racer: (-racer.points, racer.name))
# Highest possible ranking.
you = best[find(best, your_name)]
# You get the biggest bonus.
if m != 0:
you.points += place_bonus[0]
sort_racers(best)
# People ahead of you get the next biggest bonuses.
bonus_pos = 1
for i in range(find(best, your_name) - 1, -1, -1):
if bonus_pos >= m:
break
best[i].points += place_bonus[bonus_pos]
bonus_pos += 1
# People at the end get the remaining bonuses.
for i in range(n - 1, -1, -1):
if bonus_pos >= m:
break
best[i].points += place_bonus[bonus_pos]
bonus_pos += 1
sort_racers(best)
debug_print(list(map(str, best)))
best_ranking = find(best, your_name) + 1
debug_print('best ranking: %d' % best_ranking)
# Lowest possible ranking.
you = worst[find(worst, your_name)]
# If you must get a bonus, it's the smallest one.
if m == n:
you.points += place_bonus.pop()
m -= 1
sort_racers(worst)
# Award the smallest possible bonus to the person who can pass you most easily.
bonus_pos = m - 1
worst_pos = find(worst, your_name) + 1
while bonus_pos >= 0 and worst_pos < n:
debug_print('bonus_pos = %d, worst_pos = %d' % (bonus_pos, worst_pos))
candidate = worst[worst_pos]
need = you.points - candidate.points
if candidate.name > you.name:
need += 1
if place_bonus[bonus_pos] >= need:
candidate.points += place_bonus[bonus_pos]
worst_pos += 1
bonus_pos -= 1
sort_racers(worst)
debug_print(list(map(str, worst)))
worst_ranking = find(worst, your_name) + 1
debug_print('worst ranking: %d' % worst_ranking)
print('%d %d' % (best_ranking, worst_ranking))
# Made By Mostafa_Khaled
```
| 108,305 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game!
n racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to n-th (no two racers share the same place) and first m places are awarded. Racer gains bi points for i-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer i is ai points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order.
Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship.
Input
The first line contains number n (1 β€ n β€ 105) β number of racers. Each of the next n lines contains si and ai β nick of the racer (nonempty string, which consist of no more than 20 lowercase Latin letters) and the racer's points (0 β€ ai β€ 106). Racers are given in the arbitrary order.
The next line contains the number m (0 β€ m β€ n). Then m nonnegative integer numbers bi follow. i-th number is equal to amount of points for the i-th awarded place (0 β€ bi β€ 106).
The last line contains Vasya's racer nick.
Output
Output two numbers β the highest and the lowest place Vasya can take up as a result of the championship.
Examples
Input
3
teama 10
teamb 20
teamc 40
2
10 20
teama
Output
2 3
Input
2
teama 10
teamb 10
2
10 10
teamb
Output
2 2
Tags: binary search, greedy, sortings
Correct Solution:
```
class Racer:
def __init__(self, name, points):
self.name = name
self.points = points
def __str__(self):
return '%s %d' % (self.name, self.points)
n = int(input())
best = n * [ None ]
worst = n * [ None ]
for i in range(n):
name, points = input().split()
points = int(points)
best[i] = Racer(name, points)
worst[i] = Racer(name, points)
m = int(input())
place_bonus = list(reversed(sorted(map(int, input().split()))))
your_name = input().strip()
debugging = False
def debug_print(s):
if debugging:
print(s)
def find(racers, name):
for i in range(n):
if racers[i].name == name:
return i
def sort_racers(racers):
racers.sort(key=lambda racer: (-racer.points, racer.name))
#--- Highest possible ranking.
# You get the biggest bonus.
you = best[find(best, your_name)]
if m != 0:
you.points += place_bonus[0]
sort_racers(best)
# People ahead of you get the next biggest bonuses.
bonus_pos = 1
for i in range(find(best, your_name) - 1, -1, -1):
if bonus_pos >= m:
break
best[i].points += place_bonus[bonus_pos]
bonus_pos += 1
# People at the end get the remaining bonuses.
for i in range(n - 1, -1, -1):
if bonus_pos >= m:
break
best[i].points += place_bonus[bonus_pos]
bonus_pos += 1
sort_racers(best)
debug_print(list(map(str, best)))
best_ranking = find(best, your_name) + 1
debug_print('best ranking: %d' % best_ranking)
#--- Lowest possible ranking.
# If you must get a bonus, it's the smallest one.
you = worst[find(worst, your_name)]
if m == n:
you.points += place_bonus.pop()
m -= 1
sort_racers(worst)
# Award the smallest possible bonus to the person who can pass you most easily.
bonus_pos = m - 1
worst_pos = find(worst, your_name) + 1
while bonus_pos >= 0 and worst_pos < n:
debug_print('bonus_pos = %d, worst_pos = %d' % (bonus_pos, worst_pos))
candidate = worst[worst_pos]
need = you.points - candidate.points
if candidate.name > you.name:
need += 1
if place_bonus[bonus_pos] >= need:
candidate.points += place_bonus[bonus_pos]
worst_pos += 1
bonus_pos -= 1
sort_racers(worst)
debug_print(list(map(str, worst)))
worst_ranking = find(worst, your_name) + 1
debug_print('worst ranking: %d' % worst_ranking)
print('%d %d' % (best_ranking, worst_ranking))
```
| 108,306 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game!
n racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to n-th (no two racers share the same place) and first m places are awarded. Racer gains bi points for i-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer i is ai points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order.
Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship.
Input
The first line contains number n (1 β€ n β€ 105) β number of racers. Each of the next n lines contains si and ai β nick of the racer (nonempty string, which consist of no more than 20 lowercase Latin letters) and the racer's points (0 β€ ai β€ 106). Racers are given in the arbitrary order.
The next line contains the number m (0 β€ m β€ n). Then m nonnegative integer numbers bi follow. i-th number is equal to amount of points for the i-th awarded place (0 β€ bi β€ 106).
The last line contains Vasya's racer nick.
Output
Output two numbers β the highest and the lowest place Vasya can take up as a result of the championship.
Examples
Input
3
teama 10
teamb 20
teamc 40
2
10 20
teama
Output
2 3
Input
2
teama 10
teamb 10
2
10 10
teamb
Output
2 2
Tags: binary search, greedy, sortings
Correct Solution:
```
class Racer:
def __init__(self, name, points):
self.name = name
self.points = points
def __str__(self):
return '%s %d' % (self.name, self.points)
n = int(input())
best = n * [ None ]
worst = n * [ None ]
for i in range(n):
name, points = input().split()
points = int(points)
best[i] = Racer(name, points)
worst[i] = Racer(name, points)
m = int(input())
place_bonus = list(reversed(sorted(map(int, input().split()))))
your_name = input().strip()
debugging = False
def debug_print(s):
if debugging:
print(s)
def find(racers, name):
for i in range(n):
if racers[i].name == name:
return i
def sort_racers(racers):
racers.sort(key=lambda racer: (-racer.points, racer.name))
#--- Highest possible ranking.
# You get the biggest bonus.
you = best[find(best, your_name)]
if m != 0:
you.points += place_bonus[0]
sort_racers(best)
# People ahead of you get the next biggest bonuses.
bonus_pos = 1 + find(best, your_name)
# People at the end get the remaining bonuses.
for i in range(n - 1, -1, -1):
if bonus_pos >= m:
break
best[i].points += place_bonus[bonus_pos]
bonus_pos += 1
sort_racers(best)
debug_print(list(map(str, best)))
best_ranking = find(best, your_name) + 1
debug_print('best ranking: %d' % best_ranking)
#--- Lowest possible ranking.
# If you must get a bonus, it's the smallest one.
you = worst[find(worst, your_name)]
if m == n:
you.points += place_bonus.pop()
m -= 1
sort_racers(worst)
# Award the smallest possible bonus to the person who can pass you most easily.
bonus_pos = m - 1
worst_pos = find(worst, your_name) + 1
while bonus_pos >= 0 and worst_pos < n:
debug_print('bonus_pos = %d, worst_pos = %d' % (bonus_pos, worst_pos))
candidate = worst[worst_pos]
need = you.points - candidate.points
if candidate.name > you.name:
need += 1
if place_bonus[bonus_pos] >= need:
candidate.points += place_bonus[bonus_pos]
worst_pos += 1
bonus_pos -= 1
sort_racers(worst)
debug_print(list(map(str, worst)))
worst_ranking = find(worst, your_name) + 1
debug_print('worst ranking: %d' % worst_ranking)
print('%d %d' % (best_ranking, worst_ranking))
```
| 108,307 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game!
n racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to n-th (no two racers share the same place) and first m places are awarded. Racer gains bi points for i-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer i is ai points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order.
Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship.
Input
The first line contains number n (1 β€ n β€ 105) β number of racers. Each of the next n lines contains si and ai β nick of the racer (nonempty string, which consist of no more than 20 lowercase Latin letters) and the racer's points (0 β€ ai β€ 106). Racers are given in the arbitrary order.
The next line contains the number m (0 β€ m β€ n). Then m nonnegative integer numbers bi follow. i-th number is equal to amount of points for the i-th awarded place (0 β€ bi β€ 106).
The last line contains Vasya's racer nick.
Output
Output two numbers β the highest and the lowest place Vasya can take up as a result of the championship.
Examples
Input
3
teama 10
teamb 20
teamc 40
2
10 20
teama
Output
2 3
Input
2
teama 10
teamb 10
2
10 10
teamb
Output
2 2
Tags: binary search, greedy, sortings
Correct Solution:
```
class Racer:
def __init__(self, name, points):
self.name = name
self.points = points
def __str__(self):
return '%s %d' % (self.name, self.points)
n = int(input())
best = n * [ None ]
worst = n * [ None ]
for i in range(n):
name, points = input().split()
points = int(points)
best[i] = Racer(name, points)
worst[i] = Racer(name, points)
m = int(input())
place_bonus = list(reversed(sorted(map(int, input().split()))))
your_name = input().strip()
debugging = False
def debug_print(s):
if debugging:
print(s)
def find(racers, name):
for i in range(n):
if racers[i].name == name:
return i
def sort_racers(racers):
racers.sort(key=lambda racer: (-racer.points, racer.name))
# Highest possible ranking.
you = best[find(best, your_name)]
# You get the biggest bonus.
if m != 0:
you.points += place_bonus[0]
sort_racers(best)
# People ahead of you get the next biggest bonuses.
bonus_pos = 1
for i in range(find(best, your_name) - 1, -1, -1):
if bonus_pos >= m:
break
best[i].points += place_bonus[bonus_pos]
bonus_pos += 1
# People at the end get the remaining bonuses.
for i in range(n - 1, -1, -1):
if bonus_pos >= m:
break
best[i].points += place_bonus[bonus_pos]
bonus_pos += 1
sort_racers(best)
debug_print(list(map(str, best)))
best_ranking = find(best, your_name) + 1
debug_print('best ranking: %d' % best_ranking)
# Lowest possible ranking.
you = worst[find(worst, your_name)]
# If you must get a bonus, it's the smallest one.
if m == n:
you.points += place_bonus.pop()
m -= 1
sort_racers(worst)
# Award the smallest possible bonus to the person who can pass you most easily.
bonus_pos = m - 1
worst_pos = find(worst, your_name) + 1
while bonus_pos >= 0 and worst_pos < n:
debug_print('bonus_pos = %d, worst_pos = %d' % (bonus_pos, worst_pos))
candidate = worst[worst_pos]
need = you.points - candidate.points
if candidate.name > you.name:
need += 1
if place_bonus[bonus_pos] >= need:
candidate.points += place_bonus[bonus_pos]
worst_pos += 1
bonus_pos -= 1
sort_racers(worst)
debug_print(list(map(str, worst)))
worst_ranking = find(worst, your_name) + 1
debug_print('worst ranking: %d' % worst_ranking)
print('%d %d' % (best_ranking, worst_ranking))
```
| 108,308 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two trees (connected undirected acyclic graphs) S and T.
Count the number of subtrees (connected subgraphs) of S that are isomorphic to tree T. Since this number can get quite large, output it modulo 109 + 7.
Two subtrees of tree S are considered different, if there exists a vertex in S that belongs to exactly one of them.
Tree G is called isomorphic to tree H if there exists a bijection f from the set of vertices of G to the set of vertices of H that has the following property: if there is an edge between vertices A and B in tree G, then there must be an edge between vertices f(A) and f(B) in tree H. And vice versa β if there is an edge between vertices A and B in tree H, there must be an edge between f - 1(A) and f - 1(B) in tree G.
Input
The first line contains a single integer |S| (1 β€ |S| β€ 1000) β the number of vertices of tree S.
Next |S| - 1 lines contain two integers ui and vi (1 β€ ui, vi β€ |S|) and describe edges of tree S.
The next line contains a single integer |T| (1 β€ |T| β€ 12) β the number of vertices of tree T.
Next |T| - 1 lines contain two integers xi and yi (1 β€ xi, yi β€ |T|) and describe edges of tree T.
Output
On the first line output a single integer β the answer to the given task modulo 109 + 7.
Examples
Input
5
1 2
2 3
3 4
4 5
3
1 2
2 3
Output
3
Input
3
2 3
3 1
3
1 2
1 3
Output
1
Input
7
1 2
1 3
1 4
1 5
1 6
1 7
4
4 1
4 2
4 3
Output
20
Input
5
1 2
2 3
3 4
4 5
4
4 1
4 2
4 3
Output
0
Submitted Solution:
```
a=int(input())
```
No
| 108,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them.
There are n planets in their universe numbered from 1 to n. Rick is in planet number s (the earth) and he doesn't know where Morty is. As we all know, Rick owns a portal gun. With this gun he can open one-way portal from a planet he is in to any other planet (including that planet). But there are limits on this gun because he's still using its free trial.
<image>
By default he can not open any portal by this gun. There are q plans in the website that sells these guns. Every time you purchase a plan you can only use it once but you can purchase it again if you want to use it more.
Plans on the website have three types:
1. With a plan of this type you can open a portal from planet v to planet u.
2. With a plan of this type you can open a portal from planet v to any planet with index in range [l, r].
3. With a plan of this type you can open a portal from any planet with index in range [l, r] to planet v.
Rick doesn't known where Morty is, but Unity is going to inform him and he wants to be prepared for when he finds and start his journey immediately. So for each planet (including earth itself) he wants to know the minimum amount of money he needs to get from earth to that planet.
Input
The first line of input contains three integers n, q and s (1 β€ n, q β€ 105, 1 β€ s β€ n) β number of planets, number of plans and index of earth respectively.
The next q lines contain the plans. Each line starts with a number t, type of that plan (1 β€ t β€ 3). If t = 1 then it is followed by three integers v, u and w where w is the cost of that plan (1 β€ v, u β€ n, 1 β€ w β€ 109). Otherwise it is followed by four integers v, l, r and w where w is the cost of that plan (1 β€ v β€ n, 1 β€ l β€ r β€ n, 1 β€ w β€ 109).
Output
In the first and only line of output print n integers separated by spaces. i-th of them should be minimum money to get from earth to i-th planet, or - 1 if it's impossible to get to that planet.
Examples
Input
3 5 1
2 3 2 3 17
2 3 2 2 16
2 2 2 3 3
3 3 1 1 12
1 3 3 17
Output
0 28 12
Input
4 3 1
3 4 1 3 12
2 2 3 4 10
1 2 4 16
Output
0 -1 -1 12
Note
In the first sample testcase, Rick can purchase 4th plan once and then 2nd plan in order to get to get to planet number 2.
Submitted Solution:
```
# http://codeforces.com/contest/787/problem/D
from collections import defaultdict
N, Q, s = [int(x) for x in input().split()]
# Planets index from 0 - (n-1)
s -= 1
graph = dict()
for q in range(Q):
# Planets now index from 0 - (n-1)
p = [int(x)-1 for x in input().split()]
if p[0] == 0:
graph.setdefault(p[1], dict())[p[2]] = p[3]+1
elif p[0] == 1:
for x in range(p[2], p[3]+1):
graph.setdefault(p[1], dict())[x] = p[4]+1
elif p[0] == 2:
for x in range(p[2], p[3]+1):
graph.setdefault(x, dict())[p[1]] = p[4]+1
# Setup for dijkstra's.
costs = [float('inf') for n in range(N)]
unvisited = set([n for n in range(N)])
visited = set()
# Initialise
costs[s] = 0
while(len(unvisited) > 0):
current = None
for node in unvisited:
if current is None:
current = node
elif costs[node] < costs[current]:
current = node
if costs[current] == float('inf'):
break
curr_cost = costs[current]
for node, cost in graph.setdefault(current, dict()).items():
if node in unvisited:
costs[node] = min(costs[node], curr_cost + cost)
unvisited.remove(current)
visited.add(current)
print(" ".join([str(c) if c < float('inf') else str(-1) for c in costs]))
```
No
| 108,310 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them.
There are n planets in their universe numbered from 1 to n. Rick is in planet number s (the earth) and he doesn't know where Morty is. As we all know, Rick owns a portal gun. With this gun he can open one-way portal from a planet he is in to any other planet (including that planet). But there are limits on this gun because he's still using its free trial.
<image>
By default he can not open any portal by this gun. There are q plans in the website that sells these guns. Every time you purchase a plan you can only use it once but you can purchase it again if you want to use it more.
Plans on the website have three types:
1. With a plan of this type you can open a portal from planet v to planet u.
2. With a plan of this type you can open a portal from planet v to any planet with index in range [l, r].
3. With a plan of this type you can open a portal from any planet with index in range [l, r] to planet v.
Rick doesn't known where Morty is, but Unity is going to inform him and he wants to be prepared for when he finds and start his journey immediately. So for each planet (including earth itself) he wants to know the minimum amount of money he needs to get from earth to that planet.
Input
The first line of input contains three integers n, q and s (1 β€ n, q β€ 105, 1 β€ s β€ n) β number of planets, number of plans and index of earth respectively.
The next q lines contain the plans. Each line starts with a number t, type of that plan (1 β€ t β€ 3). If t = 1 then it is followed by three integers v, u and w where w is the cost of that plan (1 β€ v, u β€ n, 1 β€ w β€ 109). Otherwise it is followed by four integers v, l, r and w where w is the cost of that plan (1 β€ v β€ n, 1 β€ l β€ r β€ n, 1 β€ w β€ 109).
Output
In the first and only line of output print n integers separated by spaces. i-th of them should be minimum money to get from earth to i-th planet, or - 1 if it's impossible to get to that planet.
Examples
Input
3 5 1
2 3 2 3 17
2 3 2 2 16
2 2 2 3 3
3 3 1 1 12
1 3 3 17
Output
0 28 12
Input
4 3 1
3 4 1 3 12
2 2 3 4 10
1 2 4 16
Output
0 -1 -1 12
Note
In the first sample testcase, Rick can purchase 4th plan once and then 2nd plan in order to get to get to planet number 2.
Submitted Solution:
```
from collections import defaultdict, deque
inf = float("inf")
def distra(i, f, graph):
if i == f:
return 0
pasos = defaultdict(lambda: True)
peso = defaultdict(lambda: inf)
peso[i] = 0
q = deque()
q.append(i)
next = q.popleft
query = q.append
while len(q):
t = next()
pasos[t] = False
for j in graph[t]:
if pasos[j]:
query(j)
peso[j] = min(peso[t] + graph[t][j], peso[j])
if peso[f] is not None:
return peso[f]
else:
return -1
def main():
n, q, s = [int(i) for i in input().split()]
graph = defaultdict(lambda: defaultdict(lambda: inf))
for _ in range(q):
entrada = deque(map(int, input().split()))
getinput = entrada.popleft
t = getinput()
v = getinput()
if t == 1:
u = getinput()
graph[v][u] = min(getinput(), graph[v][u])
elif t == 2:
l = getinput()
r = getinput() + 1
w = getinput()
for i in range(l, r):
graph[v][i] = min(graph[v][i], w)
elif t == 3:
l = getinput()
r = getinput() + 1
w = getinput()
for i in range(l, r):
graph[i][v] = min(graph[i][v], w)
for i in range(1, n + 1):
print(distra(s, i, graph), end=" ")
main()
```
No
| 108,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them.
There are n planets in their universe numbered from 1 to n. Rick is in planet number s (the earth) and he doesn't know where Morty is. As we all know, Rick owns a portal gun. With this gun he can open one-way portal from a planet he is in to any other planet (including that planet). But there are limits on this gun because he's still using its free trial.
<image>
By default he can not open any portal by this gun. There are q plans in the website that sells these guns. Every time you purchase a plan you can only use it once but you can purchase it again if you want to use it more.
Plans on the website have three types:
1. With a plan of this type you can open a portal from planet v to planet u.
2. With a plan of this type you can open a portal from planet v to any planet with index in range [l, r].
3. With a plan of this type you can open a portal from any planet with index in range [l, r] to planet v.
Rick doesn't known where Morty is, but Unity is going to inform him and he wants to be prepared for when he finds and start his journey immediately. So for each planet (including earth itself) he wants to know the minimum amount of money he needs to get from earth to that planet.
Input
The first line of input contains three integers n, q and s (1 β€ n, q β€ 105, 1 β€ s β€ n) β number of planets, number of plans and index of earth respectively.
The next q lines contain the plans. Each line starts with a number t, type of that plan (1 β€ t β€ 3). If t = 1 then it is followed by three integers v, u and w where w is the cost of that plan (1 β€ v, u β€ n, 1 β€ w β€ 109). Otherwise it is followed by four integers v, l, r and w where w is the cost of that plan (1 β€ v β€ n, 1 β€ l β€ r β€ n, 1 β€ w β€ 109).
Output
In the first and only line of output print n integers separated by spaces. i-th of them should be minimum money to get from earth to i-th planet, or - 1 if it's impossible to get to that planet.
Examples
Input
3 5 1
2 3 2 3 17
2 3 2 2 16
2 2 2 3 3
3 3 1 1 12
1 3 3 17
Output
0 28 12
Input
4 3 1
3 4 1 3 12
2 2 3 4 10
1 2 4 16
Output
0 -1 -1 12
Note
In the first sample testcase, Rick can purchase 4th plan once and then 2nd plan in order to get to get to planet number 2.
Submitted Solution:
```
# http://codeforces.com/contest/787/problem/D
N, Q, s = [int(x) for x in input().split()]
graph = dict()
# how to represent graph???
for q in range(Q):
p = [int(x)-1 for x in input().split()]
if p[0] == 0:
graph.setdefault(p[1], dict())[p[2]] = p[3]+1
elif p[0] == 1:
for x in range(p[2], p[3]+1):
graph.setdefault(p[1], dict())[x] = p[4]+1
elif p[0] == 2:
for x in range(p[2], p[3]+1):
graph.setdefault(x, dict())[p[1]] = p[4]+1
# Setup for dijkstra's.
costs = [float('inf') for n in range(N)]
tent_costs = [float('inf') for n in range(N)]
unvisited = set([n for n in range(N)])
visited = set()
# Initialise
costs[s-1] = 0
tent_costs[s-1] = 0
while(len(unvisited) > 0 and min(tent_costs) < float('inf')):
current = tent_costs.index(min(tent_costs))
curr_cost = costs[current]
for node, cost in graph.setdefault(current, dict()).items():
if node in unvisited:
tent_costs[node] = curr_cost + cost
costs[node] = min(costs[node], tent_costs[node])
unvisited.remove(current)
visited.add(current)
tent_costs[current] = float('inf')
print(" ".join([str(c) if c < float('inf') else str(-1) for c in costs]))
```
No
| 108,312 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Rick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them.
There are n planets in their universe numbered from 1 to n. Rick is in planet number s (the earth) and he doesn't know where Morty is. As we all know, Rick owns a portal gun. With this gun he can open one-way portal from a planet he is in to any other planet (including that planet). But there are limits on this gun because he's still using its free trial.
<image>
By default he can not open any portal by this gun. There are q plans in the website that sells these guns. Every time you purchase a plan you can only use it once but you can purchase it again if you want to use it more.
Plans on the website have three types:
1. With a plan of this type you can open a portal from planet v to planet u.
2. With a plan of this type you can open a portal from planet v to any planet with index in range [l, r].
3. With a plan of this type you can open a portal from any planet with index in range [l, r] to planet v.
Rick doesn't known where Morty is, but Unity is going to inform him and he wants to be prepared for when he finds and start his journey immediately. So for each planet (including earth itself) he wants to know the minimum amount of money he needs to get from earth to that planet.
Input
The first line of input contains three integers n, q and s (1 β€ n, q β€ 105, 1 β€ s β€ n) β number of planets, number of plans and index of earth respectively.
The next q lines contain the plans. Each line starts with a number t, type of that plan (1 β€ t β€ 3). If t = 1 then it is followed by three integers v, u and w where w is the cost of that plan (1 β€ v, u β€ n, 1 β€ w β€ 109). Otherwise it is followed by four integers v, l, r and w where w is the cost of that plan (1 β€ v β€ n, 1 β€ l β€ r β€ n, 1 β€ w β€ 109).
Output
In the first and only line of output print n integers separated by spaces. i-th of them should be minimum money to get from earth to i-th planet, or - 1 if it's impossible to get to that planet.
Examples
Input
3 5 1
2 3 2 3 17
2 3 2 2 16
2 2 2 3 3
3 3 1 1 12
1 3 3 17
Output
0 28 12
Input
4 3 1
3 4 1 3 12
2 2 3 4 10
1 2 4 16
Output
0 -1 -1 12
Note
In the first sample testcase, Rick can purchase 4th plan once and then 2nd plan in order to get to get to planet number 2.
Submitted Solution:
```
planets, plans, Earth = map(int, input().split(' '))
class Node():
def __init__(self):
self.mark = float('inf')
self.adjancency = {}
self.notVisited = True
def addPath(self, to_, cost, planNum):
if to_ in self.adjancency:
self.adjancency[to_].append((cost, planNum))
else:
self.adjancency[to_] = [(cost, planNum)]
def pathCost(self, to_):
if to_ not in self.adjancency:
return float('inf')
else:
return self.adjancency[to_][0][0]
graph = ['nullElem']
for i in range(planets):
graph.append(Node())
for i in range(plans):
planType, *params = [int(x) for x in input().split(' ')]
if planType == 1:
v, u, cost = params
if cost < graph[v].pathCost(u):
graph[v].addPath(u, cost, i)
elif planType == 2:
v, l, r, cost = params
for j in range(l, r+1):
if cost < graph[v].pathCost(j):
graph[v].addPath(j, cost, i)
else:
v, l, r, cost = params
for j in range(l, r+1):
if cost < graph[j].pathCost(v):
graph[j].addPath(v, cost, i)
def clearMarks(graph):
for node in range(1, len(graph)):
graph[node].mark = float('inf')
graph[node].notVisited = True
return
def dijkstra(graph, startV, endV):
toQue = [startV]
buiedPlans = []
que = []
graph[startV].mark = 0
while len(toQue):
adj = graph[toQue[0]].adjancency
if len(adj.keys()) > 0:
for adjV in adj.keys():
roadCost = sorted(adj[adjV])[0]
if roadCost[0] + graph[toQue[0]].mark < graph[adjV].mark:
if roadCost[1] in buiedPlans:
graph[adjV].mark = roadCost[0] + graph[toQue[0]].mark
else:
buiedPlans.append(roadCost[1])
graph[adjV].mark = roadCost[0] + graph[toQue[0]].mark
toQue.pop(0)
if graph[adjV].notVisited:
toQue.append(adjV)
graph[adjV].notVisited = False
else:
graph[toQue[0]].notVisited = False
toQue.pop(0)
if graph[endV].mark == float('inf'):
return -1
else:
return graph[endV].mark
costs = []
for i in range(1, planets+1):
if i != Earth:
costs.append(dijkstra(graph, Earth, i))
clearMarks(graph)
else:
costs.append(0)
print(' '.join([str(x) for x in costs]))
```
No
| 108,313 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Tags: implementation
Correct Solution:
```
#!/bin/python3
n = int(input())
if len(str(n)) == 1:
print(1)
else:
c = '{:<0{}d}'.format(1, int(len(str(n))))
c = int(c)
print(((c+n)-(n%c))-n)
```
| 108,314 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Tags: implementation
Correct Solution:
```
x = input()
a = 10**(len(x)-1)
if int(x) < 10:
print(1)
else:
print(((a - int(x[1:]))))
```
| 108,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Tags: implementation
Correct Solution:
```
s=input()
if len(s)==1:print(1)
else:print((10**(len(s)-1))-(int(s[1:])))
```
| 108,316 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Tags: implementation
Correct Solution:
```
n = input()
res = str(int(n[0])+1)
for i in range(0, len(n)-1):
res += '0'
print(int(res)-int(n))
```
| 108,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Tags: implementation
Correct Solution:
```
from fractions import gcd
# from datetime import date, timedelta
from heapq import*
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
# import sys
# sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
# input = sys.stdin.readline
def main():
s = input()
if len(s) == 1:
print(1)
exit()
v = 10 ** (len(s) - 1)
n = int(s[1:])
print(v - n)
if __name__ == '__main__':
main()
```
| 108,318 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Tags: implementation
Correct Solution:
```
from math import *
a=input()
if len(a)==1:
print("1")
exit(0)
elif len(a)-a.count("0")==1:
print(10**a.count("0"))
exit(0)
else:
b=len(a)-1
a=int(a)
c=a/(10**b)
c=ceil(c)
c*=(10**b)
print(c-a)
```
| 108,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Tags: implementation
Correct Solution:
```
n = input()
print(int(str(int(n[0]) + 1) + '0' * (len(n) - 1)) - int(n))
```
| 108,320 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Tags: implementation
Correct Solution:
```
n = input()
num = int(n)
if num < 10:
print(1)
else:
k = (int(n[0]) + 1) * (10 ** (len(n) - 1))
print(k - num)
```
| 108,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Submitted Solution:
```
s = input()
n = int(s)
if n < 10:
print(1)
else:
k = n // 10**(len(s) - 1)
k += 1
k = k * 10**(len(s) - 1)
print(k - n)
```
Yes
| 108,322 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Submitted Solution:
```
N = input()
print((int(N[0])+1)*(10**(len(N)-1))-int(N))
```
Yes
| 108,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Submitted Solution:
```
n = str(input())
if len(n)==1:
print('1')
else:
print(int(str(int(n[0])+1)+'0'*(len(n)-1))-int(n))
```
Yes
| 108,324 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Submitted Solution:
```
n = int(input())
i = 0
if n < 10:
print(1)
else:
s = str(n)
print(int(str(int(s[0]) + 1) + "0" * (len(s) - 1)) - n)
```
Yes
| 108,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Submitted Solution:
```
n=list(input())
if len(n)==1:
print(1)
else:
x="1"
n.pop(0)
x+="0"*len(n)
for i in range(len(n)):
z="".join(n[i])
print(int(x)-int(z))
```
No
| 108,326 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Submitted Solution:
```
n=input()
if len(n)==1:
print(1)
else:
x=int(n[1:])
print((10**len(n)-1)-x)
```
No
| 108,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Submitted Solution:
```
#lucky year:
# no more than 1 non-zero digit
# e.g 100 40000 5
#1000000000
def checkNum(n):
nonzeros = 0
for i in str(n):
if i != "0":
nonzeros += 1
if nonzeros <= 1:
return True
else:
return False
def nextNum(n):
count = n
while not(checkNum(count)):
count += 1
return count - n
print(nextNum(int(input())))
```
No
| 108,328 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
Input
The first line contains integer number n (1 β€ n β€ 109) β current year in Berland.
Output
Output amount of years from the current year to the next lucky one.
Examples
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
Note
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Submitted Solution:
```
current = int(input())
cont = True
counter = 0
while cont:
currentstr = str(current)
currentset = set(currentstr)
if len(currentset) > 2:
counter += 1
current += 1
else:
cont = False
print(counter)
```
No
| 108,329 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Tags: implementation, strings
Correct Solution:
```
l = input()
s = input()
n = int(input())
a = []
for _ in range(n):
c = input()
nl = s
if '*' in nl:
if len(nl) <= len(c):
nl = nl.replace('*', '*'*(abs(len(nl)-len(c))+1))
elif len(nl)==len(c)+1:
nl = nl.replace('*', '')
if len(c)!=len(nl):
a.append("NO")
else:
for i in range(len(c)):
if nl[i] == '*':
if c[i] in l:
a.append("NO")
break
elif nl[i] == '?':
if c[i] not in l:
a.append("NO")
break
else:
if nl[i] != c[i]:
a.append("NO")
break
else:
a.append("YES")
for i in a:
print(i)
```
| 108,330 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Tags: implementation, strings
Correct Solution:
```
a=input()
s=input()
k=int(input())
def qw(c):
t=True
w=-1
if len(s)>len(c)+1: t=False
try:
for j in range(len(s)):
w+=1
if s[j]=='?':
if c[w] not in a: t=False
elif s[j]=='*':
b=len(c)-len(s)+1
for e in c[j:j+b]:
if e in a:
t=False
w+=b-1
else:
if s[j]!=c[w]: t=False
if t==False: break
except IndexError:
return False
return t if len(c)==w+1 else False
for i in range(k):
c=input()
print('YES') if qw(c) else print('NO')
```
| 108,331 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Tags: implementation, strings
Correct Solution:
```
a=input()
s=input()
k=int(input())
def qw(c):
t=True
w=-1
if len(s)>len(c)+1: t=False
try:
for j in range(len(s)):
w+=1
if s[j]=='?':
if c[w] not in a: t=False
elif s[j]=='*':
b=len(c)-len(s)+1
for e in c[j:j+b]:
if e in a:
t=False
w+=b-1
else:
if s[j]!=c[w]: t=False
if t==False: break
except IndexError:
return False
return t if len(c)==w+1 else False
for i in range(k):
c=input()
print('YES') if qw(c) else print('NO')
# Made By Mostafa_Khaled
```
| 108,332 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Tags: implementation, strings
Correct Solution:
```
p=q=[]
g=input()
a=input()
for _ in range(int(input())):
ans=1
x=input()
if len(x)<len(a)-1 or ('*' not in a and len(x)!=len(a)):
ans=0
if ans:
i=0
while i<min(len(a), len(x)) and a[i]!='*':
if a[i]=='?':
if x[i] not in g:
ans=0
break
else:
if a[i]!=x[i]:
ans=0
break
i+=1
j=i
if ans and i<len(a):
i=len(a)-1
z=len(x)-1
while a[i]!='*':
if a[i]=='?':
if x[z] not in g:
ans=0
break
else:
if a[i]!=x[z]:
ans=0
break
i-=1
z-=1
k=z+1
if ans:
for i in range(j, k):
if x[i] in g:
ans=0
break
print(['NO', 'YES'][ans])
```
| 108,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Tags: implementation, strings
Correct Solution:
```
import pdb
good_letters = set(input())
pattern = input()
n = int(input())
def ismatch(pattern, query):
if len(pattern) != len(query):
return False
zipped = zip(pattern, query)
for (a, b) in zipped:
if a.isalpha():
if b != a:
return False
elif a == '?':
if b not in good_letters:
return False
return True
if pattern.find('*') == -1:
for i in range(n):
if ismatch(pattern, input()):
print("YES")
else:
print("NO")
else:
(p1, sep, p2) = pattern.partition('*')
#pdb.set_trace()
for i in range(n):
query = input()
if len(query) < len(pattern) - 1:
print("NO")
else:
s1 = query[:len(p1)]
if len(p2) > 0:
s2 = query[-len(p2):]
mid = set(query[len(p1):-len(p2)])
else:
s2 = ""
mid = set(query[len(p1):])
if ismatch(p1, s1) and ismatch(p2, s2) and mid.isdisjoint(good_letters):
print("YES")
else:
print("NO")
```
| 108,334 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Tags: implementation, strings
Correct Solution:
```
good = set(input().strip())
pattern = input().strip()
n = int(input())
minlen = len(pattern)
is_star = '*' in pattern
if is_star:
minlen -= 1
maxlen = 1000000000
leftlen = pattern.find('*')
rightlen = len(pattern) - leftlen - 1
else:
maxlen = minlen
def check_simple_pattern(task, pattern):
#print(task +" -> " + pattern)
for i in range(len(task)):
if pattern[i] != task[i] and not (pattern[i] == '?' and task[i] in good):
return False
return True
def check(task):
if len(task) < minlen or len(task) > maxlen:
return False
if is_star:
if rightlen == 0:
cond = all([i not in good for i in task[leftlen:]])
else:
cond = all([i not in good for i in task[leftlen:-rightlen]])
return check_simple_pattern(task[:leftlen], pattern[:leftlen]) \
and (rightlen == 0 or check_simple_pattern(task[-rightlen:], pattern[-rightlen:])) \
and cond
else:
return check_simple_pattern(task, pattern)
for i in range(n):
task = input().strip()
if check(task):
print("YES")
else:
print("NO")
```
| 108,335 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Tags: implementation, strings
Correct Solution:
```
goods = input()
query = input().split('*')
l = [len(s) for s in query]
def match(pat, s):
if len(pat) != len(s):
return False
for x, y in zip(pat, s):
if x == '?':
if y not in goods:
return False
else:
if x != y:
return False
return True
for tc in range(int(input())):
s = input()
if len(query) == 1:
left = match(query[0], s)
mid = True
right = True
else:
left = match(query[0], s[:l[0]])
mid = len(s) >= sum(l) and all(c not in goods for c in s[l[0]:len(s) - l[1]])
right = match(query[1], s[len(s) - l[1]:])
print('YES' if left and mid and right else 'NO')
```
| 108,336 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Tags: implementation, strings
Correct Solution:
```
import re
abc = set(list('abcdefghijklmnopqrstuvwxyz'))
good = set(input())
sp = {'?', '*'}
bad = abc - good
ans = []
pat = input()
pl = len(pat)
for _ in range(int(input())):
hasstar = False
answered = False
q = input()
d = len(q) - pl
if d < -1 or (d == -1 and "*" not in pat):
ans.append("NO")
continue
else:
i = 0
j = 0
while i < pl:
if (pat[i] == '?' and q[j] in bad) or (pat[i] not in sp and q[j] != pat[i]):
ans.append("NO")
answered = True
break
elif pat[i] == '*':
hasstar = True
if any(q[k] in good for k in range(j, j+d+1)):
ans.append("NO")
answered = True
break
j += d
i += 1
j += 1
if not answered:
if not hasstar:
if pl == len(q):
ans.append('YES')
answered = True
else:
ans.append('NO')
answered = True
else:
ans.append("YES")
answered = True
print('\n'.join(ans))
```
| 108,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Submitted Solution:
```
good, p, n = input(), input(), int(input())
plen = len(p)
if '*' not in p:
pflag = True
else:
pflag = False
for c in range(n):
s = input()
slen, i, j, flag = len(s), 0, 0, True
if slen < plen:
if pflag:
flag = False
elif slen < plen - 1:
flag = False
while i < plen and flag:
if p[i] == '*':
break
elif p[i] == '?':
if s[j] not in good:
flag = False
else:
if p[i] != s[j]:
flag = False
i += 1
j += 1
if i < plen and flag:
sp = j
i, j = plen-1, slen-1
while i >= 0 and flag:
if p[i] == '*':
break
elif p[i] == '?':
if s[j] not in good:
flag = False
else:
if p[i] != s[j]:
flag = False
i -= 1
j -= 1
while j >= sp and flag:
if s[j] in good:
flag = False
j -= 1
else:
if j < slen:
flag = False
if flag:
print("YES")
else:
print("NO")
```
Yes
| 108,338 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Submitted Solution:
```
a = [0] * 26
s = str(input())
for c in s:
a[ord(c) - 97] = 1
t = str(input())
n = len(t)
idx = n
for j, c in enumerate(t):
if c == '*':
idx = j
break
q = int(input())
for i in range(q):
p = str(input())
m = len(p)
l, r = 0, 0
possible = True
if idx == n:
if n != m:
possible = False
else:
for j in range(n):
if t[j] == '?':
if not a[ord(p[j]) - 97]:
possible = False
break
else:
if t[j] != p[j]:
possible = False
break
if possible:
print('YES')
else:
print('NO')
else:
while t[l] != '*':
if l == m:
possible = False
break
if t[l] == '?':
if not a[ord(p[l]) - 97]:
possible = False
break
else:
if t[l] != p[l]:
possible = False
break
l += 1
while t[n - r - 1] != '*':
if r == m:
possible = False
break
if t[n - r - 1] == '?':
if not a[ord(p[m - r - 1]) - 97]:
possible = False
break
else:
if t[n - r - 1] != p[m - r - 1]:
possible = False
break
r += 1
for j in range(l, l + m - r - l):
if a[ord(p[j]) - 97]:
possible = False
break
if l + r > m:
possible = False
if possible:
print('YES')
else:
print('NO')
```
Yes
| 108,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Submitted Solution:
```
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
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")
#-------------------game starts now----------------------------------------------------
s=input()
ls=[0 for i in range(26)]
for i in range(len(s)):
ls[ord(s[i])-97]=1
s=input()
n=int(input())
while n:
q=input()
if(len(q)<len(s)-1):print("NO")
elif('*' not in s):
if(len(s)!=len(q)):print("NO")
else:
flag=True
for j in range(len(s)):
if(s[j]!=q[j]):
if(s[j]=='?'):
if(ls[ord(q[j])-97]!=1):
flag=False
break
else:
flag=False
break
if(flag):print("YES")
else:print("NO")
else:
flag=True
i=s.index('*')
for j in range(i):
if(s[j]!=q[j]):
if(s[j]=='?'):
if(ls[ord(q[j])-97]!=1):
flag=False
break
else:
flag=False
break
for j in range(i,len(q)-(len(s)-i-1)):
if(ls[ord(q[j])-97]!=0):
flag=False
break
k=len(q)-(len(s)-i-1)
for j in range(i+1,len(s)):
if(s[j]!=q[k]):
if(s[j]=='?'):
if(ls[ord(q[k])-97]!=1):
flag=False
break
else:
flag=False
break
k+=1
if(flag):print("YES")
else:print("NO")
n-=1
```
Yes
| 108,340 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Submitted Solution:
```
all_letters = {chr(i) for i in range(97, 97 + 26)}
good_letters = {letter for letter in input()}
bad_letters = all_letters - good_letters
pattern = input()
n = int(input())
star_index = pattern.find('*')
def check(s, m_pattern):
for i in range(len(s)):
if m_pattern[i] == '$':
if s[i] not in bad_letters:
return False
elif m_pattern[i] == '?':
if s[i] not in good_letters:
return False
else:
if m_pattern[i] != s[i]:
return False
return True
def match(s):
if len(s) < len(pattern) - 1:
return False
else:
if len(s) == len(pattern) - 1:
if star_index == -1:
return False
else:
return check(s, pattern[:star_index] + pattern[star_index + 1:])
else:
m_pattern = ''
if star_index == -1:
if len(s) > len(pattern):
return False
else:
m_pattern = pattern[:]
else:
m_pattern += pattern[:star_index]
m_sec_pattern = pattern[:star_index]
for i in range(len(s) - len(pattern) + 1):
m_pattern += '$'
m_pattern += pattern[star_index + 1:]
return check(s, m_pattern)
for i in range(n):
qs = input()
print('YES' if match(qs) else 'NO')
```
Yes
| 108,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Submitted Solution:
```
good = input()
sh = input()
pr = int(input())
ind = -1
if '*' in sh:
ind = sh.index('*')
for i in range(pr):
t = input()
res = "NO"
for j in range(len(sh)):
if len(t) < len(sh):
t = t[:ind] + ' ' + t[ind:]
elif len(t) > len(sh):
res = "NO"
break
if t[j] == sh[j]:
res = "YES"
elif sh[j] == '?':
if t[j] in good:
res = "YES"
else:
res = "NO"
break
elif sh[j] == '*':
if t[j] not in good:
res = "YES"
else:
res = "NO"
print(res)
```
No
| 108,342 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Submitted Solution:
```
lower = "azertyuiopqsdfghjklmwxcvbn"
alphabet = input()
pattern_str = input()
n = int(input())
for i in range(n):
line = list(input())
pattern = list(pattern_str)
result = "NO"
while len(line) > 0 and len(pattern) > 0:
if line[0] not in lower:
break
if line[0] == pattern[0]:
line.pop(0)
pattern.pop(0)
continue
if line[0] in alphabet:
if pattern[0] == "?":
line.pop(0)
pattern.pop(0)
elif pattern[0] == "*":
pattern.pop(0)
else:
break
else:
if pattern[0] == "*":
line.pop(0)
else:
break
if len(line) + len(pattern) == 0 or (len(pattern) == 1 and pattern[0] == "*"):
result = "YES"
print(result)
```
No
| 108,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Submitted Solution:
```
l=['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']
s1=input().strip()
s1=list(s1)
s2=[]
for i in l:
if i not in s1:
s2.append(i)
pattern=input().strip()
pattern=list(pattern)
if ("*" not in pattern):
length_main=len(pattern)
n=int(input().strip())
for i in range(n):
f=0
string=input().strip()
length=len(string)
if (length_main==length):
for j in range(length_main):
if (string[j]!=pattern[j]):
if (pattern[j]!="?"):
print ('NO')
f=1
break
else:
if (string[j] not in s1):
print ('NO')
f=1
break
else:
print ('NO')
if (f==0):
print ('YES')
else:
ind=pattern.index("*")
length_main=len(pattern)
n=int(input().strip())
for i in range(n):
string=input().strip()
length=len(string)
if (length<length_main-1):
print ('NO')
else:
f=0
for j in range(ind):
if (string[j]!=pattern[j]):
if (pattern[j]!="?"):
print ('NO')
f=1
break
else:
if (string[j] not in s1):
print ('NO')
f=1
break
if (f!=1):
q=length_main-length
for j in range(length_main-1,ind,-1):
if (string[j-q]!=pattern[j]):
if (pattern[j]!="?"):
print ('NO')
f=1
break
else:
if (string[j-q] not in s1):
print ('NO')
f=1
break
if (f!=1):
save= ind+1-q
string=list(string)
x=string[ind:save]
for j in x:
if (j not in s2):
print ('NO')
f=1
break
if (f==0):
print ('YES')
```
No
| 108,344 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..
There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.
Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.
Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.
A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.
The good letters are given to Petya. All the others are bad.
Input
The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.
The second line contains the pattern β a string s of lowercase English letters, characters "?" and "*" (1 β€ |s| β€ 105). It is guaranteed that character "*" occurs in s no more than once.
The third line contains integer n (1 β€ n β€ 105) β the number of query strings.
n lines follow, each of them contains single non-empty string consisting of lowercase English letters β a query string.
It is guaranteed that the total length of all query strings is not greater than 105.
Output
Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
ab
a?a
2
aaa
aab
Output
YES
NO
Input
abc
a?a?a*
4
abacaba
abaca
apapa
aaaaax
Output
NO
YES
NO
YES
Note
In the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.
Explanation of the second example.
* The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.
* The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.
* The third query: "NO", because characters "?" can't be replaced with bad letters.
* The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Submitted Solution:
```
def do(cur)->str:
i=j=0
while i<len(pt) and j<len(cur):
if pt[i]=="?":
if cur[j] not in good:return"NO"
elif pt[i]=="*":
while j<len(cur) and cur[j] not in good:j+=1
if j==len(cur):
if i==len(pt)-1:break
return"NO"
elif i==len(pt)-1:return "NO"
i+=1;continue
else:
if pt[i]!=cur[j]:return"NO"
i+=1;j+=1
return "YES" if j==len(cur) and i==len(pt) else "NO"
good=set(input())
pt=input()
for _ in range(int(input())):
cur=input()
print(do(cur))
```
No
| 108,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This story is happening in a town named BubbleLand. There are n houses in BubbleLand. In each of these n houses lives a boy or a girl. People there really love numbers and everyone has their favorite number f. That means that the boy or girl that lives in the i-th house has favorite number equal to fi.
The houses are numerated with numbers 1 to n.
The houses are connected with n - 1 bidirectional roads and you can travel from any house to any other house in the town. There is exactly one path between every pair of houses.
A new dating had agency opened their offices in this mysterious town and the citizens were very excited. They immediately sent q questions to the agency and each question was of the following format:
* a b β asking how many ways are there to choose a couple (boy and girl) that have the same favorite number and live in one of the houses on the unique path from house a to house b.
Help the dating agency to answer the questions and grow their business.
Input
The first line contains an integer n (1 β€ n β€ 105), the number of houses in the town.
The second line contains n integers, where the i-th number is 1 if a boy lives in the i-th house or 0 if a girl lives in i-th house.
The third line contains n integers, where the i-th number represents the favorite number fi (1 β€ fi β€ 109) of the girl or boy that lives in the i-th house.
The next n - 1 lines contain information about the roads and the i-th line contains two integers ai and bi (1 β€ ai, bi β€ n) which means that there exists road between those two houses. It is guaranteed that it's possible to reach any house from any other.
The following line contains an integer q (1 β€ q β€ 105), the number of queries.
Each of the following q lines represents a question and consists of two integers a and b (1 β€ a, b β€ n).
Output
For each of the q questions output a single number, the answer to the citizens question.
Example
Input
7
1 0 0 1 0 1 0
9 2 9 2 2 9 9
2 6
1 2
4 2
6 5
3 6
7 4
2
1 3
7 5
Output
2
3
Note
In the first question from house 1 to house 3, the potential couples are (1, 3) and (6, 3).
In the second question from house 7 to house 5, the potential couples are (7, 6), (4, 2) and (4, 5).
Submitted Solution:
```
from collections import namedtuple
import sys
Route = namedtuple('Route', ['A', 'B'])
class Gender():
BOY = 1
GIRL = 2
class Person():
def __init__(self, gender, favorite_number):
self.gender = gender
self.favorite_number = favorite_number
def get_path(start, end, path, routes):
next_routes = iter(route for route in routes if route not in path and (route.A == start or route.B == start))
if not next_routes:
return path
len_of_path = len(path)
for next_route in next_routes:
path = path[:len_of_path] + [next_route]
if path[-1].A != end and path[-1].B != end:
path = get_path(next_route.B if next_route.A == start else next_route.A, end, path, routes)
if path[-1].A == end or path[-1].B == end:
break
return path
def get_love(persons):
for i, first_person in enumerate(persons):
for second_person in persons[i + 1:]:
if first_person.gender != second_person.gender and first_person.favorite_number == second_person.favorite_number:
yield (first_person, second_person)
def get_answer(question, routes, persons):
path = get_path(question[0], question[1], list(), routes)
persons_on_way = list(set(persons[i - 1] for route in path for i in [route.A, route.B]))
number_of_love = 0
for love in get_love(persons_on_way):
number_of_love += 1
return number_of_love
def main():
persons = []
routes = []
genders = None
number_of_questions = None
line_num = 0
n = None
questions = []
# file = open('input.txt')
for line in sys.stdin.readlines():
# for line in file.readlines():
line_num += 1
if line_num == 1:
n = int(line)
elif line_num == 2:
genders = [number for number in line.split(' ')]
elif line_num == 3:
persons = [Person(genders[i], int(favorite_number)) for i, favorite_number in enumerate(line.split(' '))]
elif line_num < n + 3:
a, b = map(int, line.split(' '))
if a > b:
b, a = a, b
routes.append(Route(a, b))
elif line_num == n + 3:
number_of_questions = int(line)
else:
a, b = map(int, line.split(' '))
questions.append((a, b))
for question in questions:
answer = get_answer(question, routes, persons)
print(answer)
if __name__ == '__main__':
main()
```
No
| 108,346 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Tags: data structures, dfs and similar, graphs, shortest paths
Correct Solution:
```
from sys import *
f = lambda: map(int, input().split())
n, m, k = f()
t = [[1e9 * (q == '.') for q in stdin.readline()] for i in range(n)]
t.append([0] * m)
a, b, c, d = [q - 1 for q in f()]
u = [(a, b)]
t[a][b] = l = 0
def g(i, x, y):
if i > k or t[x][y] < l: return 0
if t[x][y] > l:
t[x][y] = l
v.append((x, y))
return 1
while u and t[c][d] == 1e9:
l += 1
v = []
for x, y in u:
i = j = 1
while g(i, x - i, y): i += 1
while g(j, x + j, y): j += 1
i = j = 1
while g(i, x, y - i): i += 1
while g(j, x, y + j): j += 1
u = v
print(l if t[c][d] < 1e9 else -1)
```
| 108,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Tags: data structures, dfs and similar, graphs, shortest paths
Correct Solution:
```
# aadiupadhyay
import os.path
from math import gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')
def st(): return list(sys.stdin.readline().strip())
def li(): return list(map(int, sys.stdin.readline().split()))
def mp(): return map(int, sys.stdin.readline().split())
def inp(): return int(sys.stdin.readline())
def pr(n): return sys.stdout.write(str(n)+"\n")
def prl(n): return sys.stdout.write(str(n)+" ")
if os.path.exists('input.txt'):
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]
n, m, k = mp()
l = []
now = [INF for i in range(m)]
distance = []
for i in range(n):
cur = list(now)
s = st()
l.append(s)
distance.append(cur)
a, b, c, d = mp()
a, b, c, d = a-1, b-1, c-1, d-1
q = deque()
q.append((a, b))
distance[a][b] = 0
ans = -1
while q:
x, y = q.popleft()
if (x, y) == (c, d):
ans = distance[x][y]
break
for i in range(4):
for j in range(1, k+1):
x1, x2 = x+j*dx[i], y+j*dy[i]
if x1 < 0 or x2 < 0 or x1 >= n or x2 >= m or l[x1][x2] == '#' or distance[x1][x2] < 1+distance[x][y]:
break
else:
if distance[x1][x2] > 1 + distance[x][y]:
distance[x1][x2] = 1+distance[x][y]
q.append((x1, x2))
pr(ans)
```
| 108,348 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Tags: data structures, dfs and similar, graphs, shortest paths
Correct Solution:
```
import sys
import io, os
input = sys.stdin.readline
INF = 10**18
def main():
h, w, k = map(int, input().split())
C = [input().rstrip() for i in range(h)]
x1, y1, x2, y2 = map(int, input().split())
x1, y1, x2, y2 = x1-1, y1-1, x2-1, y2-1
#print(C)
from collections import deque
q = deque()
q.append((x1, y1))
dist = [[INF]*w for i in range(h)]
dist[x1][y1] = 0
while q:
x, y = q.popleft()
if x == x2 and y == y2:
print(dist[x][y])
exit()
for dx, dy in (0, 1), (1, 0), (0, -1), (-1, 0):
for i in range(1, k+1):
nx, ny = x+dx*i, y+dy*i
if nx < 0 or h <= nx:
break
if ny < 0 or w <= ny:
break
if C[nx][ny] == '#':
break
if dist[nx][ny] <= dist[x][y]:
break
if dist[nx][ny] == dist[x][y]+1:
continue
dist[nx][ny] = dist[x][y]+1
q.append((nx, ny))
#print(dist)
print(-1)
if __name__ == '__main__':
main()
```
| 108,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Tags: data structures, dfs and similar, graphs, shortest paths
Correct Solution:
```
from sys import *
f = lambda: map(int, input().split())
n, m, k = f()
t = [[1e9 * (q == '.') for q in stdin.readline()] for i in range(n)]
t.append([0] * m)
a, b, c, d = [q - 1 for q in f()]
u = [(a, b)]
t[a][b] = l = 0
def g(x, y):
if t[x][y] > l:
t[x][y] = l
v.append((x, y))
while u and t[c][d] == 1e9:
l += 1
v = []
for x, y in u:
i = 1
while i <= k and t[x - i][y] >= l:
g(x - i, y)
i += 1
i = 1
while i <= k and t[x + i][y] >= l:
g(x + i, y)
i += 1
j = 1
while j <= k and t[x][y - j] >= l:
g(x, y - j)
j += 1
j = 1
while j <= k and t[x][y + j] >= l:
g(x, y + j)
j += 1
u = v
print(l if t[c][d] < 1e9 else -1)
```
| 108,350 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Tags: data structures, dfs and similar, graphs, shortest paths
Correct Solution:
```
# ------------------- fast io --------------------
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")
# ------------------- fast io --------------------
from math import ceil
def prod(a, mod=10 ** 9 + 7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
from math import inf
from collections import deque
for _ in range(int(input()) if not True else 1):
#n = int(input())
n, m, k = map(int, input().split())
# a, b = map(int, input().split())
# c, d = map(int, input().split())
# a = list(map(int, input().split()))
# b = list(map(int, input().split()))
a = []
for i in range(n):
a += [input()]
x1, y1, x2, y2 = map(int, input().split())
x1, y1 = x1-1, y1-1
x2, y2 = x2-1, y2-1
queue = deque([(x1, y1)])
dist = [[inf] * m for i in range(n)]
dist[x1][y1] = 0
while queue:
x, y = queue.popleft()
for i in range(x+1, x + k + 1):
if i >= n or dist[i][y] <= dist[x][y] or a[i][y]=='#': break
if dist[i][y] == inf:
queue += [(i, y)]
dist[i][y] = dist[x][y] + 1
for i in range(x - 1, x - k - 1, -1):
if i < 0 or dist[i][y] <= dist[x][y] or a[i][y]=='#': break
if dist[i][y] == inf:
queue += [(i, y)]
dist[i][y] = dist[x][y] + 1
for j in range(y + 1, y + k + 1):
if j >= m or dist[x][j] <= dist[x][y] or a[x][j]=='#': break
if dist[x][j] == inf:
queue += [(x, j)]
dist[x][j] = dist[x][y] + 1
for j in range(y - 1, y - k - 1, -1):
if j < 0 or dist[x][j] <= dist[x][y] or a[x][j]=='#': break
if dist[x][j] == inf:
queue += [(x, j)]
dist[x][j] = dist[x][y] + 1
print(-1 if dist[x2][y2] == inf else dist[x2][y2])
```
| 108,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Tags: data structures, dfs and similar, graphs, shortest paths
Correct Solution:
```
import sys
from collections import deque
input=sys.stdin.readline
n,m,k=map(int,input().split())
grid=[]
grid1=[]
grid2=[]
leftyes=[]
rightyes=[]
upyes=[]
downyes=[]
for i in range(n):
grid.append(input())
grid1.append([-1]*m)
grid2.append([0]*m)
leftyes.append([0]*m)
rightyes.append([0]*m)
downyes.append([0]*m)
upyes.append([0]*m)
for i in range(n):
count=0
for j in range(m):
if grid[i][j]=='.':
count+=1
else:
count=0
if count>k:
leftyes[i][j]=1
rightyes[i][j-k]=1
for i in range(m):
count=0
for j in range(n):
if grid[j][i]=='.':
count+=1
else:
count=0
if count>k:
upyes[j][i]=1
downyes[j-k][i]=1
x1,y1,x2,y2=map(int,input().split())
que=deque([(x1-1,y1-1,0)])
grid1[x1-1][y1-1]=0
while que:
x,y,step=que.popleft()
if grid2[x][y]:
continue
grid2[x][y]=1
if not(x<n-1 and grid1[x+1][y]!=-1 and grid1[x+1][y]<=step):
curr=x-1
count=0
while count<k and curr>=0 and grid[curr][y]=='.':
if grid1[curr][y]!=-1:
curr-=1
count+=1
continue
que.append((curr,y,step+1))
grid1[curr][y]=step+1
curr-=1
count+=1
else:
if upyes[x][y] and grid1[x-k][y]==-1:
que.append((x-k,y,step+1))
grid1[x-k][y]=step+1
if not(x>0 and grid1[x-1][y]!=-1 and grid1[x-1][y]<=step):
curr=x+1
count=0
while count<k and curr<=n-1 and grid[curr][y]=='.':
if grid1[curr][y]!=-1:
curr+=1
count+=1
continue
que.append((curr,y,step+1))
grid1[curr][y]=step+1
curr+=1
count+=1
else:
if downyes[x][y] and grid1[x+k][y]==-1:
que.append((x+k,y,step+1))
grid1[x+k][y]=step+1
if not(y<m-1 and grid1[x][y+1]!=-1 and grid1[x][y+1]<=step):
curr=y-1
count=0
while count<k and curr>=0 and grid[x][curr]=='.':
if grid1[x][curr]!=-1:
curr-=1
count+=1
continue
que.append((x,curr,step+1))
grid1[x][curr]=step+1
curr-=1
count+=1
else:
if leftyes[x][y] and grid1[x][y-k]==-1:
que.append((x,y-k,step+1))
grid1[x][y-k]=step+1
if not(y>0 and grid1[x][y-1]!=-1 and grid1[x][y-1]<=step):
curr=y+1
count=0
while count<k and curr<=m-1 and grid[x][curr]=='.':
if grid1[x][curr]!=-1:
curr+=1
count+=1
continue
que.append((x,curr,step+1))
grid1[x][curr]=step+1
curr+=1
count+=1
else:
if rightyes[x][y] and grid1[x][y+k]==-1:
que.append((x,y+k,step+1))
grid1[x][y+k]=step+1
print(grid1[x2-1][y2-1])
```
| 108,352 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Tags: data structures, dfs and similar, graphs, shortest paths
Correct Solution:
```
from collections import deque
n, m, k = map(int, input().split())
INF = float("inf")
d = [[INF] * m for _ in range(n)]
t = [[] for i in range(n)]
for i in range(n):
a = list(input())
t[i] = a
sx, sy, gx, gy = map(int, input().split())
sx, sy, gx, gy = sx - 1, sy - 1, gx - 1, gy - 1
def bfs():
que = deque()
que.append((sx, sy))
d[sx][sy] = 0
while len(que):
x, y = que.popleft()
if x == gx and y == gy:
break
for dx, dy in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
for i in range(1, k + 1):
nx, ny = x + i * dx, y + i * dy
if not 0 <= nx < n or not 0 <= ny < m or t[nx][ny] != "." or d[nx][ny] <= d[x][y]:
break
else:
if d[nx][ny] > d[x][y] + 1:
d[nx][ny] = d[x][y] + 1
que.append((nx, ny))
return d[gx][gy]
ans = bfs()
if ans == INF:
print(-1)
else:
print(ans)
```
| 108,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Tags: data structures, dfs and similar, graphs, shortest paths
Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n,m,k = LI()
a = [[-1] * (m+2)]
a += [[-1] + [inf if c=='.' else -1 for c in S()] + [-1] for _ in range(n)]
a += [[-1] * (m+2)]
x1,y1,x2,y2 = LI()
a[x1][y1] = 0
q = [(x1,y1)]
qi = 0
dy = [-1,1,0,0]
dx = [0,0,-1,1]
while qi < len(q):
x,y = q[qi]
qi += 1
nd = a[x][y] + 1
for di in range(4):
for j in range(1,k+1):
ny = y + dy[di] * j
nx = x + dx[di] * j
if a[nx][ny] > nd:
if ny == y2 and nx == x2:
return nd
a[nx][ny] = nd
q.append((nx,ny))
elif a[nx][ny] < nd:
break
if a[x2][y2] < inf:
return a[x2][y2]
return -1
print(main())
```
| 108,354 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Submitted Solution:
```
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
from collections import deque
n,m,k=map(int,input().split())
dp=[[float("infinity") for i in range(m)] for i in range(n)]
l=[]
for i in range(n):
l.append(list(input()))
x1,y1,x2,y2=map(lambda a:int(a)-1,input().split())
t=[(1,0),(0,1),(0,-1),(-1,0)]
q=deque()
q.append((x1,y1))
dp[x1][y1]=0
while q:
x,y=q.popleft()
if x==x2 and y==y2:
# print(90)
break
for a,b in t:
for i in range(1,k+1):
e=x+i*a
f=y+i*b
if e<0 or e>=n or f>=m or f<0 or l[e][f]!="." or dp[e][f]<dp[x][y]+1:
# print(e,f)
break
else:
if dp[e][f]>dp[x][y]+1:
dp[e][f]=dp[x][y]+1
q.append((e,f))
# print(q)
ans=dp[x2][y2]
if ans==float("infinity"):
ans=-1
print(ans)
```
Yes
| 108,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Submitted Solution:
```
# aadiupadhyay
import os.path
# testing extension
from math import gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')
def st(): return list(sys.stdin.readline().strip())
def li(): return list(map(int, sys.stdin.readline().split()))
def mp(): return map(int, sys.stdin.readline().split())
def inp(): return int(sys.stdin.readline())
def pr(n): return sys.stdout.write(str(n)+"\n")
def prl(n): return sys.stdout.write(str(n)+" ")
if os.path.exists('input.txt'):
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]
n, m, k = mp()
l = []
now = [INF for i in range(m)]
distance = []
for i in range(n):
cur = list(now)
s = st()
l.append(s)
distance.append(cur)
a, b, c, d = mp()
a, b, c, d = a-1, b-1, c-1, d-1
q = deque()
q.append((a, b))
distance[a][b] = 0
ans = -1
while q:
x, y = q.popleft()
if (x, y) == (c, d):
ans = distance[x][y]
break
for i in range(4):
for j in range(1, k+1):
x1, x2 = x+j*dx[i], y+j*dy[i]
if x1 < 0 or x2 < 0 or x1 >= n or x2 >= m or l[x1][x2] == '#' or distance[x1][x2] < 1+distance[x][y]:
break
else:
if distance[x1][x2] > 1 + distance[x][y]:
distance[x1][x2] = 1+distance[x][y]
q.append((x1, x2))
pr(ans)
```
Yes
| 108,356 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Submitted Solution:
```
import sys
from collections import deque
input=sys.stdin.readline
n,m,k=map(int,input().split())
grid=[]
grid1=[]
grid2=[]
leftyes=[]
rightyes=[]
upyes=[]
downyes=[]
for i in range(n):
grid.append(input())
grid1.append([-1]*m)
grid2.append([0]*m)
leftyes.append([0]*m)
rightyes.append([0]*m)
downyes.append([0]*m)
upyes.append([0]*m)
for i in range(n):
count=0
for j in range(m):
if grid[i][j]=='.':
count+=1
else:
count=0
if count>k:
leftyes[i][j]=1
rightyes[i][j-k]=1
for i in range(m):
count=0
for j in range(n):
if grid[j][i]=='.':
count+=1
else:
count=0
if count>k:
upyes[j][i]=1
downyes[j-k][i]=1
x1,y1,x2,y2=map(int,input().split())
que=deque([(x1-1,y1-1,0)])
grid1[x1-1][y1-1]=0
while que:
x,y,step=que.popleft()
if grid2[x][y]:
continue
grid2[x][y]=1
if not(x<n-1 and grid1[x+1][y]!=-1):
curr=x-1
count=0
while count<k and curr>=0 and grid[curr][y]=='.' and grid1[curr][y]==-1:
que.append((curr,y,step+1))
grid1[curr][y]=step+1
curr-=1
count+=1
else:
if upyes[x][y] and grid1[x-k][y]==-1:
que.append((x-k,y,step+1))
grid1[x-k][y]=step+1
if not(x>0 and grid1[x-1][y]!=-1):
curr=x+1
count=0
while count<k and curr<=n-1 and grid[curr][y]=='.' and grid1[curr][y]==-1:
que.append((curr,y,step+1))
grid1[curr][y]=step+1
curr+=1
count+=1
else:
if downyes[x][y] and grid1[x+k][y]==-1:
que.append((x+k,y,step+1))
grid1[x+k][y]=step+1
if not(y<m-1 and grid1[x][y+1]!=-1):
curr=y-1
count=0
while count<k and curr>=0 and grid[x][curr]=='.' and grid1[x][curr]==-1:
que.append((x,curr,step+1))
grid1[x][curr]=step+1
curr-=1
count+=1
else:
if leftyes[x][y] and grid1[x][y-k]==-1:
que.append((x,y-k,step+1))
grid1[x][y-k]=step+1
if not(y>0 and grid1[x][y-1]!=-1):
curr=y+1
count=0
while count<k and curr<=m-1 and grid[x][curr]=='.' and grid1[x][curr]==-1:
que.append((x,curr,step+1))
grid1[x][curr]=step+1
curr+=1
count+=1
else:
if rightyes[x][y] and grid1[x][y+k]==-1:
que.append((x,y+k,step+1))
grid1[x][y+k]=step+1
print(grid1[x2-1][y2-1])
```
No
| 108,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Submitted Solution:
```
import sys
from collections import deque
input=sys.stdin.readline
n,m,k=map(int,input().split())
grid=[]
grid1=[]
grid2=[]
leftyes=[]
rightyes=[]
upyes=[]
downyes=[]
for i in range(n):
grid.append(input())
grid1.append([-1]*m)
grid2.append([0]*m)
leftyes.append([0]*m)
rightyes.append([0]*m)
downyes.append([0]*m)
upyes.append([0]*m)
for i in range(n):
count=0
for j in range(m):
if grid[i][j]=='.':
count+=1
else:
count=0
if count>k:
leftyes[i][j]=1
rightyes[i][j-k]=1
for i in range(m):
count=0
for j in range(n):
if grid[j][i]=='.':
count+=1
else:
count=0
if count>k:
upyes[j][i]=1
downyes[j-k][i]=1
x1,y1,x2,y2=map(int,input().split())
que=deque([(x1-1,y1-1,0)])
grid1[x1-1][y1-1]=0
while que:
x,y,step=que.popleft()
if grid2[x][y]:
continue
grid2[x][y]=1
if not(x<n-1 and grid1[x+1][y]!=-1):
curr=x-1
count=0
while count<k and curr>=0 and grid[curr][y]=='.' and grid1[curr][y]==-1:
que.append((curr,y,step+1))
grid1[curr][y]=step+1
curr-=1
count+=1
else:
if upyes[x][y]:
que.append((x-k,y,step+1))
grid1[x-k][y]=step+1
if not(x>0 and grid1[x-1][y]!=-1):
curr=x+1
count=0
while count<k and curr<=n-1 and grid[curr][y]=='.' and grid1[curr][y]==-1:
que.append((curr,y,step+1))
grid1[curr][y]=step+1
curr+=1
count+=1
else:
if downyes[x][y]:
que.append((x+k,y,step+1))
grid1[x+k][y]=step+1
if not(y<m-1 and grid1[x][y+1]!=-1):
curr=y-1
count=0
while count<k and curr>=0 and grid[x][curr]=='.' and grid1[x][curr]==-1:
que.append((x,curr,step+1))
grid1[x][curr]=step+1
curr-=1
count+=1
else:
if leftyes[x][y]:
que.append((x,y-k,step+1))
grid1[x][y-k]=step+1
if not(y>0 and grid1[x][y-1]!=-1):
curr=y+1
count=0
while count<k and curr<=m-1 and grid[x][curr]=='.' and grid1[x][curr]==-1:
que.append((x,curr,step+1))
grid1[x][curr]=step+1
curr+=1
count+=1
else:
if rightyes[x][y]:
que.append((x,y+k,step+1))
grid1[x][y+k]=step+1
print(grid1[x2-1][y2-1])
```
No
| 108,358 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Submitted Solution:
```
from collections import deque
n, m, k = map(int, input().split())
INF = float("inf")
d = [[INF] * (m + 1) for _ in range(n + 1)]
t = [[] for i in range(n + 1)]
for i in range(n):
a = list("#" + input())
t[i + 1] = a
sx, sy, gx, gy = map(int, input().split())
def bfs():
px, py, cnt = 0, 0, 1
que = deque()
que.append((sx, sy, px, py, cnt))
d[sx][sy] = 0
while len(que):
x, y, px, py, cnt = que.popleft()
if x == gx and y == gy:
break
for dx, dy in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
nx, ny = x + dx, y + dy
if 0 < nx <= n and 0 < ny <= m and t[nx][ny] != "#" and d[nx][ny] - 1 > d[x][y]:
if px == dx and py == dy and cnt < k:
d[nx][ny] = d[x][y]
cnt += 1
que.append((nx, ny, dx, dy, cnt))
else:
d[nx][ny] = d[x][y] + 1
cnt = 1
que.append((nx, ny, dx, dy, cnt))
return d[gx][gy]
ans = bfs()
if ans == INF:
print(-1)
else:
print(ans)
```
No
| 108,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Olya loves energy drinks. She loves them so much that her room is full of empty cans from energy drinks.
Formally, her room can be represented as a field of n Γ m cells, each cell of which is empty or littered with cans.
Olya drank a lot of energy drink, so now she can run k meters per second. Each second she chooses one of the four directions (up, down, left or right) and runs from 1 to k meters in this direction. Of course, she can only run through empty cells.
Now Olya needs to get from cell (x1, y1) to cell (x2, y2). How many seconds will it take her if she moves optimally?
It's guaranteed that cells (x1, y1) and (x2, y2) are empty. These cells can coincide.
Input
The first line contains three integers n, m and k (1 β€ n, m, k β€ 1000) β the sizes of the room and Olya's speed.
Then n lines follow containing m characters each, the i-th of them contains on j-th position "#", if the cell (i, j) is littered with cans, and "." otherwise.
The last line contains four integers x1, y1, x2, y2 (1 β€ x1, x2 β€ n, 1 β€ y1, y2 β€ m) β the coordinates of the first and the last cells.
Output
Print a single integer β the minimum time it will take Olya to get from (x1, y1) to (x2, y2).
If it's impossible to get from (x1, y1) to (x2, y2), print -1.
Examples
Input
3 4 4
....
###.
....
1 1 3 1
Output
3
Input
3 4 1
....
###.
....
1 1 3 1
Output
8
Input
2 2 1
.#
#.
1 1 2 2
Output
-1
Note
In the first sample Olya should run 3 meters to the right in the first second, 2 meters down in the second second and 3 meters to the left in the third second.
In second sample Olya should run to the right for 3 seconds, then down for 2 seconds and then to the left for 3 seconds.
Olya does not recommend drinking energy drinks and generally believes that this is bad.
Submitted Solution:
```
from collections import deque
n, m, k = map(int, input().split())
INF = float("inf")
d = [[INF] * (m + 1) for _ in range(n + 1)]
t = [[] for i in range(n + 1)]
for i in range(n):
a = list("#" + input())
t[i + 1] = a
sx, sy, gx, gy = map(int, input().split())
def bfs():
px, py, cnt = 0, 0, 0
que = deque()
que.append((sx, sy, px, py, cnt))
d[sx][sy] = 0
while len(que):
x, y, px, py, cnt = que.popleft()
# if x == gx and y == gy:
# break
for dx, dy in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
nx, ny = x + dx, y + dy
if 0 < nx <= n and 0 < ny <= m and t[nx][ny] != "#" and d[nx][ny] - 1 > d[x][y]:
if px == dx and py == dy and cnt < k:
d[nx][ny] = d[x][y]
cnt += 1
else:
d[nx][ny] = d[x][y] + 1
cnt = 1
px, py = dx, dy
que.append((nx, ny, px, py, cnt))
return d[gx][gy]
ans = bfs()
if ans == INF:
print(-1)
else:
print(ans)
```
No
| 108,360 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 β€ i β€ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 β€ m β€ 105) β the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer β the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Tags: data structures, dp, strings
Correct Solution:
```
n = int(input()); s = input(); m = int(input())
a = [0]*(n+2); b = [0]*(n+2); q = [0]*(n+1);
dp = [(0, 0)]*(n+2)
for i in range(0, n):
b[i] = b[i-2]+(s[i] == 'b')
a[i] = a[i-2]+(s[i] == 'a')
q[i] = q[i-1]+(s[i] == '?')
for i in range(n-1, -1, -1):
if i+m-1 >= n:
continue
dp[i] = dp[i+1]
i_b = 1 if m%2 == 1 else 2
i_a = 1 if m%2 == 0 else 2
if not (b[i+m-i_b]-b[i-2] or a[i+m-i_a]-a[i-1]):
t, r = dp[i+m]
dp[i] = min((t-1, r+q[i+m-1]-q[i-1]), dp[i])
print(dp[0][1])
```
| 108,361 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 β€ i β€ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 β€ m β€ 105) β the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer β the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Tags: data structures, dp, strings
Correct Solution:
```
n = int(input()); s = input(); m = int(input())
a = [0]*(n+2); b = [0]*(n+2); q = [0]*(n+1);
dp = [(0, 0)]*(n+2)
for i in range(0, n):
b[i] = b[i-2]+(s[i] == 'b')
a[i] = a[i-2]+(s[i] == 'a')
q[i] = q[i-1]+(s[i] == '?')
for i in range(n-m, -1, -1):
dp[i] = dp[i+1]
i_b = 1 if m%2 == 1 else 2
i_a = 1 if m%2 == 0 else 2
if not (b[i+m-i_b]-b[i-2] or a[i+m-i_a]-a[i-1]):
t, r = dp[i+m]
dp[i] = min((t-1, r+q[i+m-1]-q[i-1]), dp[i])
print(dp[0][1])
```
| 108,362 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 β€ i β€ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 β€ m β€ 105) β the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer β the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Tags: data structures, dp, strings
Correct Solution:
```
match = 0; nonmatch = 0; count = 0
def calc_match(s, t, p):
global match
global nonmatch
global count
if p == len(s)-len(t):
return
if p+len(t) < len(s):
if s[p+len(t)] == '?':
count -= 1
elif s[p+len(t)] == t[-1]:
match -= 1
else:
nonmatch -= 1
match, nonmatch = nonmatch, match
if p+len(t) < len(s):
if s[p] == '?':
count += 1
elif s[p] == 'a':
match += 1
else:
nonmatch += 1
def init_match(s, t):
global match
global nonmatch
global count
p = len(s)-len(t)
for i in range(len(t)):
if s[p+i] == '?':
count += 1
elif s[p+i] == t[i]:
match += 1
else:
nonmatch += 1
n = int(input())
s = input()
m = int(input())
t = ""
for i in range(m):
if i%2==0:
t = t + 'a'
else:
t = t + 'b'
init_match(s,t)
dp = []
for i in range(n+3):
dp.append((0, 0))
p = n-m
while p >= 0:
calc_match(s, t, p)
if nonmatch == 0:
if dp[p+1][0] == dp[p+m][0]+1:
dp[p] = (dp[p+1][0], min(dp[p+1][1], dp[p+m][1]+count))
elif dp[p+1][0] > dp[p+m][0]+1:
dp[p] = dp[p+1]
else:
dp[p] = (dp[p+m][0]+1, dp[p+m][1]+count)
else:
dp[p] = dp[p+1]
p -= 1
print(dp[0][1])
```
| 108,363 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 β€ i β€ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 β€ m β€ 105) β the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer β the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Tags: data structures, dp, strings
Correct Solution:
```
match = 0
nonmatch = 0
count = 0
def calc_match(s, t, p):
global match
global nonmatch
global count
if p == len(s)-len(t):
return
if p+len(t) < len(s):
if s[p+len(t)] == '?':
count -= 1
elif s[p+len(t)] == t[-1]:
match -= 1
else:
nonmatch -= 1
match, nonmatch = nonmatch, match
if p+len(t) < len(s):
if s[p] == '?':
count += 1
elif s[p] == 'a':
match += 1
else:
nonmatch += 1
def init_match(s, t):
global match
global nonmatch
global count
p = len(s)-len(t)
for i in range(len(t)):
if s[p+i] == '?':
count += 1
elif s[p+i] == t[i]:
match += 1
else:
nonmatch += 1
n = int(input())
s = input()
m = int(input())
t = ""
for i in range(m):
if i%2==0:
t = t + 'a'
else:
t = t + 'b'
init_match(s,t)
dp = []
for i in range(n+3):
dp.append((0, 0))
p = n-m
while p >= 0:
calc_match(s, t, p)
if nonmatch == 0:
if dp[p+1][0] == dp[p+m][0]+1:
dp[p] = (dp[p+1][0], min(dp[p+1][1], dp[p+m][1]+count))
elif dp[p+1][0] > dp[p+m][0]+1:
dp[p] = dp[p+1]
else:
dp[p] = (dp[p+m][0]+1, dp[p+m][1]+count)
else:
dp[p] = dp[p+1]
p -= 1
print(dp[0][1])
```
| 108,364 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 β€ i β€ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 β€ m β€ 105) β the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer β the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Submitted Solution:
```
n = int(input())
s = list(input())
t = int(input())
re = s.copy()
kras = 'ab'
kras *= t
kras = kras[:t]
col = s.count('?')
c = 0
v = 0
q = 0
h = 0
for i in range(2 ** col):
shable = bin(i)[2:]
priv = '0' * (col - len(shable))
priv += shable
shable = priv
for el in range(n):
if s[el] == '?':
if shable[q] == '1':
if el % 2 == 0:
s[el] = 'a'
else:
s[el] = 'b'
q += 1
new = ''.join(s).count(kras)
if new > c:
v = shable.count('1')
c = new
s = re.copy()
q = 0
h = 0
for i in range(2 ** col):
shable = bin(i)[2:]
priv = '0' * (col - len(shable))
priv += shable
shable = priv
for el in range(n):
if s[el] == '?':
if shable[q] == '1':
if el % 2 == 0:
s[el] = 'b'
else:
s[el] = 'a'
q += 1
new = ''.join(s).count(kras)
if new > c:
v = shable.count('1')
c = new
s = re.copy()
q = 0
h = 0
print(v)
```
No
| 108,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 β€ i β€ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 β€ m β€ 105) β the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer β the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Submitted Solution:
```
match = 0
nonmatch = 0
count = 0
def calc_match(s, t, p):
global match
global nonmatch
global count
if p+len(t) < len(s):
if s[p+len(t)] == '?':
count -= 1
elif s[p+len(t)] == t[-1]:
match -= 1
else:
nonmatch -= 1
match, nonmatch = nonmatch, match
if p+len(t) < len(s):
if s[p] == '?':
count += 1
elif s[p] == 'a':
match += 1
else:
nonmatch += 1
def init_match(s, t):
global match
global nonmatch
global count
p = len(s)-len(t)
for i in range(len(t)):
if s[p+i] == '?':
count += 1
elif s[p+i] == t[i]:
match += 1
else:
nonmatch += 1
n = int(input())
s = input()
m = int(input())
t = ""
for i in range(m):
if i%2==0:
t = t + 'a'
else:
t = t + 'b'
init_match(s,t)
dp = []
for i in range(n+3):
dp.append((0, 0))
p = n-m
while p >= 0:
calc_match(s, t, p)
if nonmatch == 0:
if dp[p+1][0] == dp[p+m][0]+1:
dp[p] = (dp[p+1][0], min(dp[p+1][1], dp[p+m][1]+count))
elif dp[p+1][0] > dp[p+m][0]+1:
dp[p] = dp[p+1]
else:
dp[p] = (dp[p+m][0]+1, dp[p+m][1]+count)
else:
dp[p] = dp[p+1]
p -= 1
print(dp[0][1])
```
No
| 108,366 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 β€ i β€ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 β€ m β€ 105) β the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer β the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Submitted Solution:
```
n = int(input())
s = list(input())
t = int(input())
re = s.copy()
kras = 'ab'
kras *= t
kras = kras[:t]
col = s.count('?')
c = 0
v = 0
q = 0
h = 0
for i in range(2 ** col):
shable = bin(i)[2:]
priv = '0' * (col - len(shable))
priv += shable
shable = priv
for el in range(n):
if s[el] == '?':
if shable[q] == '1':
h += 1
if el % 2 == 0:
s[el] = 'a'
else:
s[el] = 'b'
q += 1
new = ''.join(s).count(kras)
if new > c:
v = h
c = new
s = re.copy()
q = 0
h = 0
print(v)
```
No
| 108,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.
Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.
Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 β€ i β€ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.
The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the length of s.
The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.
The third line contains a single integer m (1 β€ m β€ 105) β the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.
Output
Print the only integer β the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.
Examples
Input
5
bb?a?
1
Output
2
Input
9
ab??ab???
3
Output
2
Note
In the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.
In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Submitted Solution:
```
n = int(input())
s = list(input())
t = int(input())
re = s.copy()
kras = 'ab'
kras *= t
kras = kras[:t]
col = s.count('?')
c = 0
v = 0
q = 0
h = 0
for i in range(2 ** col):
shable = bin(i)[2:]
priv = '0' * (col - len(shable))
priv += shable
shable = priv
for el in range(n):
if s[el] == '?':
if shable[q] == '1':
if s[el - 1] == 'b':
s[el] = 'a'
else:
s[el] = 'b'
q += 1
new = ''.join(s).count(kras)
if new > c:
v = shable.count('1')
c = new
s = re.copy()
q = 0
h = 0
print(v)
```
No
| 108,368 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Tags: data structures, greedy, strings, trees
Correct Solution:
```
def add(x):
global tree
now = 0
tree[now][2] += 1
for i in range(29, -1, -1):
bit = (x>>i)&1
if tree[now][bit]==0:
tree[now][bit]=len(tree)
tree.append([0, 0, 0])
now = tree[now][bit]
tree[now][2] += 1
def find_min(x):
global tree
now = ans = 0
for i in range(29, -1, -1):
bit = (x>>i)&1
if tree[now][bit] and tree[tree[now][bit]][2]:
now = tree[now][bit]
else:
now = tree[now][bit^1]
ans |= (1<<i)
tree[now][2] -= 1
return ans
tree = [[0, 0, 0]]
n = int(input())
a = list(map(int, input().split()))
list(map(add, map(int, input().split())))
[print(x, end=' ') for x in list(map(find_min, a))]
```
| 108,369 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Tags: data structures, greedy, strings, trees
Correct Solution:
```
def add(x):
global tree, cnt
now = 0
tree[now][2] += 1
for i in range(29, -1, -1):
bit = (x>>i)&1
if tree[now][bit]==0:
cnt += 1
tree[now][bit] = cnt
tree.append([0, 0, 0])
now = tree[now][bit]
tree[now][2] += 1
def find_min(x):
global tree
now = ans = 0
for i in range(29, -1, -1):
bit = (x>>i)&1
if tree[now][bit] and tree[tree[now][bit]][2]:
now = tree[now][bit]
else:
now = tree[now][bit^1]
ans |= (1<<i)
tree[now][2] -= 1
return ans
tree = [[0, 0, 0]]
cnt = 0
n = int(input())
a = list(map(int, input().split()))
list(map(add, map(int, input().split())))
[print(x, end=' ') for x in list(map(find_min, a))]
```
| 108,370 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Tags: data structures, greedy, strings, trees
Correct Solution:
```
def add(x):
global tree
now = 0
tree[now][2] += 1
for i in range(29, -1, -1):
bit = (x>>i)&1
if tree[now][bit]==0:
tree[now][bit]=len(tree)
tree.append([0, 0, 0])
now = tree[now][bit]
tree[now][2] += 1
def find_min(x):
global tree
now = ans = 0
for i in range(29, -1, -1):
bit = (x>>i)&1
if tree[now][bit] and tree[tree[now][bit]][2]:
now = tree[now][bit]
else:
now = tree[now][bit^1]
ans |= (1<<i)
tree[now][2] -= 1
return ans
tree = [[0, 0, 0]]
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
list(map(add, b))
[print(x, end=' ') for x in list(map(find_min, a))]
```
| 108,371 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Tags: data structures, greedy, strings, trees
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: max(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] > k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie--------------------------------
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
s=BinaryTrie()
for i in b:
s.insert(i)
for i in a:
print(s.query(i),end=" ")
```
| 108,372 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Tags: data structures, greedy, strings, trees
Correct Solution:
```
n=int(input())
ai=list(map(int,input().split()))
pi=list(map(int,input().split()))
oi=[]
class node:
def __init__(self,data):
self.data=data
self.right=None
self.left=None
self.val=None
self.count=0
class trie:
def __init__(self):
self.root=node("0")
def insert(self,data):
self.active = self.root
for i in data:
if i=="1":
if self.active.right:
self.active=self.active.right
else:
self.active.right=node("1")
self.active=self.active.right
if i=="0":
if self.active.left:
self.active=self.active.left
else:
self.active.left=node("0")
self.active=self.active.left
self.active.count+=1
self.active.val=int(data,2)
def func(self,data):
self.active=self.root
for i in data:
if i=="0":
if self.active.left and self.active.left.count>0:
self.active=self.active.left
else:
self.active=self.active.right
else:
if self.active.right and self.active.right.count>0:
self.active=self.active.right
else:
self.active=self.active.left
self.active.count-=1
return int(data,2)^self.active.val
t=trie()
for i in pi:
t.insert(bin(i)[2:].rjust(31,"0"))
for i in ai:
oi.append(t.func(bin(i)[2:].rjust(31,"0")))
print(*oi)
```
| 108,373 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Tags: data structures, greedy, strings, trees
Correct Solution:
```
from sys import stdin
input=stdin.readline
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
self.count=0
class Trie():
def __init__(self):
self.root=Node(0)
def insert(self,preXor):
self.temp=self.root
for i in range(31,-1,-1):
val=preXor&(1<<i)
if val:
if not self.temp.right:
self.temp.right=Node(0)
self.temp=self.temp.right
self.temp.count+=1
else:
if not self.temp.left:
self.temp.left=Node(0)
self.temp=self.temp.left
self.temp.count+=1
self.temp.data=preXor
def query(self,val):
self.temp=self.root
for i in range(31,-1,-1):
active=val&(1<<i)
if active:
if self.temp.right and self.temp.right.count>0:
self.temp=self.temp.right
elif self.temp.left:
self.temp=self.temp.left
else:
if self.temp.left and self.temp.left.count>0:
self.temp=self.temp.left
elif self.temp.right:
self.temp=self.temp.right
self.temp.count-=1
return val^(self.temp.data)
n=input()
l1=list(map(int,input().strip().split()))
l2=list(map(int,input().strip().split()))
trie=Trie()
for i in l2:
trie.insert(i)
for i in l1:
print(trie.query(i),end=" ")
```
| 108,374 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Submitted Solution:
```
n = int(input())
A = map(int, input().split(" "))
P = map(int, input().split(" "))
results = []
class TrieNode:
def __init__(self):
self.children = [None, None]
self.counter = 1
def add(self, number):
node = self
for i in range(30, -1, -1):
digit = (number >> i) & 1
if node.children[digit]:
node.children[digit].counter += 1
else:
node.children[digit] = TrieNode()
node = node.children[digit]
def find(self, number):
node = self
result = 0
for i in range(30, -1, -1):
node.counter -= 1
digit = (number >> i) & 1
other_digit = 1 - digit
if node.children[digit] and node.children[digit].counter > 0:
result |= digit << i
node = node.children[digit]
else:
result |= other_digit << i
node = node.children[other_digit]
return result
root = TrieNode()
for x in P:
root.add(x)
for a in A:
results.append(root.find(a) ^ a)
print(" ".join(map(str, results)))
```
No
| 108,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Submitted Solution:
```
n = int(input())
A = input().split(" ")
P = input().split(" ")
res = []
A = list(map(bin, map(int, A)))
P = list(map(bin, map(int, P)))
dicti = {}
for p in P:
if len(p) in dicti.keys():
tmp = dicti[len(p)]
tmp.append(p)
dicti[len(p)] = tmp
else:
dicti[len(p)] = [p]
dicti_keys = list(dicti.keys())
dicti_keys.sort()
tmp = []
for a in A:
l = len(a)
for count, char in enumerate(a):
if char == "1" and (l - count + 2 in dicti_keys):
tmp = dicti[l - count + 2]
break
if not len(tmp):
tmp = dicti[dicti_keys[0]]
mini = int(tmp[0], 2) ^ int(a, 2)
el = 0
for j in range(1, len(tmp)):
if (int(tmp[j], 2) ^ int(a, 2)) < mini:
mini = int(tmp[j], 2) ^ int(a, 2)
el = j
res.append(tmp[el])
l = len(tmp[el])
del tmp[el]
if len(tmp):
dicti[l] = tmp
else:
dicti_keys.remove(l)
for i, el in enumerate(res):
res[i] = int(el, 2) ^ int(A[i], 2)
print(" ".join(map(str, res)))
```
No
| 108,376 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Submitted Solution:
```
n = int(input())
A = input().split(" ")
P = input().split(" ")
res = []
A = list(map(bin, map(int, A)))
P = list(map(bin, map(int, P)))
dicti = {}
for p in P:
if len(p) in dicti.keys():
tmp = dicti[len(p)]
tmp.append(p)
dicti[len(p)] = tmp
else:
dicti[len(p)] = [p]
dicti_keys = list(dicti.keys())
dicti_keys.sort()
for a in A:
tmp = []
len_a = len(a)
for count, char in enumerate(a):
if char == "1" and len_a - count + 2 in dicti.keys():
tmp = dicti[len_a - count + 2]
break
if not len(tmp):
tmp = dicti[dicti_keys[0]]
mini = int(tmp[0], 2) ^ int(a, 2)
el = 0
for j in range(1, len(tmp)):
if (int(tmp[j], 2) ^ int(a, 2)) < mini:
mini = int(tmp[j], 2) ^ int(a, 2)
el = j
res.append(tmp[el])
l = len(tmp[el])
del tmp[el]
if len(tmp):
dicti[l] = tmp
else:
dicti_keys.remove(l)
for i, el in enumerate(res):
res[i] = int(el, 2) ^ int(A[i], 2)
print(" ".join(map(str, res)))
```
No
| 108,377 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (<image>, where <image> denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) and stores this encrypted message A. Alice is smart. Be like Alice.
For example, Alice may have wanted to store a message M = (0, 15, 9, 18). She generated a key K = (16, 7, 6, 3). The encrypted message is thus A = (16, 8, 15, 17).
Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.
Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.
In the above example, Bob may have, for instance, selected a permutation (3, 4, 1, 2) and stored the permuted key P = (6, 3, 16, 7).
One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?
Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?
More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that <image> for every i.
Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Si < Ti and for all j < i the condition Sj = Tj holds.
Input
The first line contains a single integer N (1 β€ N β€ 300000), the length of the message.
The second line contains N integers A1, A2, ..., AN (0 β€ Ai < 230) representing the encrypted message.
The third line contains N integers P1, P2, ..., PN (0 β€ Pi < 230) representing the permuted encryption key.
Output
Output a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.
Examples
Input
3
8 4 13
17 2 7
Output
10 3 28
Input
5
12 7 87 22 11
18 39 9 12 16
Output
0 14 69 6 44
Input
10
331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951
226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667
Output
128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284
Note
In the first case, the solution is (10, 3, 28), since <image>, <image> and <image>. Other possible permutations of key yield messages (25, 6, 10), (25, 3, 15), (10, 21, 10), (15, 21, 15) and (15, 6, 28), which are all lexicographically larger than the solution.
Submitted Solution:
```
import math
#f = open("input")
def readline():
return input()#f.readline().strip()
def get_min_xor(target_num, P):
index = int(math.log(target_num, 2))
max_num = 2 ** (index + 1)
i = 0
min_b, curr_index = None, 0
curr_num = P[0]
while min_b == None or (curr_index < len(P) and P[curr_index] <= max_num):
if min_b == None:
min_b = target_num ^ P[curr_index]
curr_num = P[curr_index]
else:
min_b = min(min_b, target_num ^ P[curr_index])
if min_b == target_num ^ P[curr_index]:
curr_num = P[curr_index]
curr_index += 1
return (min_b, curr_num)
def task_3():
amount = int(readline())
A = list(map(lambda x: int(x), readline().split(" ")))
P = list(map(lambda x: int(x), readline().split(" ")))
P.sort()
result = []
for a in A:
(b, p) = get_min_xor(a, P)
P.remove(p)
result.append(b)
print(" ".join([str(x) for x in result]))
task_3()
```
No
| 108,378 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Tags: math
Correct Solution:
```
def cut(n):
if n ==0: return (0)
if n%2:
return (n+1)//2
else:
return (n+1)
n = int(input())
print(cut(n))
```
| 108,379 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Tags: math
Correct Solution:
```
import os
import sys
def main():
n = int(input())
if n % 2 == 0 and n != 0:
print(n + 1)
if n % 2 != 0:
print((n + 1) // 2)
if n == 0:
print(0)
if __name__ == "__main__":
main()
```
| 108,380 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Tags: math
Correct Solution:
```
n = int(input())
if n == 0:
print(0)
elif n % 2 == 0:
print(n + 1)
else:
print((n + 1) // 2)
```
| 108,381 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Tags: math
Correct Solution:
```
a = int(int(input()) + 1)
if a == 1:
print(0)
elif a % 2 == 0:
print(a//2)
else:
print(a)
```
| 108,382 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Tags: math
Correct Solution:
```
n = int(input())
if n % 2 == 1:
print((n + 1) // 2)
elif n == 0:
print(0)
else:
print(n + 1)
```
| 108,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Tags: math
Correct Solution:
```
n=int(input())+1
print(n//2if n%2==0 or n==1 else n)
```
| 108,384 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Tags: math
Correct Solution:
```
n=int(input())
if n==0: print(0)
elif n%2: print((n+1)//2)
else: print(n+1)
```
| 108,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Tags: math
Correct Solution:
```
def read_nums():
return [int(x) for x in input().split()]
def solve(n):
if n == 0:
print(0)
return
if (n + 1) % 2 == 0:
print((n + 1) // 2)
else:
print(n + 1)
def main():
n, = read_nums()
solve(n)
if __name__ == '__main__':
main()
```
| 108,386 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Submitted Solution:
```
n=int(input())
if(n==0):
print(0)
else:
if(n%2==1):
print(n//2+1)
else:
print(n+1)
```
Yes
| 108,387 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Submitted Solution:
```
n=int(input())
if n==0:
print("0")
exit(0)
n+=1
if n%2==0:
print(n//2)
else:
print(n)
```
Yes
| 108,388 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Submitted Solution:
```
n=int(input())
n+=1
if n==1:
print("0")
elif n%2==0:
print(n//2)
else:
print(n)
```
Yes
| 108,389 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Submitted Solution:
```
#n, k = map(int, input().split(" ")) # read multiple integers into different variables
#L = [int(x) for x in input().split()] # read multiple integers into a list
#print(' '.join(map(str, L))) # print multiple integers in one line
n = int(input())
if n == 0 : print(0)
elif n % 2 == 0 : print(n + 1)
else : print((n + 1) // 2)
```
Yes
| 108,390 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Submitted Solution:
```
n=int(input())
if (n+1)%2==0:
print((n+1)/2)
else:
print(n+1)
```
No
| 108,391 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Submitted Solution:
```
n=int(input())
if n%2==0:
print(n+1)
else:
print(n-1)
```
No
| 108,392 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Submitted Solution:
```
n = int(input())
c=0
if(n == 0):
c = n
elif(n % 2 == 0):
c = n+1
else:
c = (n+1)/2
print(c)
```
No
| 108,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
Input
A single line contains one non-negative integer n (0 β€ n β€ 10^{18}) β the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.
Output
A single integer β the number of straight cuts Shiro needs.
Examples
Input
3
Output
2
Input
4
Output
5
Note
To cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.
To cut the round pizza into five equal parts one has to make five cuts.
Submitted Solution:
```
a = int(input())+1
if a==1:
print(0)
if a%2 ==0:
print(int(a//2))
else:
print(a)
```
No
| 108,394 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string s of length n can be encrypted by the following algorithm:
* iterate over all divisors of n in decreasing order (i.e. from n to 1),
* for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d).
For example, the above algorithm applied to the string s="codeforces" leads to the following changes: "codeforces" β "secrofedoc" β "orcesfedoc" β "rocesfedoc" β "rocesfedoc" (obviously, the last reverse operation doesn't change the string because d=1).
You are given the encrypted string t. Your task is to decrypt this string, i.e., to find a string s such that the above algorithm results in string t. It can be proven that this string s always exists and is unique.
Input
The first line of input consists of a single integer n (1 β€ n β€ 100) β the length of the string t. The second line of input consists of the string t. The length of t is n, and it consists only of lowercase Latin letters.
Output
Print a string s such that the above algorithm results in t.
Examples
Input
10
rocesfedoc
Output
codeforces
Input
16
plmaetwoxesisiht
Output
thisisexampletwo
Input
1
z
Output
z
Note
The first example is described in the problem statement.
Tags: implementation
Correct Solution:
```
class CodeforcesTask999BSolution:
def __init__(self):
self.result = ''
self.n = 0
self.code = ''
def read_input(self):
self.n = int(input())
self.code = input()
def process_task(self):
for x in range(1, self.n + 1):
if not self.n % x:
self.code = self.code[:x][::-1] + self.code[x:]
self.result = self.code
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask999BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
```
| 108,395 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string s of length n can be encrypted by the following algorithm:
* iterate over all divisors of n in decreasing order (i.e. from n to 1),
* for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d).
For example, the above algorithm applied to the string s="codeforces" leads to the following changes: "codeforces" β "secrofedoc" β "orcesfedoc" β "rocesfedoc" β "rocesfedoc" (obviously, the last reverse operation doesn't change the string because d=1).
You are given the encrypted string t. Your task is to decrypt this string, i.e., to find a string s such that the above algorithm results in string t. It can be proven that this string s always exists and is unique.
Input
The first line of input consists of a single integer n (1 β€ n β€ 100) β the length of the string t. The second line of input consists of the string t. The length of t is n, and it consists only of lowercase Latin letters.
Output
Print a string s such that the above algorithm results in t.
Examples
Input
10
rocesfedoc
Output
codeforces
Input
16
plmaetwoxesisiht
Output
thisisexampletwo
Input
1
z
Output
z
Note
The first example is described in the problem statement.
Tags: implementation
Correct Solution:
```
a=int(input())
b=input()
f=[]
for i in range(1,a+1):
if a%i==0:
f.append(i)
f.sort()
def aa(a,b):
g=''
for i in range(a,len(b)):
g=g+b[i]
e=[]
for i in range(a):
e.append(b[i])
e.reverse()
t=''
for i in e:
t=t+i
t=t+g
return(t)
for i in f:
b=aa(i,b)
print(b)
```
| 108,396 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string s of length n can be encrypted by the following algorithm:
* iterate over all divisors of n in decreasing order (i.e. from n to 1),
* for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d).
For example, the above algorithm applied to the string s="codeforces" leads to the following changes: "codeforces" β "secrofedoc" β "orcesfedoc" β "rocesfedoc" β "rocesfedoc" (obviously, the last reverse operation doesn't change the string because d=1).
You are given the encrypted string t. Your task is to decrypt this string, i.e., to find a string s such that the above algorithm results in string t. It can be proven that this string s always exists and is unique.
Input
The first line of input consists of a single integer n (1 β€ n β€ 100) β the length of the string t. The second line of input consists of the string t. The length of t is n, and it consists only of lowercase Latin letters.
Output
Print a string s such that the above algorithm results in t.
Examples
Input
10
rocesfedoc
Output
codeforces
Input
16
plmaetwoxesisiht
Output
thisisexampletwo
Input
1
z
Output
z
Note
The first example is described in the problem statement.
Tags: implementation
Correct Solution:
```
n = int(input())
str1 = str(input())
l2 = []
for i in str1:
l2.append(i)
l1 = []
# x = n/1.0
for j in range(1,n):
if n/j == int(n/j):
l1.append(j)
l1.append(int(n))
for i in l1:
l3 = l2[0:i]
l3.reverse()
l2[0:i] = l3[0:i]
strp = ""
for i in l2:
strp+=i
print(strp)
```
| 108,397 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string s of length n can be encrypted by the following algorithm:
* iterate over all divisors of n in decreasing order (i.e. from n to 1),
* for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d).
For example, the above algorithm applied to the string s="codeforces" leads to the following changes: "codeforces" β "secrofedoc" β "orcesfedoc" β "rocesfedoc" β "rocesfedoc" (obviously, the last reverse operation doesn't change the string because d=1).
You are given the encrypted string t. Your task is to decrypt this string, i.e., to find a string s such that the above algorithm results in string t. It can be proven that this string s always exists and is unique.
Input
The first line of input consists of a single integer n (1 β€ n β€ 100) β the length of the string t. The second line of input consists of the string t. The length of t is n, and it consists only of lowercase Latin letters.
Output
Print a string s such that the above algorithm results in t.
Examples
Input
10
rocesfedoc
Output
codeforces
Input
16
plmaetwoxesisiht
Output
thisisexampletwo
Input
1
z
Output
z
Note
The first example is described in the problem statement.
Tags: implementation
Correct Solution:
```
def rev( l , d ) :
ll = l[ d : ]
ll1 = l[ : d]
ll = ll1[::-1] + ll
return ll
n = int( input() )
s = str( input() )
di = []
for i in range( 1 , n + 1 ) :
if n % i == 0 :
di.append( i )
l = list( s )
for i in range( len( di ) ) :
#print( ''.join( l ) )
l = rev( l , di[ i ] )
#print(''.join( l ) , di[ i ] )
print( ''.join(l) )
```
| 108,398 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A string s of length n can be encrypted by the following algorithm:
* iterate over all divisors of n in decreasing order (i.e. from n to 1),
* for each divisor d, reverse the substring s[1 ... d] (i.e. the substring which starts at position 1 and ends at position d).
For example, the above algorithm applied to the string s="codeforces" leads to the following changes: "codeforces" β "secrofedoc" β "orcesfedoc" β "rocesfedoc" β "rocesfedoc" (obviously, the last reverse operation doesn't change the string because d=1).
You are given the encrypted string t. Your task is to decrypt this string, i.e., to find a string s such that the above algorithm results in string t. It can be proven that this string s always exists and is unique.
Input
The first line of input consists of a single integer n (1 β€ n β€ 100) β the length of the string t. The second line of input consists of the string t. The length of t is n, and it consists only of lowercase Latin letters.
Output
Print a string s such that the above algorithm results in t.
Examples
Input
10
rocesfedoc
Output
codeforces
Input
16
plmaetwoxesisiht
Output
thisisexampletwo
Input
1
z
Output
z
Note
The first example is described in the problem statement.
Tags: implementation
Correct Solution:
```
IL = lambda: list(map(int, input().split()))
n = int(input())
s = list(input())
for i in range(1, n+1):
if n%i:
continue
s[:i] = s[i-1::-1]
print(''.join(s))
```
| 108,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.