text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Tags: binary search, sortings
Correct Solution:
```
from collections import defaultdict
n, m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
d = defaultdict(int)
d[0] = 0
for v in a:
for i in range(1, m + 1):
d[v * i] = i
q = int(input())
for _ in range(q):
x = int(input())
r = m + 1
for k, v in d.items():
y = x - k
if y in d:
r = min(r, v + d[y])
print(r if r <= m else -1)
```
| 14,600 |
Provide tags and a correct Python 3 solution for this coding contest problem.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Tags: binary search, sortings
Correct Solution:
```
def find(x):
ret = 100
for k in mp:
if x - k in mp:
ret = min(ret, mp[k] + mp[x - k])
return ret if ret <= m else -1
n, m = (int(x) for x in input().split())
a = [int(x) for x in input().split()]
mp = {}
for i in a:
for j in range(m + 1):
x = i * j
if x in mp:
mp[x] = min(j, mp[x])
else:
mp[x] = j
q = int(input())
for Q in range(q):
x = int(input())
print(find(x))
```
| 14,601 |
Provide tags and a correct Python 3 solution for this coding contest problem.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Tags: binary search, sortings
Correct Solution:
```
n_k = input()
n_k = n_k.split(" ")
n = int(n_k[0])
k = int(n_k[1])
ais = input()
ais = ais.split(" ")
q = int(input())
pares = {}
for a in ais:
a = int(a)
for i in range(k):
p = int((i+1)*a)
if (p not in pares) or (i+1 < pares[p]):
pares[p] = i+1
m = 1000000000
for i in range(q):
x = int(input())
ans = 1000;
minimo = m
for plata, deuda in pares.items():
if plata == x:
if deuda <= k:
if deuda < minimo:
minimo = deuda
else:
r = x-plata
if r in pares:
if deuda+pares[r] < minimo:
if deuda + pares[r] <= k:
minimo = deuda+pares[r]
if minimo == m:
print(-1)
else:
print(minimo)
# 1538793706889
```
| 14,602 |
Provide tags and a correct Python 3 solution for this coding contest problem.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Tags: binary search, sortings
Correct Solution:
```
n_k = input()
n_k = n_k.split(" ")
n = int(n_k[0])
k = int(n_k[1])
ais = input()
ais = ais.split(" ")
q = int(input())
pares = {}
for a in ais:
a = int(a)
for i in range(k):
p = int((i+1)*a)
if (p not in pares) or (i+1 < pares[p]):
pares[p] = i+1
m = 1000000000
for i in range(q):
x = int(input())
ans = 1000;
minimo = m
for money, bills in pares.items():
if money == x and bills <= k and bills < minimo:
minimo = bills
else:
r = x-money
if r in pares and bills+pares[r] < minimo and bills + pares[r] <= k:
minimo = bills+pares[r]
if minimo == m:
print(-1)
else:
print(minimo)
```
| 14,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Submitted Solution:
```
f = lambda: map(int, input().split())
n, k = f()
t = list(f())
u = [{i * q for q in t} for i in range(1, k + 1)]
def g(d):
v = [{d - q for q in p} for p in u]
for j in range(1, k + 1):
if d in u[j - 1]: return j
for i in range(j // 2):
if u[i].intersection(v[j - i - 2]): return j
return -1
for i in range(int(input())): print(g(int(input())))
```
Yes
| 14,604 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Submitted Solution:
```
n,k = [int(s) for s in input().split()]
bills = [int(s) for s in input().split()]
pairs = {}
for bill in bills:
for i in range(k):
possible = (i+1)*bill
if possible not in pairs or i+1 < pairs[possible]:
pairs[possible] = i+1
q = int(input())
mymax = 100000000000000000
for i in range(q):
query = int(input())
minumum = mymax
for money, nbills in pairs.items():
if money == query and nbills <=k and nbills < minumum:
minumum = nbills
else:
rest = query-money
if rest in pairs and nbills+pairs[rest] < minumum and nbills+pairs[rest] <= k:
minumum = nbills+pairs[rest]
if minumum == mymax:
print(-1)
else:
print(minumum)
```
Yes
| 14,605 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Submitted Solution:
```
n, k = (int(x) for x in input().split())
a = [int(x) for x in input().split()]
q = int(input())
for _ in range(q):
x = int(input())
m = -1
for i in range(n):
for j in range(i+1, n):
#print("trying", x, "with", a[i], a[j])
k1, r = divmod(x, a[j])
#print("result:", k1, r)
if r % a[i] == 0:
k2 = r //a[i]
if k1 + k2 <= k and (m == -1 or k1 + k2 < m):
m = k1 + k2
print(m)
```
No
| 14,606 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Submitted Solution:
```
n, k= map(int, input().split())
d = list(map(int, input().split()))
d.reverse()
q = int(input())
while q>0:
q -= 1
count = 0
anothercount = 0
amt = int(input())
for i in range(0, n):
if amt < d[i]:
i += 1
else:
count += amt//d[i]
anothercount += 1
amt %= d[i]
if amt != 0 or count > k or anothercount > 2:
print(-1)
else:
print(count)
```
No
| 14,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Submitted Solution:
```
n = list(map(int, input().split()))
k = n[1]
n = n[0]
bills = list(map(int, input().split()))
n_queries = int(input())
# used_bills = set()
#
#
# def check(amount, times, used_bills=None):
# used_bills = used_bills if used_bills else set()
# if times > k:
# return -1
# for bill in list(reversed(bills)):
# if amount - bill >= 0:
# used_bills.add(bill)
# if len(used_bills) > 2:
# return -1
# times += 1
# amount -= bill
# if amount == 0:
# return times
# return check(amount, times, used_bills)
# return -1
#
# times = 0
# for i in range(n_queries):
# print(check(int(input()), times))
def max_bill(amount):
times = 0
for bill in list(reversed(bills)):
if amount - bill >= 0:
times += amount//bill
# print("Times:", times)
# print("Bill:", bill)
if times > k:
return -1
amount -= amount//bill * bill
if amount == 0:
return times
return other_bill(amount, bill, times)
def other_bill(amount, bill, times):
for billy in list(reversed(bills)):
if billy >= bill:
continue
if not (amount/billy).is_integer():
continue
else:
times += amount//billy
# print("Billy:", billy)
if times > k:
return -1
return times
return False
for i in range(n_queries):
test_a = max_bill(int(input()))
print(test_a)
```
No
| 14,608 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.
Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.
Input
The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20).
The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.
The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make.
The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.
Output
For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print - 1, if it is impossible to get the corresponding sum.
Examples
Input
6 20
10 50 100 500 1000 5000
8
4200
100000
95000
96000
99000
10100
2015
9950
Output
6
20
19
20
-1
3
-1
-1
Input
5 2
1 2 3 5 8
8
1
3
5
7
9
11
13
15
Output
1
1
1
2
2
2
2
-1
Submitted Solution:
```
n = list(map(int, input().split()))
k = n[1]
n = n[0]
bills = list(map(int, input().split()))
n_queries = int(input())
used_bills = set()
def check(amount, times, used_bills=None):
used_bills = used_bills if used_bills else set()
if times > k:
return -1
for bill in list(reversed(bills)):
if amount - bill >= 0:
used_bills.add(bill)
if len(used_bills) > 2:
return -1
times += 1
amount -= bill
if amount == 0:
return times
return check(amount, times, used_bills)
return -1
times = 0
for i in range(n_queries):
print(check(int(input()), times))
```
No
| 14,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Tags: data structures, greedy, sortings
Correct Solution:
```
#!/usr/bin/env python
# 556D_fug.py - Codeforces.com 556D Fug quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Input
The first line contains integers n and m - the number of islands and bridges.
Next n lines each contain two integers li and ri - the coordinates of the
island endpoints.
The last line contains m integer numbers a1..am - the lengths of the bridges
that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands
in the required manner, print on a single line "No" (without the quotes)
, otherwise print in the first line "Yes" (without the quotes), and in the
second line print n-1 numbers b1, bn-1, which mean that between islands
i and i+1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this
problem it is necessary to print "Yes" and "No" in correct case
"""
# Standard libraries
import unittest
import sys
import re
# Additional libraries
import heapq
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.list = args[0]
self.alist = args[1]
self.gn = len(self.list) - 1
# Sorted list of bridges
self.asrt = sorted((n, i) for i, n in enumerate(self.alist))
# List of gaps between islands
self.gaps = []
prevli = self.list[0]
for i in range(self.gn):
li = self.list[i+1]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
self.gaps.append((min, max, i))
prevli = li
# Sorted list of gaps between islands
self.gsrt = sorted(self.gaps)
self.gmin = [n[0] for n in self.gsrt]
self.result = [None]*self.gn
self.heap = []
def iterate(self):
j = 0
for (b, i) in self.asrt:
# Traverse gmin array
while j < self.gn and self.gmin[j] <= b:
it = self.gsrt[j]
heapq.heappush(self.heap, (it[1], it[0], it[2]))
j += 1
# Update result and remove the element from lists
if self.heap:
(mmax, mmin, mi) = self.heap[0]
if mmin <= b and mmax >= b:
self.result[mi] = i + 1
heapq.heappop(self.heap)
yield
def calculate(self):
""" Main calcualtion function of the class """
for it in self.iterate():
pass
for n in self.result:
if n is None:
return "No"
answer = " ".join([str(n) for n in self.result])
return "Yes\n" + answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return sys.stdin.readline()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
list = [[int(s) for s in uinput().split()] for i in range(num[0])]
alist = [int(s) for s in uinput().split()]
# Decoding inputs into a list
inputs = [list, alist]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 20000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
x += 2
test += str(x) + " " + str(x+1) + "\n"
for i in range(size):
test += str(2) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
self.assertEqual(d.list[0][0], 1)
self.assertEqual(d.alist[0], 4)
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gaps[0], (2, 7, 0))
self.assertEqual(d.gsrt[0], (1, 3, 1))
iter = d.iterate()
next(iter)
self.assertEqual(d.gmin, [1, 2, 2])
self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)])
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
print(calculate())
```
| 14,610 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Tags: data structures, greedy, sortings
Correct Solution:
```
#!/usr/bin/env python
# 556D_fug.py - Codeforces.com 556D Fug quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Input
The first line contains integers n and m - the number of islands and bridges.
Next n lines each contain two integers li and ri - the coordinates of the
island endpoints.
The last line contains m integer numbers a1..am - the lengths of the bridges
that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands
in the required manner, print on a single line "No" (without the quotes)
, otherwise print in the first line "Yes" (without the quotes), and in the
second line print n-1 numbers b1, bn-1, which mean that between islands
i and i+1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this
problem it is necessary to print "Yes" and "No" in correct case
"""
# Standard libraries
import unittest
import sys
import re
# Additional libraries
import heapq
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.list = args[0]
self.alist = args[1]
self.gn = len(self.list) - 1
# Sorted list of bridges
self.asrt = sorted((n, i) for i, n in enumerate(self.alist))
# List of gaps between islands
self.gaps = []
prevli = self.list[0]
for i in range(self.gn):
li = self.list[i+1]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
self.gaps.append((min, max, i))
prevli = li
# Sorted list of gaps between islands
self.gsrt = sorted(self.gaps)
self.gmin = [n[0] for n in self.gsrt]
self.result = [None]*self.gn
self.heap = []
def iterate(self):
j = 0
for (b, i) in self.asrt:
# Traverse gmin array
while j < self.gn and self.gmin[j] <= b:
it = self.gsrt[j]
heapq.heappush(self.heap, (it[1], it[0], it[2]))
j += 1
# Update result and remove the element from lists
if self.heap:
(mmax, mmin, mi) = self.heap[0]
if mmin <= b and mmax >= b:
self.result[mi] = i + 1
heapq.heappop(self.heap)
yield
def calculate(self):
""" Main calcualtion function of the class """
for it in self.iterate():
pass
answer = ""
for (i, n) in enumerate(self.result):
if n is None:
return "No"
answer += (" " if i > 0 else "") + str(n)
return "Yes\n" + answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return input()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
list = [[int(s) for s in uinput().split()] for i in range(num[0])]
alist = [int(s) for s in uinput().split()]
# Decoding inputs into a list
inputs = [list, alist]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 50000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
x += 2
test += str(x) + " " + str(x+1) + "\n"
for i in range(size):
test += str(2) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
self.assertEqual(d.list[0][0], 1)
self.assertEqual(d.alist[0], 4)
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gaps[0], (2, 7, 0))
self.assertEqual(d.gsrt[0], (1, 3, 1))
iter = d.iterate()
next(iter)
self.assertEqual(d.gmin, [1, 2, 2])
self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)])
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
print(calculate())
```
| 14,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Tags: data structures, greedy, sortings
Correct Solution:
```
import heapq
n,m=[int(x) for x in input().split()]
l1,r1=[int(x) for x in input().split()]
req=[]
start=[]
for i in range(n-1):
l2,r2=[int(x) for x in input().split()]
req.append((l2-r1,r2-l1,i))
l1,r1=l2,r2
have=[int(x) for x in input().split()]
for i in range(m):
have[i]=(have[i],i)
have.sort()
req.sort()
now=[]
i=0
j=0
slen=len(req)
hlen=len(have)
ans=[0]*(n-1)
while j<hlen:
if i<slen and req[i][0]<=have[j][0]:
heapq.heappush(now,(req[i][1],req[i][2]))
i+=1
else:
try:
x=heapq.heappop(now)
except IndexError:
j+=1
continue
if x[0]<have[j][0]:
break
else:
ans[x[1]]=have[j][1]
j+=1
if i<slen or len(now)!=0 or j<hlen:
print('No')
else:
print('Yes')
print(' '.join([str(x+1) for x in ans]))
```
| 14,612 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Tags: data structures, greedy, sortings
Correct Solution:
```
#!/usr/bin/env python
# 556D_fug.py - Codeforces.com 556D Fug quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Input
The first line contains integers n and m - the number of islands and bridges.
Next n lines each contain two integers li and ri - the coordinates of the
island endpoints.
The last line contains m integer numbers a1..am - the lengths of the bridges
that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands
in the required manner, print on a single line "No" (without the quotes)
, otherwise print in the first line "Yes" (without the quotes), and in the
second line print n-1 numbers b1, bn-1, which mean that between islands
i and i+1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this
problem it is necessary to print "Yes" and "No" in correct case
"""
# Standard libraries
import unittest
import sys
import re
# Additional libraries
import heapq
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.list = args[0]
self.alist = args[1]
self.gn = len(self.list) - 1
# Sorted list of bridges
self.asrt = sorted((n, i) for i, n in enumerate(self.alist))
# List of gaps between islands
self.gaps = [()]*self.gn
prevli = self.list[0]
for i in range(self.gn):
li = self.list[i+1]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
self.gaps[i] = (min, max, i)
prevli = li
# Sorted list of gaps between islands
self.gsrt = sorted(self.gaps)
self.gmin = [n[0] for n in self.gsrt]
self.result = [None]*self.gn
self.heap = []
def iterate(self):
j = 0
for (b, i) in self.asrt:
# Traverse gmin array
while j < self.gn and self.gmin[j] <= b:
it = self.gsrt[j]
heapq.heappush(self.heap, (it[1], it[0], it[2]))
j += 1
# Update result and remove the element from lists
if self.heap:
(mmax, mmin, mi) = self.heap[0]
if mmin <= b and mmax >= b:
self.result[mi] = i + 1
heapq.heappop(self.heap)
yield
def calculate(self):
""" Main calcualtion function of the class """
for it in self.iterate():
pass
answer = ""
for (i, n) in enumerate(self.result):
if n is None:
return "No"
answer += (" " if i > 0 else "") + str(n)
return "Yes\n" + answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return input()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
list = [[int(s) for s in uinput().split()] for i in range(num[0])]
alist = [int(s) for s in uinput().split()]
# Decoding inputs into a list
inputs = [list, alist]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 100000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
x += 2
test += str(x) + " " + str(x+1) + "\n"
for i in range(size):
test += str(2) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
self.assertEqual(d.list[0][0], 1)
self.assertEqual(d.alist[0], 4)
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gaps[0], (2, 7, 0))
self.assertEqual(d.gsrt[0], (1, 3, 1))
iter = d.iterate()
next(iter)
self.assertEqual(d.gmin, [1, 2, 2])
self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)])
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
print(calculate())
```
| 14,613 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Tags: data structures, greedy, sortings
Correct Solution:
```
#!/usr/bin/env python
# 556D_fug.py - Codeforces.com 556D Fug quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Input
The first line contains integers n and m - the number of islands and bridges.
Next n lines each contain two integers li and ri - the coordinates of the
island endpoints.
The last line contains m integer numbers a1..am - the lengths of the bridges
that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands
in the required manner, print on a single line "No" (without the quotes)
, otherwise print in the first line "Yes" (without the quotes), and in the
second line print n-1 numbers b1, bn-1, which mean that between islands
i and i+1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this
problem it is necessary to print "Yes" and "No" in correct case
"""
# Standard libraries
import unittest
import sys
import re
# Additional libraries
import heapq
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.list = args[0]
self.alist = args[1]
self.gn = len(self.list) - 1
# Sorted list of bridges
self.asrt = sorted((n, i) for i, n in enumerate(self.alist))
# List of gaps between islands
self.gaps = []
prevli = self.list[0]
for i in range(self.gn):
li = self.list[i+1]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
self.gaps.append((min, max, i))
prevli = li
# Sorted list of gaps between islands
self.gsrt = sorted(self.gaps)
self.gmin = [n[0] for n in self.gsrt]
self.result = [None]*self.gn
self.heap = []
def iterate(self):
j = 0
for (b, i) in self.asrt:
# Traverse gmin array
while j < self.gn and self.gmin[j] <= b:
it = self.gsrt[j]
heapq.heappush(self.heap, (it[1], it[0], it[2]))
j += 1
# Update result and remove the element from lists
if self.heap:
(mmax, mmin, mi) = self.heap[0]
if mmin <= b and mmax >= b:
self.result[mi] = i + 1
heapq.heappop(self.heap)
yield
def calculate(self):
""" Main calcualtion function of the class """
for it in self.iterate():
pass
for n in self.result:
if n is None:
return "No"
answer = " ".join([str(n) for n in self.result])
return "Yes\n" + answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return input()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
list = [[int(s) for s in uinput().split()] for i in range(num[0])]
alist = [int(s) for s in uinput().split()]
# Decoding inputs into a list
inputs = [list, alist]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 20000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
x += 2
test += str(x) + " " + str(x+1) + "\n"
for i in range(size):
test += str(2) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
self.assertEqual(d.list[0][0], 1)
self.assertEqual(d.alist[0], 4)
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gaps[0], (2, 7, 0))
self.assertEqual(d.gsrt[0], (1, 3, 1))
iter = d.iterate()
next(iter)
self.assertEqual(d.gmin, [1, 2, 2])
self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)])
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
print(calculate())
```
| 14,614 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Tags: data structures, greedy, sortings
Correct Solution:
```
#!/usr/bin/env python
# 556D_fug.py - Codeforces.com 556D Fug quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Input
The first line contains integers n and m - the number of islands and bridges.
Next n lines each contain two integers li and ri - the coordinates of the
island endpoints.
The last line contains m integer numbers a1..am - the lengths of the bridges
that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands
in the required manner, print on a single line "No" (without the quotes)
, otherwise print in the first line "Yes" (without the quotes), and in the
second line print n-1 numbers b1, bn-1, which mean that between islands
i and i+1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this
problem it is necessary to print "Yes" and "No" in correct case
"""
# Standard libraries
import unittest
import sys
import re
# Additional libraries
import heapq
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.list = args[0]
self.alist = args[1]
self.gn = len(self.list) - 1
# Sorted list of bridges
self.asrt = sorted((n, i) for i, n in enumerate(self.alist))
# List of gaps between islands
self.gaps = []
prevli = self.list[0]
for i in range(self.gn):
li = self.list[i+1]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
self.gaps.append((min, max, i))
prevli = li
# Sorted list of gaps between islands
self.gsrt = sorted(self.gaps)
self.gmin = [n[0] for n in self.gsrt]
self.result = [None]*self.gn
self.heap = []
def iterate(self):
j = 0
for (b, i) in self.asrt:
# Traverse gmin array
while j < self.gn and self.gmin[j] <= b:
it = self.gsrt[j]
heapq.heappush(self.heap, (it[1], it[0], it[2]))
j += 1
# Update result and remove the element from lists
if self.heap:
(mmax, mmin, mi) = self.heap[0]
if mmin <= b and mmax >= b:
self.result[mi] = str(i + 1)
heapq.heappop(self.heap)
yield
def calculate(self):
""" Main calcualtion function of the class """
for it in self.iterate():
pass
for n in self.result:
if n is None:
return "No"
answer = "Yes\n"
answer += " ".join(self.result)
return answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return sys.stdin.readline()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
list = [[int(s) for s in uinput().split()] for i in range(num[0])]
alist = [int(s) for s in uinput().split()]
# Decoding inputs into a list
inputs = [list, alist]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 10000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
x += 2
test += str(x) + " " + str(x+1) + "\n"
for i in range(size):
test += str(2) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
self.assertEqual(d.list[0][0], 1)
self.assertEqual(d.alist[0], 4)
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gaps[0], (2, 7, 0))
self.assertEqual(d.gsrt[0], (1, 3, 1))
iter = d.iterate()
next(iter)
self.assertEqual(d.gmin, [1, 2, 2])
self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)])
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(calculate())
```
| 14,615 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Tags: data structures, greedy, sortings
Correct Solution:
```
#!/usr/bin/env python
# 556D_fug.py - Codeforces.com 556D Fug quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Input
The first line contains integers n and m - the number of islands and bridges.
Next n lines each contain two integers li and ri - the coordinates of the
island endpoints.
The last line contains m integer numbers a1..am - the lengths of the bridges
that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands
in the required manner, print on a single line "No" (without the quotes)
, otherwise print in the first line "Yes" (without the quotes), and in the
second line print n-1 numbers b1, bn-1, which mean that between islands
i and i+1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this
problem it is necessary to print "Yes" and "No" in correct case
"""
# Standard modules
import unittest
import sys
import re
# Additional modules
import bisect
###############################################################################
# Fastlist Class
###############################################################################
class Fastlist(object):
""" Fastlist representation """
def __init__(self, l=[], load=5000, sorted=0):
self._load = load
self._sorted = sorted
self._lists = []
self._starts = []
self._mins = []
self._insert_list()
self._irev = 0
self.extend(l)
def _index_location(self, index):
if len(self._lists[0]) == 0:
raise IndexError("List index out of range")
if index == 0:
return (0, 0)
if index == -1:
return (len(self._lists) - 1, len(self._lists[-1]) - 1)
if self._sorted:
raise RuntimeError("No index access to the sorted list, exc 0, -1")
length = len(self)
if index < 0:
index = length + index
if index >= length:
raise IndexError("List index out of range")
il = bisect.bisect_right(self._starts, index) - 1
return (il, index - self._starts[il])
def _insert_list(self, il=None):
if il is None:
il = len(self._lists)
self._lists.insert(il, [])
if self._sorted:
if il == 0:
self._mins.insert(il, None)
else:
self._mins.insert(il, self._lists[il-1][-1])
else:
if il == 0:
self._starts.insert(il, 0)
else:
start = self._starts[il-1] + len(self._lists[il-1])
self._starts.insert(il, start)
def _del_list(self, il):
del self._lists[il]
if self._sorted:
del self._mins[il]
else:
del self._starts[il]
def _rebalance(self, il):
illen = len(self._lists[il])
if illen >= self._load * 2:
self._insert_list(il)
self._even_lists(il)
if illen <= self._load * 0.2:
if il != 0:
self._even_lists(il-1)
elif len(self._lists) > 1:
self._even_lists(il)
def _even_lists(self, il):
tot = len(self._lists[il]) + len(self._lists[il+1])
if tot < self._load * 1:
self._lists[il] += self._lists[il+1]
self._del_list(il+1)
if self._sorted:
self._mins[il] = self._lists[il][0]
else:
half = tot//2
ltot = self._lists[il] + self._lists[il+1]
self._lists[il] = ltot[:half]
self._lists[il+1] = ltot[half:]
if self._sorted:
self._mins[il] = self._lists[il][0]
self._mins[il+1] = self._lists[il+1][0]
else:
self._starts[il+1] = self._starts[il] + len(self._lists[il])
def _obj_location(self, obj, l=0):
if not self._sorted:
raise RuntimeError("No by value access to an unserted list")
il = 0
if len(self._mins) > 1 and obj > self._mins[0]:
if l:
il = bisect.bisect_left(self._mins, obj) - 1
else:
il = bisect.bisect_right(self._mins, obj) - 1
if l:
ii = bisect.bisect_left(self._lists[il], obj)
else:
ii = bisect.bisect_right(self._lists[il], obj)
if ii == len(self._lists[il]) and il != len(self._lists) - 1:
ii = 0
il += 1
return (il, ii)
def insert(self, index, obj):
(il, ii) = self._index_location(index)
self._lists[il].insert(ii, obj)
for j in range(il + 1, len(self._starts)):
self._starts[j] += 1
self._rebalance(il)
def append(self, obj):
if len(self._lists[-1]) >= self._load:
self._insert_list()
self._lists[-1].append(obj)
if self._sorted and self._mins[0] is None:
self._mins[0] = self._lists[0][0]
def extend(self, iter):
for n in iter:
self.append(n)
def pop(self, index=None):
if index is None:
index = -1
(il, ii) = self._index_location(index)
item = self._lists[il].pop(ii)
if self._sorted:
if ii == 0 and len(self._lists[il]) > 0:
self._mins[il] = self._lists[il][0]
else:
for j in range(il + 1, len(self._starts)):
self._starts[j] -= 1
self._rebalance(il)
return item
def clear(self):
self._lists.clear()
self._starts.clear()
self._mins.clear()
self._insert_list()
def as_list(self):
return sum(self._lists, [])
def insort(self, obj, l=0):
(il, ii) = self._obj_location(obj, l)
self._lists[il].insert(ii, obj)
if ii == 0:
self._mins[il] = obj
self._rebalance(il)
def add(self, obj):
if self._sorted:
self.insort(obj)
else:
self.append(obj)
def insort_left(self, obj):
self.insort(obj, l=1)
def lower_bound(self, obj):
(self._il, self._ii) = self._obj_location(obj, l=1)
return self
def upper_bound(self, obj):
(self._il, self._ii) = self._obj_location(obj)
return self
def __str__(self):
return str(self.as_list())
def __setitem__(self, index, obj):
if isinstance(index, int):
(il, ii) = self._index_location(index)
self._lists[il][ii] = obj
elif isinstance(index, slice):
raise RuntimeError("Slice assignment is not supported")
def __getitem__(self, index):
if isinstance(index, int):
(il, ii) = self._index_location(index)
return self._lists[il][ii]
elif isinstance(index, slice):
rg = index.indices(len(self))
if rg[0] == 0 and rg[1] == len(self) and rg[2] == 1:
return self.as_list()
return [self.__getitem__(index) for index in range(*rg)]
def __iadd__(self, obj):
if self._sorted:
[self.insort(n) for n in obj]
else:
[self.append(n) for n in obj]
return self
def __delitem__(self, index):
if isinstance(index, int):
self.pop(index)
elif isinstance(index, slice):
rg = index.indices(len(self))
[self.__delitem__(rg[0]) for i in range(*rg)]
def __len__(self):
if self._sorted:
return sum([len(l) for l in self._lists])
return self._starts[-1] + len(self._lists[-1])
def __contains__(self, obj):
if self._sorted:
it = self.lower_bound(obj)
return not it.iter_end() and obj == it.iter_getitem()
else:
for n in self:
if obj == n:
return True
return False
def __bool__(self):
return len(self._lists[0]) != 0
def __iter__(self):
self._il = self._ii = self._irev = 0
return self
def __reversed__(self):
self._il = len(self._lists) - 1
self._ii = len(self._lists[self._il]) - 1
self._irev = 1
return self
def __next__(self):
if self._il in (-1, len(self._lists)) or len(self._lists[0]) == 0:
raise StopIteration("Iteration stopped")
item = self._lists[self._il][self._ii]
if not self._irev:
self._ii += 1
if self._ii == len(self._lists[self._il]):
self._il += 1
self._ii = 0
else:
self._ii -= 1
if self._ii == 0:
self._il -= 1
self._ii = len(self._lists[self._il])
return item
def iter_getitem(self):
return self._lists[self._il][self._ii]
def iter_end(self):
return (self._il == len(self._lists) - 1 and
self._ii == len(self._lists[self._il]))
def iter_del(self):
self.iter_pop()
def iter_pop(self):
item = self._lists[self._il].pop(self._ii)
if self._sorted:
if self._ii == 0 and len(self._lists[self._il]) > 0:
self._mins[self._il] = self._lists[self._il][0]
else:
for j in range(self._il + 1, len(self._starts)):
self._starts[j] -= 1
self._rebalance(self._il)
return item
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.gsrt = args[0]
self.asrt = args[1]
self.gn = args[2]
self.result = [0]*self.gn
self.a = Fastlist(self.asrt, load=500, sorted=1)
def calculate(self):
""" Main calcualtion function of the class """
for i in range(self.gn):
g = self.gsrt[i]
it = self.a.lower_bound((g[1], 0))
if not it.iter_end():
alb = it.iter_getitem()
if alb[0] > g[0]:
return "No"
self.result[g[2]] = alb[1]+1
it.iter_del()
else:
return "No"
answer = "Yes\n" + " ".join(str(n) for n in self.result)
return answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return sys.stdin.readline()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
gaps = []
prevli = [int(s) for s in uinput().split()]
for i in range(num[0] - 1):
li = [int(s) for s in uinput().split()]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
gaps.append((max, min, i))
prevli = li
alist = [(int(s), i) for i, s in enumerate(uinput().split())]
# Decoding inputs into a list
inputs = [sorted(gaps), sorted(alist), num[0]-1]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[(3, 1, 1), (5, 2, 2), (7, 3, 0)],
[(3, 2), (4, 0), (5, 1), (8, 3)], 3])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 200000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
test += str(x) + " " + str(x + i + 1) + "\n"
x += 2 * (i + 1)
for i in reversed(range(size)):
test += str(i) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[(1, 3, 1), (2, 5, 2), (3, 7, 0)],
[(3, 2), (4, 0), (5, 1), (8, 3)], 3])
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gsrt[0], (1, 3, 1))
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(calculate())
```
| 14,616 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Tags: data structures, greedy, sortings
Correct Solution:
```
#!/usr/bin/env python
# 556D_fug.py - Codeforces.com 556D Fug quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Input
The first line contains integers n and m - the number of islands and bridges.
Next n lines each contain two integers li and ri - the coordinates of the
island endpoints.
The last line contains m integer numbers a1..am - the lengths of the bridges
that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands
in the required manner, print on a single line "No" (without the quotes)
, otherwise print in the first line "Yes" (without the quotes), and in the
second line print n-1 numbers b1, bn-1, which mean that between islands
i and i+1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this
problem it is necessary to print "Yes" and "No" in correct case
"""
# Standard libraries
import unittest
import sys
import re
# Additional libraries
import heapq
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.list = args[0]
self.alist = args[1]
self.gn = len(self.list) - 1
# Sorted list of bridges
self.asrt = sorted((n, i) for i, n in enumerate(self.alist))
# List of gaps between islands
self.gaps = []
prevli = self.list[0]
for i in range(self.gn):
li = self.list[i+1]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
self.gaps.append((min, max, i))
prevli = li
# Sorted list of gaps between islands
self.gsrt = sorted(self.gaps)
self.gmin = [n[0] for n in self.gsrt]
self.result = [None]*self.gn
self.heap = []
def iterate(self):
j = 0
for (b, i) in self.asrt:
# Traverse gmin array
while j < self.gn and self.gmin[j] <= b:
it = self.gsrt[j]
heapq.heappush(self.heap, (it[1], it[0], it[2]))
j += 1
# Update result and remove the element from lists
if self.heap:
(mmax, mmin, mi) = self.heap[0]
if mmin <= b and mmax >= b:
self.result[mi] = i + 1
heapq.heappop(self.heap)
yield
def calculate(self):
""" Main calcualtion function of the class """
for it in self.iterate():
pass
for n in self.result:
if n is None:
return "No"
answer = " ".join([str(n) for n in self.result])
return "Yes\n" + answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return sys.stdin.readline()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
list = [[int(s) for s in uinput().split()] for i in range(num[0])]
alist = [int(s) for s in uinput().split()]
# Decoding inputs into a list
inputs = [list, alist]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 20000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
x += 2
test += str(x) + " " + str(x+1) + "\n"
for i in range(size):
test += str(2) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
self.assertEqual(d.list[0][0], 1)
self.assertEqual(d.alist[0], 4)
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gaps[0], (2, 7, 0))
self.assertEqual(d.gsrt[0], (1, 3, 1))
iter = d.iterate()
next(iter)
self.assertEqual(d.gmin, [1, 2, 2])
self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)])
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(calculate() + "\n")
```
| 14,617 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Submitted Solution:
```
# Standard libraries
import unittest
import sys
import re
# Additional libraries
import heapq
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.list = args[0]
self.alist = args[1]
self.gn = len(self.list) - 1
# Sorted list of bridges
self.asrt = sorted((n, i) for i, n in enumerate(self.alist))
# List of gaps between islands
self.gaps = []
prevli = self.list[0]
for i in range(self.gn):
li = self.list[i+1]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
self.gaps.append((min, max, i))
prevli = li
# Sorted list of gaps between islands
self.gsrt = sorted(self.gaps)
self.gmin = [n[0] for n in self.gsrt]
self.result = [None]*self.gn
self.heap = []
def iterate(self):
j = 0
for (b, i) in self.asrt:
# Traverse gmin array
while j < self.gn and self.gmin[j] <= b:
it = self.gsrt[j]
heapq.heappush(self.heap, (it[1], it[0], it[2]))
j += 1
# Update result and remove the element from lists
if self.heap:
(mmax, mmin, mi) = self.heap[0]
if mmin <= b and mmax >= b:
self.result[mi] = i + 1
heapq.heappop(self.heap)
yield
def calculate(self):
""" Main calcualtion function of the class """
for it in self.iterate():
pass
for n in self.result:
if n is None:
return "No"
answer = " ".join([str(n) for n in self.result])
return "Yes\n" + answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return input()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
list = [[int(s) for s in uinput().split()] for i in range(num[0])]
alist = [int(s) for s in uinput().split()]
# Decoding inputs into a list
inputs = [list, alist]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 20000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
x += 2
test += str(x) + " " + str(x+1) + "\n"
for i in range(size):
test += str(2) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
self.assertEqual(d.list[0][0], 1)
self.assertEqual(d.alist[0], 4)
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gaps[0], (2, 7, 0))
self.assertEqual(d.gsrt[0], (1, 3, 1))
iter = d.iterate()
next(iter)
self.assertEqual(d.gmin, [1, 2, 2])
self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)])
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
print(calculate())
```
Yes
| 14,618 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Submitted Solution:
```
#!/usr/bin/env python
# 556D_fug.py - Codeforces.com 556D Fug quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Input
The first line contains integers n and m - the number of islands and bridges.
Next n lines each contain two integers li and ri - the coordinates of the
island endpoints.
The last line contains m integer numbers a1..am - the lengths of the bridges
that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands
in the required manner, print on a single line "No" (without the quotes)
, otherwise print in the first line "Yes" (without the quotes), and in the
second line print n-1 numbers b1, bn-1, which mean that between islands
i and i+1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this
problem it is necessary to print "Yes" and "No" in correct case
"""
# Standard libraries
import unittest
import sys
import re
# Additional libraries
import bisect
import heapq
###############################################################################
# Fug Class
###############################################################################
class Fug:
""" Fug representation """
def __init__(self, args):
""" Default constructor """
self.list = args[0]
self.alist = args[1]
self.gn = len(self.list) - 1
# Sorted list of bridges
self.asrt = sorted((n, i) for i, n in enumerate(self.alist))
# List of gaps between islands
self.gaps = []
prevli = self.list[0]
for i in range(self.gn):
li = self.list[i+1]
min = li[0] - prevli[1]
max = li[1] - prevli[0]
self.gaps.append((min, max, i))
prevli = li
# Sorted list of gaps between islands
self.gsrt = sorted(self.gaps)
self.gmin = []
self.result = []
self.heap = []
for n in self.gsrt:
self.gmin.append(n[0])
self.result.append(None)
def iterate(self):
j = 0
for (b, i) in self.asrt:
# Traverse gmin array
while j < self.gn and self.gmin[j] <= b:
it = self.gsrt[j]
heapq.heappush(self.heap, (it[1], it[0], it[2]))
j += 1
# Update result and remove the element from lists
if self.heap:
(mmax, mmin, mi) = self.heap[0]
if mmin <= b and mmax >= b:
self.result[mi] = i + 1
heapq.heappop(self.heap)
yield
def calculate(self):
""" Main calcualtion function of the class """
for it in self.iterate():
pass
answer = ""
for (i, n) in enumerate(self.result):
if n is None:
return "No"
answer += (" " if i > 0 else "") + str(n)
return "Yes\n" + answer
###############################################################################
# Executable code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return input()
# Getting string inputs. Place all uinput() calls here
num = [int(s) for s in uinput().split()]
list = [[int(s) for s in uinput().split()] for i in range(num[0])]
alist = [int(s) for s in uinput().split()]
# Decoding inputs into a list
inputs = [list, alist]
return inputs
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Fug(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "4 4\n1 4\n7 8\n9 10\n12 14\n4 5 3 8"
self.assertEqual(calculate(test), "Yes\n2 3 1")
self.assertEqual(
get_inputs(test),
[[[1, 4], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
# My tests
test = "5 5\n1 1\n2 7\n8 8\n10 10\n16 16\n1 1 5 6 2"
self.assertEqual(calculate(test), "Yes\n1 2 5 4")
# Other tests
test = "2 2\n11 14\n17 18\n2 9"
self.assertEqual(calculate(test), "No")
# Other tests
test = (
"2 1\n1 1\n1000000000000000000 1000000000000000000" +
"\n999999999999999999")
self.assertEqual(calculate(test), "Yes\n1")
test = ("5 9\n1 2\n3 3\n5 7\n11 13\n14 20\n2 3 4 10 6 2 6 9 5")
self.assertEqual(calculate(test), "Yes\n1 6 3 2")
size = 50000
test = str(size) + " " + str(size) + "\n"
x = size*1000
for i in range(size):
x += 2
test += str(x) + " " + str(x+1) + "\n"
for i in range(size):
test += str(2) + " "
self.assertEqual(calculate(test)[0], "Y")
def test_Fug_class__basic_functions(self):
""" Fug class basic functions testing """
# Constructor test
d = Fug([[[1, 5], [7, 8], [9, 10], [12, 14]], [4, 5, 3, 8]])
self.assertEqual(d.list[0][0], 1)
self.assertEqual(d.alist[0], 4)
# Sort bridges
self.assertEqual(d.asrt[0], (3, 2))
# Sort Gaps
self.assertEqual(d.gaps[0], (2, 7, 0))
self.assertEqual(d.gsrt[0], (1, 3, 1))
iter = d.iterate()
next(iter)
self.assertEqual(d.gmin, [1, 2, 2])
self.assertEqual(d.heap, [(5, 2, 2), (7, 2, 0)])
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
print(calculate())
```
Yes
| 14,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Submitted Solution:
```
from sys import stdin
import heapq
n,m = [int(x) for x in stdin.readline().split()]
islands = []
for i in range(n):
islands.append([int(x) for x in stdin.readline().split()])
gaps = []
for i in range(n-1):
gaps.append((islands[i+1][0]-islands[i][1], islands[i+1][1]-islands[i][0]))
bridges = [int(x) for x in stdin.readline().split()]
bridges = sorted([(bridges[x],x+1) for x in range(m)])
gaps2 = []
for l,r in gaps:
low = 0
high = m-1
while low <= high:
mid = (low+high)//2
if bridges[mid][0] < l:
low = mid+1
else:
high = mid-1
trueL = low
low = 0
high = m-1
while low <= high:
mid = (low+high)//2
if bridges[mid][0] > r:
high = mid-1
else:
low = mid+1
trueR = high
gaps2.append((trueL,trueR))
gaps2 = [(gaps2[x], x) for x in range(n-1)]
gaps2.sort()
final = [0 for x in range(n-1)]
ind = 0
q = []
valid = True
for x in range(m):
i2 = bridges[x][1]
if ind < n-1:
while gaps2[ind][0][0] == x:
heapq.heappush(q, (gaps2[ind][0][1], gaps2[ind][1]))
ind += 1
if ind >= n-1:
break
if not q:
continue
nxt,ind = heapq.heappop(q)
if nxt < x:
valid = False
break
else:
final[ind] = i2
if 0 in final:
valid = False
if valid:
print('Yes')
print(' '.join([str(x) for x in final]))
else:
print('No')
```
No
| 14,620 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Submitted Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
def test(i, island, bridge, n, m):
if i == n-1:
return [True, []]
flag = [False, []]
lmax = island[i+1][1] - island[i][0]
lmin = island[i+1][0] - island[i][1]
for j in range(m):
if bridge[j] > 0 and bridge[j] <= lmax and bridge[j] >= lmin:
buf = bridge[j]
bridge[j] = 0
flag = test(i+1, island, bridge, n, m)
if flag[0] == True:
flag[1].append(j)
break
bridge[j] = buf
return flag
(n, m) = (int(i) for i in input().split())
if m < n-1 :
print("No")
else:
island = []
for i in range(n):
island.append([int(i) for i in input().split()])
bridge = [int(i) for i in input().split()]
start = time.time()
ans = test(0, island, bridge, n, m);
if ans[0] == True:
print("Yes")
for i in range(n-1):
print(ans[1][i]+1, end=" ")
print()
else:
print("No")
finish = time.time()
#print(finish - start)
```
No
| 14,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Submitted Solution:
```
n, m = (int(x) for x in input().split())
coord, dest, br = [], [], []
for i in range(n):
coord.append(tuple(int(x) for x in input().split()))
temp = input().split()
br = [(int(temp[x]), x + 1) for x in range(len(temp))]
coord.sort()
for i in range(len(coord) - 1):
dest.append((coord[i+1][0] - coord[i][1], coord[i+1][1] - coord[i][0], i))
dest.sort(key = lambda x: (x[1], x[0]))
br.sort()
def f(dest, br):
brIt = len(br) - 1
res = [0 for i in range(len(dest))]
for dIt in range(len(dest) - 1, -1, -1):
if brIt < 0:
print("No")
return
while not (dest[dIt][0] <= br[brIt][0] <= dest[dIt][1]):
brIt -= 1
if brIt < 0:
print("No")
return
res[dest[dIt][2]] = brIt
brIt -= 1
print("Yes")
print(" ".join(str(x) for x in res))
f(dest, br)
```
No
| 14,622 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.
The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.
To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a.
The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.
Input
The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges.
Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints.
The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.
Output
If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.
If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.
Examples
Input
4 4
1 4
7 8
9 10
12 14
4 5 3 8
Output
Yes
2 3 1
Input
2 2
11 14
17 18
2 9
Output
No
Input
2 1
1 1
1000000000000000000 1000000000000000000
999999999999999999
Output
Yes
1
Note
In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.
In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Submitted Solution:
```
islands, nbridges = map(int, input().split(' '))
data = []
for _ in range(islands):
data.append(tuple(map(int, input().split(' '))))
bridges = iter(sorted(enumerate(map(int, input().split(' '))), key=lambda x: x[1]))
lengths = []
for i in range(islands-1):
outer = data[i+1][1] - data[i][0]
inner = data[i+1][0] - data[i][1]
lengths.append((inner, outer, i))
lengths = sorted(lengths)
ans = []
try:
for inner, outer, i in lengths:
b = next(bridges)
while not inner <= b[1] <= outer:
b = next(bridges)
ans.append((i, b[0]))
print('Yes')
print(' '.join(str(i[1]+1) for i in sorted(ans)))
except StopIteration:
print('No')
```
No
| 14,623 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Tags: implementation, math
Correct Solution:
```
def Swap(a,b):
return (b,a)
a,b = map(int,input().split())
if a > b:
a,b = Swap(a,b)
print("%d %d" %(a,(b - a) //2))
```
| 14,624 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Tags: implementation, math
Correct Solution:
```
import math
n,m=map(int,input().split())
if n>m:
print(m,int((n-m)/2))
elif m>n:
print(n,int((m-n)/2))
else:
print(n,0)
```
| 14,625 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Tags: implementation, math
Correct Solution:
```
z = [int(s) for s in input().split()]
a, b = z[0], z[1]
if a > b:
print(b, (a - b) // 2)
elif a<b:
print(a, (b - a) // 2)
elif a == b:
print(a, 0)
```
| 14,626 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Tags: implementation, math
Correct Solution:
```
n,m=map(int,input().split(" "))
a=0
if n>=m:
a=m
else:
a=n
b=(max(n,m)-a)//2
print(f"{a} {b}")
```
| 14,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Tags: implementation, math
Correct Solution:
```
a, b = map(int, input().split())
first = min(a, b)
second = max((a-first)//2, (b-first)//2)
print(first, second)
```
| 14,628 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Tags: implementation, math
Correct Solution:
```
n, m = map(int, input().split())
print(min(n, m), end = ' ')
print((max(n, m) - min(n, m)) // 2)
```
| 14,629 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Tags: implementation, math
Correct Solution:
```
a = input().split()
b = int(a[1])
a = int(a[0])
print(min(a,b),abs(a-b)//2)
```
| 14,630 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Tags: implementation, math
Correct Solution:
```
def main(b, r):
minim = min([b,r])
maxim = max([b,r])
if(b!=r):
if ((maxim - minim) % 2 != 0):
cols = int((maxim - minim - 1) / 2)
else:
cols = int((maxim - minim) /2)
return ' '.join([str(minim), str(cols)])
else:
return ' '.join([str(b), str('0')])
inp = input().split(' ')
blue = int(inp[0])
red = int(inp[1])
print(main(blue, red))
```
| 14,631 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Submitted Solution:
```
x=list(map(int,input().split()))
print(min(x),abs(x[0]-x[1])//2)
```
Yes
| 14,632 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Submitted Solution:
```
A = [int(k) for k in input().split()]
B = [min(A[0],A[1]),(max(A[0],A[1])-min(A[0],A[1]))//2]
for i in range(2):
B[i] = str(B[i])
print(' '.join(B))
```
Yes
| 14,633 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Submitted Solution:
```
s,k=map(int,input().split())
b=abs(s-k)//2
a=abs((s+k)//2-b)
print(a,b)
```
Yes
| 14,634 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Submitted Solution:
```
a,b=sorted([int(x) for x in input().split()])
print(a,(b-a)//2)
```
Yes
| 14,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Submitted Solution:
```
a, b = map(int,input().split())
if a>b:
diff_socks = (min(a,b))
sim_socks = b - a%b
print(diff_socks,sim_socks,end=' ')
elif b>a:
diff_socks = (min(a,b))
sim_socks = a - a%b
print(diff_socks,sim_socks,end=' ')
elif a==b:
diff_socks = (min(a,b))
sim_socks = (b - a%b)-b
print(diff_socks,sim_socks,end=' ')
```
No
| 14,636 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Submitted Solution:
```
a,b = map(int,input().split())
tim = a - b
z = tim/2
z = int(z)
if(a > b):
print(b, z)
else:
print(a, z)
```
No
| 14,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Submitted Solution:
```
a , b = map(int, input().split())
if a > b:
x = b
y = int((a-b)/2)
print(str(x) + ' ' + str(y))
elif b>a:
x = a
y = int((b-a)/2)
print(str(x)+' '+ str(y))
if a == b:
x =(int(a/2))
print(str(x) + ' '+ '0')
```
No
| 14,638 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
Input
The single line of the input contains two positive integers a and b (1 ≤ a, b ≤ 100) — the number of red and blue socks that Vasya's got.
Output
Print two space-separated integers — the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.
Examples
Input
3 1
Output
1 1
Input
2 3
Output
2 0
Input
7 3
Output
3 2
Note
In the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Submitted Solution:
```
a,b=map(int,input().split())
if a>=b:
k=b
m=a//2
elif a<b:
k=a
m=b//2
print(k,m)
```
No
| 14,639 |
Provide tags and a correct Python 3 solution for this coding contest problem.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().split())
print(int((((n * (k - 1) + 1)) + ((n - 1) * (n - k + 1)) / 2) * n))
for i in range(n):
curr = []
for j in range(n):
if j + 1 == k:
curr.append((n * (k - 1) + 1) + i * (n - k + 1))
elif j + 1 > k:
curr.append((n * (k - 1) + 1) + i * (n - k + 1) + (j + 1 - k))
else:
curr.append(i * (k - 1) + j + 1)
print(' '.join(map(str, curr)))
```
| 14,640 |
Provide tags and a correct Python 3 solution for this coding contest problem.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Tags: constructive algorithms, implementation
Correct Solution:
```
sLine = input()
sSplit = sLine.split()
n = int(sSplit[0])
k = int(sSplit[1])
v = []
for i in range(n) :
v.append([])
for j in range(n) :
v[i].append(0)
x1 = n * n
x2 = 1
for i in range(n) :
for j in range(n-1, (k-1)-1, -1) :
v[i][j] = x1
x1 -= 1
for j in range(0, (k-1), 1) :
v[i][j] = x2
x2 += 1
nSum = 0
for i in range(n) :
nSum += v[i][k-1]
print(nSum)
for i in range(n) :
for j in range(n) :
print(v[i][j], end='')
if j == n - 1 :
print('')
else :
print(' ', end='')
```
| 14,641 |
Provide tags and a correct Python 3 solution for this coding contest problem.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().split())
k -= 1
answer = [[0] * n for i in range(n)]
cur = 1
for i in range(n):
for j in range(k):
answer[i][j] = cur
cur += 1
for i in range(n):
for j in range(k, n):
answer[i][j] = cur
cur += 1
summa = 0
for i in range(n):
summa += answer[i][k]
print(summa)
for i in range(n):
print(*answer[i])
```
| 14,642 |
Provide tags and a correct Python 3 solution for this coding contest problem.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().split())
a = []
for i in range(1, (n*(k-1)) + 1):
a.append(i)
a = a[::-1]
lst = []
for i in range((n*(k-1)) + 1, (n*n) + 1):
lst.append(i)
lst = lst[::-1]
s = 0
ans = ""
for i in range(1, n + 1):
for j in range(1, n + 1):
if j < k:
ans += str(a.pop()) + " "
else:
if j == k:
s += lst[-1]
ans += str(lst.pop()) + " "
ans += "\n"
print(s)
print(ans)
```
| 14,643 |
Provide tags and a correct Python 3 solution for this coding contest problem.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().split())
sol = [[0] * n for _ in range(n)]
res = 0
c = 1
for j in range(k - 1):
for i in range(n):
sol[i][j] = c
c += 1
for i in range(n):
for j in range(k - 1, n):
sol[i][j] = c
c += 1
for i in range(n):
res += sol[i][k - 1]
print(res)
for line in sol:
for col in line:
print(col, end=" ")
print()
```
| 14,644 |
Provide tags and a correct Python 3 solution for this coding contest problem.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Tags: constructive algorithms, implementation
Correct Solution:
```
n, m = map(int, input().split())
n1, n2 = 1, (m - 1) * n + 1
ans = 0
print(n * (n - 1) // 2 * (n - m + 1) + n2 * n)
for i in range(n):
j = 0
while j < m - 1:
print(n1, end=' ')
n1 += 1
j += 1
while j < n:
print(n2, end=' ')
n2 += 1
j += 1
print()
```
| 14,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Tags: constructive algorithms, implementation
Correct Solution:
```
n,k=map(int,input().split())
ans=((n*n)-(n-k))
test=ans
op=[n*n-(n-k)]
op2=[]
count=[]
for i in range(1,n):
ans+=test-i*(n-k+1)
op.append(test-i*(n-k+1))
print(ans)
for i in range(n):
count.append(k+i*n)
pos=1
j=1
op=sorted(op)
#print(op)
if n==1 and k==1:
print('1')
else:
if k==1:
for i in range(n):
print(op[i],end= ' ')
for q in range(n-2):
print(op[i]+q+1,end= ' ')
print(op[i]+n-1)
elif k==n:
for i in range(n):
for q in range(i*(n-1)+1,(i+1)*(n-1)+1):
print(q,end=' ')
print(op[i])
else:
while j<=(k-1)*n:
for i in range(k-1):
print(j,end=' ')
pos+=1
j+=1
#print('pos is',pos)
print(op[pos//n],end=' ')
now=op[pos//n]
pos+=1
for i in range(k+1,n):
now+=1
print(now,end=' ')
pos+=1
print(now+1)
pos+=1
```
| 14,646 |
Provide tags and a correct Python 3 solution for this coding contest problem.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().split())
a=[]
for i in range(n):
a.append([])
for j in range(n):
a[i].append(0)
c = 1
for i in range(n):
for j in range(k - 1):
a[i][j] = c
c += 1
for i in range(n):
for j in range(k - 1, n):
a[i][j] = c
c += 1
ans = 0
for i in range(n):
ans += a[i][k - 1]
print(ans)
for i in range(n):
print (" ".join(map(str, a[i])))
```
| 14,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Submitted Solution:
```
def main():
(n, k) = (int(x) for x in input().split())
(total, table) = solver(n, k)
print(total)
for row in range(n):
for col in range(n):
print(table[row][col], end = " ")
print()
def solver(n, k):
col = k - 1
smallest = col * n + 1
table = [list(range(col * row + 1, col * (row + 1) + 1)) +
list(range((n - col) * row + smallest, (n - col) * (row + 1) + smallest))
for row in range(n)]
total = n * smallest + n * (n - 1) * (n - col) // 2
return (total, table)
#print(solver(5, 2))
main()
```
Yes
| 14,648 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Submitted Solution:
```
def main():
n, k = [int(t) for t in input().split()]
k -= 1
lst = [[0 for t in range(n)] for t in range(n)]
for col in range(n-1, k-1, -1):
for row in range(n):
lst[row][col] = n*n - (n-1-col) - row*(n-k)
for col in range(k-1, -1, -1):
for row in range(n):
lst[row][col] = n*k - (k-1-col) - row*k
print(sum([lst[i][k] for i in range(n)]))
out = "\n".join(" ".join(str(v) for v in lst[i]) for i in range(n))
print(out)
main()
# PYTHON3!!
```
Yes
| 14,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Submitted Solution:
```
n,k=map(int,input().split())
print(n*(n*n +(k-2)*n+k+1)//2)
t1=[([0]*n) for i in range(n)]
for j in range(k-1):
for i in range(n):
t1[i][j]=i+1+n*j
for i in range(n):
for j in range(k-1,n):
t1[i][j]=j+i*(n-k+1)+n*(k-1)+2-k
for i in range(n):
print(' '.join(str(j) for j in t1[i]))
```
Yes
| 14,650 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Submitted Solution:
```
string = input()
numbers = string.split()
a, b = int(numbers[0]), int(numbers[1])
rows = [[0 for x in range(a)] for x in range(a)]
p = a ** 2 + 1
s = 1
n = 0
for x in range(a):
p -= a - b + 1
t = s
for y in range(b - 1):
rows[x][y] = t
t += 1
q = p
for y in range(b - 1, a):
rows[x][y] = q
q += 1
s += b - 1
n += p
print(n)
for x in rows:
print(" ".join(map(str, x)))
```
Yes
| 14,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Submitted Solution:
```
string = input()
numbers = string.split()
a, b = int(numbers[0]), int(numbers[1])
rows = [[0 for x in range(a)] for x in range(a)]
p = a ** 2 + 1
s = 1
for x in range(a):
p -= a - b + 1
t = s
for y in range(b - 1):
rows[x][y] = t
t += 1
q = p
for y in range(b - 1, a):
rows[x][y] = q
q += 1
s += b - 1
for x in rows:
print(" ".join(map(str, x)))
```
No
| 14,652 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Submitted Solution:
```
n, k = map(int, input().split())
arr = [[0 for i in range(n)] for j in range(n)]
c = n * n
s = 0
for i in range(n):
#arr[i][n - 1] = c
#c -= 1
for j in range(n - 1, k - 2, -1):
arr[i][j] = c
c -= 1
s += c + 1
for i in range(n):
for j in range(k - 1):
arr[i][j] = c
c -= 1
print(s)
for i in arr:
print(*i)
```
No
| 14,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Submitted Solution:
```
n, k = map(int, input().split(' '))
ans = [[0 for i in range(n)] for j in range(n)]
cur = n ** 2
for i in range(n):
for j in range(k-1, n):
j = n + k - 2 - j
ans[i][j] = cur
cur -= 1
cur = 1
for i in range(n):
for j in range(k-1):
ans[i][j] = cur
cur += 1
for row in ans:
print(' '.join(map(str, row)))
```
No
| 14,654 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.
Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:
* every integer from 1 to n2 appears in the table exactly once;
* in each row numbers are situated in increasing order;
* the sum of numbers in the k-th column is maximum possible.
Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.
Output
First print the sum of the integers in the k-th column of the required table.
Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.
If there are multiple suitable table, you are allowed to print any.
Examples
Input
4 1
Output
28
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input
5 3
Output
85
5 6 17 18 19
9 10 23 24 25
7 8 20 21 22
3 4 14 15 16
1 2 11 12 13
Submitted Solution:
```
n,k=map(int,input().split())
m=1
q=n*(k-1)
q+=1
mat=[[0]*n]*n
for i in range(n):
for j in range(n):
if j<k-1:
mat[i][j]=m
print(mat[i][j],'',end='')
m+=1
elif j>=k-1:
mat[i][j]=q
print(mat[i][j],'',end='')
q+=1
print('')
```
No
| 14,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two positive integers are coprime if and only if they don't have a common divisor greater than 1.
Some bear doesn't want to tell Radewoosh how to solve some algorithmic problem. So, Radewoosh is going to break into that bear's safe with solutions. To pass through the door, he must enter a permutation of numbers 1 through n. The door opens if and only if an entered permutation p1, p2, ..., pn satisfies:
<image>
In other words, two different elements are coprime if and only if their indices are coprime.
Some elements of a permutation may be already fixed. In how many ways can Radewoosh fill the remaining gaps so that the door will open? Print the answer modulo 109 + 7.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 1 000 000).
The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n) where pi = 0 means a gap to fill, and pi ≥ 1 means a fixed number.
It's guaranteed that if i ≠ j and pi, pj ≥ 1 then pi ≠ pj.
Output
Print the number of ways to fill the gaps modulo 109 + 7 (i.e. modulo 1000000007).
Examples
Input
4
0 0 0 0
Output
4
Input
5
0 0 1 2 0
Output
2
Input
6
0 0 1 2 0 0
Output
0
Input
5
5 3 4 2 1
Output
0
Note
In the first sample test, none of four element is fixed. There are four permutations satisfying the given conditions: (1,2,3,4), (1,4,3,2), (3,2,1,4), (3,4,1,2).
In the second sample test, there must be p3 = 1 and p4 = 2. The two permutations satisfying the conditions are: (3,4,1,2,5), (5,4,1,2,3).
Submitted Solution:
```
n = int(input())
p = list(map(int,input().split()))
MOD = 1000000007
if n <= 5:
from itertools import permutations
from math import gcd
ans = 0
for perm in permutations(range(1,n + 1),n):
flag = True
for i in range(n):
if p[i] != perm[i] and p[i] != 0:
flag = False
break
for i in range(n):
for j in range(n):
if i == j:
continue
if (gcd(perm[i],perm[j]) == 1 and gcd(i + 1,j + 1) != 1) or (gcd(perm[i],perm[j]) != 1 and gcd(i + 1,j + 1) == 1):
flag = False
if flag:
ans += 1
print(ans)
else:
def prime_sieve(n):
"""returns a sieve of primes >= 5 and < n"""
flag = n % 6 == 2
sieve = bytearray((n // 3 + flag >> 3) + 1)
for i in range(1, int(n**0.5) // 3 + 1):
if not (sieve[i >> 3] >> (i & 7)) & 1:
k = (3 * i + 1) | 1
for j in range(k * k // 3, n // 3 + flag, 2 * k):
sieve[j >> 3] |= 1 << (j & 7)
for j in range(k * (k - 2 * (i & 1) + 4) // 3, n // 3 + flag, 2 * k):
sieve[j >> 3] |= 1 << (j & 7)
return sieve
def prime_list(n):
"""returns a list of primes <= n"""
res = []
if n > 1:
res.append(2)
if n > 2:
res.append(3)
if n > 4:
sieve = prime_sieve(n + 1)
res.extend(3 * i + 1 | 1 for i in range(1, (n + 1) // 3 + (n % 6 == 1)) if not (sieve[i >> 3] >> (i & 7)) & 1)
return res
pList = prime_list(n)
largePand1 = [False] * n
largePand1[0] = True
largePand1Cnt = 1
for elem in pList:
if elem > n // 2:
largePand1[elem - 1] = True
largePand1Cnt += 1
flag = True
fixed = 0
for i in range(n):
if p[i] == 0:
continue
else:
if largePand1[i - 1]:
fixed += 1
elif i + 1 == p[i]:
pass
else:
flag = False
if not flag:
print(0)
else:
ans = 1
for i in range(1,largePand1Cnt - fixed + 1):
ans *= i
ans %= MOD
print(ans)
```
No
| 14,656 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Tags: implementation, math
Correct Solution:
```
lst = input().split()
n = int(lst[0])
k = int(lst[1])
t = int(lst[2])
full = n*k
points = int(n*k*t/100)
result = []
while full > 0:
if points >= k:
result.append(str(k))
elif points > 0:
result.append(str(int(points)))
else:
result.append('0')
full -= k
points -= k
print(' '.join(result))
```
| 14,657 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Tags: implementation, math
Correct Solution:
```
from math import floor
(n, k, t) = list(map(int, input().split()))
t = floor(t * n * k / 100)
sat = t // k
part = t % k
s = (str(k) + " ") * sat
if (part > 0):
s += (str(part) + " ")
sat += 1
s += (str(0) + " ") * (n - sat)
print(s)
```
| 14,658 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Tags: implementation, math
Correct Solution:
```
n, k, t = map(int, input().split())
p = int((t/100)*(n*k))
f = p//k
for x in range(f):
print(k, end=' ')
p -= f*k
if p > 0:
print(p, end=' ')
f+=1
for x in range(n-f):
print("0", end=' ')
```
| 14,659 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Tags: implementation, math
Correct Solution:
```
import math
#n=int(input())
#lst = list(map(int, input().strip().split(' ')))
n,k,t = map(int, input().strip().split(' '))
x1=math.floor((t*n*k)/100)
c=0
f=0
for j in range(n):
c+=k
if f==1:
print(0,end=" ")
else:
if c<=x1:
print(k,end=" ")
elif c>x1:
c-=k
print(x1-c,end=" ")
f=1
```
| 14,660 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Tags: implementation, math
Correct Solution:
```
#codeforces_71B
gi = lambda : list(map(int,input().split()))
n,k,t = gi()
t = (n*k*t)//100
while t > k:
print(k,end=" ")
t -= k
n -= 1
print(t,end=" ")
n -= 1
while n:
print(0,end=" ")
n -= 1
```
| 14,661 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Tags: implementation, math
Correct Solution:
```
a = input().split(" ")
n = int(a[0])
k = int(a[1])
t = int(a[2]) / 100
loop = 1
output = ""
sumTotal = int(t * n * k)
while(loop <= n):
if(loop / n <= t):
output += str(k)
elif(((loop - 1) / n < t) and (loop / n > t)):
between = sumTotal - ((loop - 1) * k)
output += str(between)
else:
output += "0"
output += " "
loop += 1
print(output)
```
| 14,662 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Tags: implementation, math
Correct Solution:
```
x = input()
a,b,c=[int(i) for i in x.split(" ")]
proz = c/100
anz = a*b
volle = int(proz*anz/b)
rest = int(proz*anz/b%1*b)
res = ""
for i in range(volle):
res = res + str(b) + " "
if(a-volle != 0):
res = res + str(rest) + " "
for i in range(a-volle-1):
res = res + "0 "
print(res)
```
| 14,663 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Tags: implementation, math
Correct Solution:
```
def readln(): return tuple(map(int, input().split()))
n, k, t = readln()
for i in range(n):
for p in range(0, k + 1):
if 100 * (i * k + p) <= n * k * t < 100 * (i * k + p + 1):
print(*([k] * i + [p] + [0]*(n - i - 1)))
import sys
sys.exit(0)
```
| 14,664 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Submitted Solution:
```
n,k,t=map(int,input().split())
ok=(n*k*t)//100
ans=[]*n
while k<=ok:
ans.append(k)
ok-=k
if ok==0:
final=ans+[0]*(n-len(ans))
else:
final=ans+[ok]+[0]*(n-len(ans)-1)
print(*final)
```
Yes
| 14,665 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Submitted Solution:
```
n,k,t=map(int,input().split())
total=n*k
t=int(total*(t/100))
for i in range(1,n+1):
if t>k:
print(k,end=" ")
t=t-k
elif 0<t<=k:
print(t,end=" ")
t-=t
else:
print(0,end=" ")
```
Yes
| 14,666 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Submitted Solution:
```
def process(n,k,t):
for i in range(1,n+1):
for l in range(0,k+1):
b1,b2 = ((i-1)*k + l)/(n*k),((i-1)*k + 1 + l)/(n*k)
if(b1<=t/100<b2):
for j in range(1,i):
print(k,end= ' ')
print(l,end = ' ')
for j in range(i+1,n+1):
print(0,end= ' ')
return
n, k, t = map(int,input().split())
process(n,k,t)
```
Yes
| 14,667 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Submitted Solution:
```
val = list(map(int,input().split()))
eachBar = val[0]
maxeachBar = val[1]
percentValue = val[2]
presentmaxvalue = int(eachBar * maxeachBar * (percentValue/100))
a,b = divmod(presentmaxvalue,maxeachBar)
arr = []
for ans in range(a):
arr.append(maxeachBar)
if b != 0:
arr.append(b)
for y in range(eachBar-a-1):
arr.append(0)
else:
for y in range(eachBar-a):
arr.append(0)
print(*arr)
```
Yes
| 14,668 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Submitted Solution:
```
from math import floor
n, k, t = map(int, input().split())
answer = ""
filled = 100/n
for i in range(1,n+1):
if filled <= t:
answer += str(k) + " "
t = t - filled
elif filled > t:
answer += str(floor(t)) + " "
t = 0
else:
answer += str(0) + " "
print(answer)
```
No
| 14,669 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Submitted Solution:
```
l=list()
while(1):
n,k,t = [int(i) for i in input().split()]
if n in range(101)and t in range(101)and k in range(101) :
break
for i in range(n+1) :
a=round(n*t*0.01)
if i<a :
l.append(str(k))
elif i==a :
l.append((str(int((t*n)%100)/10))[:len(str(int((t*n)%100)/10))-2])
elif i>a :
l.append(str(0))
print(" ".join(l))
```
No
| 14,670 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Submitted Solution:
```
l=list()
while(1):
n,k,t = [int(i) for i in input().split()]
if n in range(101)and t in range(101)and k in range(101) :
break
for i in range(n+2) :
a=round(n*t*0.01)
if i<a :
l.append(str(k))
elif i==a :
l.append((str(int((t*n)%100)/10))[:len(str(int((t*n)%100)/10))-2])
elif i>a :
l.append(str(0))
l.append('0')
print(" ".join(l))
```
No
| 14,671 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.
A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≤ i ≤ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.
So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.
The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled:
<image>
An example of such a bar can be seen on the picture.
<image>
For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.
Input
We are given 3 space-separated integers n, k, t (1 ≤ n, k ≤ 100, 0 ≤ t ≤ 100).
Output
Print n numbers. The i-th of them should be equal to ai.
Examples
Input
10 10 54
Output
10 10 10 10 10 4 0 0 0 0
Input
11 13 37
Output
13 13 13 13 0 0 0 0 0 0 0
Submitted Solution:
```
n,k,t = map(int, input().split())
import math
box_size = 100/n
full = math.floor(t/box_size)
middle = math.floor((t%box_size)*k/box_size)
output = []
for i in range(n):
if i < full:
output.append(str(k))
elif i == full:
output.append(str(middle))
else:
output.append(str(0))
str1 = " "
print(str1.join(output))
```
No
| 14,672 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Tags: dfs and similar, dp, dsu, graphs, implementation, trees
Correct Solution:
```
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n-1):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
c = list(map(int, input().split()))
dif = [0 for _ in range(n)]
cnt = 0
for v in range(n):
dif[v] = 0
for u in g[v]:
if c[u] != c[v]:
dif[v] += 1
cnt += dif[v] > 0
ans = -1
for v in range(n):
if dif[v] + 1 >= cnt:
ans = v+1
if ans >= 0:
print('YES\n%d' % ans)
else:
print('NO')
```
| 14,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Tags: dfs and similar, dp, dsu, graphs, implementation, trees
Correct Solution:
```
n = int(input())
edges = [tuple(map(int, input().split())) for i in range(n - 1)]
colours = input().split()
'''better plan:
1)take any node
2)go up while parent has the same colour
3)as soon as colour changes save the result
4)check if result is good enough
5)if no, then it's unsolvable
6)else -- print result
'''
'''even better plan:
1)take any edge than connects two different colour nodes
2)if imbossible -- we won
3)else check if one of two nodes in the picked edge is good enough
4)we have ans
'''
possible_roots = []
for edge in edges:
one, two = edge
if colours[one - 1] != colours[two - 1]:
possible_roots.append(edge)
if len(possible_roots) == 0:
print('YES')
print(1)
exit()
one, two = possible_roots[0]
is_one_root = False
is_two_root = False
for edge in possible_roots[1:]:
if one in edge:
is_one_root = True
elif two in edge:
is_two_root = True
else:
print('NO')
exit()
if is_one_root and is_two_root:
print('NO')
exit()
print('YES')
if is_one_root:
print(one)
else:
print(two)
```
| 14,674 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Tags: dfs and similar, dp, dsu, graphs, implementation, trees
Correct Solution:
```
read = lambda: map(int, input().split())
n = int(input())
ed = []
for i in range(n - 1):
u, v = read()
if u > v: u, v = v, u
ed.append((u, v))
c = [0] + list(read())
edr = []
g = [list() for i in range(n + 1)]
ver = set()
for u, v in ed:
if c[u] != c[v]:
g[u].append(v)
g[v].append(u)
ver.add(u)
ver.add(v)
root = 1
for i in range(1, n + 1):
if len(g[i]) > 1:
root = i
break
if len(g[i]) == 1:
root = i
was = [0] * (n + 1)
was[root] = 1
for u in g[root]:
was[u] = 1
for i in ver:
if not was[i]:
print('NO')
exit()
print('YES')
print(root)
```
| 14,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Tags: dfs and similar, dp, dsu, graphs, implementation, trees
Correct Solution:
```
N = int(input())
G = [[] for i in range(N)]
d = []
for i in range(N - 1):
a, b = map(int, input().split())
a, b = a - 1, b - 1
G[a].append(b)
G[b].append(a)
d.append((a, b))
C = list(map(int, input().split()))
num = 0
for i in range(N - 1):
if C[d[i][0]] != C[d[i][1]]:
num += 1
for i in range(N):
s = 0
for j in G[i]:
if C[i] != C[j]:
s += 1
if s == num:
print('YES')
print(i + 1)
break
else:
print('NO')
```
| 14,676 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Tags: dfs and similar, dp, dsu, graphs, implementation, trees
Correct Solution:
```
import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
e = [ [] for i in range(n+1)]
for i in range(n-1):
u,v = mints()
e[u].append(v)
e[v].append(u)
c = list(mints())
start = None
for i in range(1, n+1):
ci = c[i-1]
for j in e[i]:
if c[j-1] != ci:
start = (i, j)
break
if start != None:
break
if start == None:
print("YES")
print(1)
return
for s in start:
was = [False]*(n+1)
ql = 0
q = []
was[s] = True
for i in e[s]:
was[i] = True
q.append((i, c[i-1]))
ok = True
while ql < len(q):
v, cc = q[ql]
ql += 1
for i in e[v]:
if was[i]:
continue
was[i] = True
if c[i-1] != cc:
ok = False
q.append((i, cc))
if ok:
print("YES")
print(s)
return
print("NO")
solve()
```
| 14,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Tags: dfs and similar, dp, dsu, graphs, implementation, trees
Correct Solution:
```
import sys
import collections
import itertools
n = int(sys.stdin.readline())
graph = collections.defaultdict(list)
for _ in range(n - 1):
u, v = map(int, str.split(sys.stdin.readline()))
graph[u].append(v)
graph[v].append(u)
colors = tuple(map(int, str.split(sys.stdin.readline())))
root = None
root_possible = []
for node in graph:
diff_subs = []
for sub_node in graph[node]:
if colors[node - 1] != colors[sub_node - 1]:
diff_subs.append(sub_node)
if len(diff_subs) > 1:
if root is None:
root = node
else:
print("NO")
exit()
elif len(diff_subs) == 1:
root_possible.append((node, diff_subs[0]))
root_possible_set = set(itertools.chain.from_iterable(root_possible))
if root:
print("YES")
print(root)
elif not root_possible:
print("YES")
print(1)
elif len(root_possible_set) == 2:
print("YES")
print(next(iter(root_possible_set)))
else:
print("NO")
```
| 14,678 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Tags: dfs and similar, dp, dsu, graphs, implementation, trees
Correct Solution:
```
#!/usr/bin/env python3
def ri():
return map(int, input().split())
n = int(input())
e = []
for i in range(n-1):
a, b = ri()
a -= 1
b -= 1
e.append([a, b])
c = list(ri())
ed = []
for ee in e:
if c[ee[0]] != c[ee[1]]:
ed.append(ee)
if len(ed) == 0:
print("YES")
print(1)
exit()
cand = ed[0]
not0 = 0
not1 = 0
for ee in ed:
if cand[0] != ee[0] and cand[0] != ee[1]:
not0 = 1
break
for ee in ed:
if cand[1] != ee[0] and cand[1] != ee[1]:
not1 = 1
break
if not0 == 0:
print("YES")
print(cand[0]+1)
elif not1 == 0:
print("YES")
print(cand[1]+1)
else:
print("NO")
```
| 14,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Tags: dfs and similar, dp, dsu, graphs, implementation, trees
Correct Solution:
```
class Node:
def __init__(self, number, color, adjacency_set):
self.number = number
self.color = color
self.adjacency_set = adjacency_set
def main():
n = int(input())
tree = []
for i in range(n):
tree.append(Node(i+1, 0, set()))
for i in range(n-1):
I = input().split(" ")
a = int(I[0])
b = int(I[1])
tree[a-1].adjacency_set.add(tree[b-1])
tree[b-1].adjacency_set.add(tree[a-1])
I = input().split(" ")
for i in range(n):
tree[i].color = int(I[i])
edges = set()
for node in tree:
for adjacent_node in node.adjacency_set:
if node.color != adjacent_node.color:
edges.add(frozenset([node, adjacent_node]))
if len(edges) == 0:
print("YES")
print(1)
return
if len(edges) == 1:
print("YES")
only_set = edges.pop()
print(list(only_set)[0].number)
return
# now we know that len(edges) >= 2
intersection = edges.pop()
for edge in edges:
intersection &= edge
if len(intersection) == 0:
print("NO")
return
print("YES")
print(list(intersection)[0].number)
main()
```
| 14,680 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Submitted Solution:
```
n = int(input())
e = [[0, 0] for i in range(n - 1)]
c = [0 for i in range(n)]
t = []
num = 0
for i in range(n - 1):
inp = input().split()
for j in range(2):
e[i][j] = int(inp[j]) - 1
inp = input().split()
for i in range(n):
c[i] = int(inp[i])
for i in range(n - 1):
if c[e[i][0]] != c[e[i][1]]:
#print(e[i], "opposite color")
if num == 0:
t = e[i]
num += 1
else:
if len(t) > 1 and t[1] not in e[i]:
t.remove(t[1])
if len(t) > 0 and t[0] not in e[i]:
t.remove(t[0])
#print(t)
if num == 0:
print("YES")
print(1)
else:
if len(t) == 0:
print("NO")
else:
print("YES")
print(t[0] + 1)
```
Yes
| 14,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Submitted Solution:
```
n=int(input())
graph=dict()
for i in range(1,n+1):
graph[i]=[]
diff=[]
for i in range(n-1):
u,v=map(int,input().split())
graph[u].append(v)
graph[v].append(u)
color=list(map(int,input().split()))
# print(color)
# print(graph)
flag=0 # used to indicate if two different colors nodes are present in an edge
for i in range(1,n+1):
if(graph[i]!=[]):
for j in graph[i]:
if(color[i-1]!=color[j-1]):
diff.append(i)
diff.append(j)
flag=1
break
if(flag==1):
break
# print(diff)
#check=[-1 for i in range(n)]
def dfs(graph,node,col,parentnode):
# print(node,col,color[node-1])
# global check
if(color[node-1]!=col):
return -1
# check[node-1]=0
if(graph[node]!=[]):
for i in graph[node]:
if(i!=parentnode):
f1=dfs(graph,i,col,node)
if(f1==-1):
return -1
return 1
if(flag==0): # single color nodes are present in the entire tree
print("YES")
print(n)
else: # different color present
# print("check",check)
#check[diff[0]-1]=0
f=1
for i in graph[diff[0]]:
f=dfs(graph,i,color[i-1],diff[0])
# print(f,i)
if(f==-1): # some of the children nodes are of different color
break
if(f!=-1):# if all the children satisfy the condition
# flag1=0
# for i in range(n):
# if(check[i]==-1):
# for j in range(i+1,n):
# if(check[j]==-1 and color[j]!=color[i]):
# flag1=-1 # two different colors found
# break
# if(flag1==-1):
# break
# if(flag1==0):
print("YES")
print(diff[0])
# else:
# f=-1
if(f==-1): # the checking of the children node has started
# for i in range(n):
# check[i]=-1
# check[diff[1]-1]=0
# print("check1",check1)
f2=1
for i in graph[diff[1]]:
f2=dfs(graph,i,color[i-1],diff[1])
# print(f2,i)
if(f2==-1):
break
# print(f2,check1)
if(f2==-1):
print("NO")
else:# if all the children satisfy the condition
# print(color)
# flag1=0
# for i in range(n):
# if(check[i]==-1):
# for j in range(i+1,n):
# if(check[j]==-1 and color[j]!=color[i]):
# flag1=-1 # two different colors found
# break
# if(flag1==-1):
# break
# if(flag1==0):
print("YES")
print(diff[1])
# else:
# print("NO")
```
Yes
| 14,682 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Submitted Solution:
```
n = int(input())
edges = list()
edges = []
for i in range(n-1):
edge = []
edge = input().split(' ')
edge = list(map(int,edge))
edges.append(edge)
colors = []
colors = input().split(' ')
colors = list(map(int,colors))
colors.insert(0,0)
if n<3:
print('YES')
print(edges[0][0])
exit()
commonedge = []
for edge in edges:
if colors[edge[0]] != colors[edge[1]]:
if len(commonedge)==0:
commonedge.append(edge[0])
commonedge.append(edge[1])
elif len(commonedge)==2:
if commonedge.count(edge[0])==0 and commonedge.count(edge[1])==0:
print('NO')
exit()
elif commonedge.count(edge[1])==0:
if commonedge[0]==edge[0]:
del commonedge[1]
else:
del commonedge[0]
else:
if commonedge[0]==edge[1]:
del commonedge[1]
else:
del commonedge[0]
else:
if commonedge.count(edge[0])==0 and commonedge.count(edge[1])==0:
print('NO')
exit()
print('YES')
if len(commonedge)>0:
print(commonedge[0])
else:
print(edges[0][0])
```
Yes
| 14,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Submitted Solution:
```
n = int(input())
edges = []
for i in range(n-1):
edges.append(list(map(int, input().split())))
colors = [0] + list(map(int, input().split()))
tops = []
for e in edges:
if colors[e[0]] != colors[e[1]]:
tops.append(e)
if not tops:
print('YES')
print(1)
else:
s = set(tops[0])
list(map(lambda t: s.intersection_update(set(t)), tops))
if s:
print('YES')
print(list(s)[0])
else:
print('NO')
```
Yes
| 14,684 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Submitted Solution:
```
n = int(input())
edges = [tuple(map(int, input().split())) for i in range(n - 1)]
colours = input().split()
'''better plan:
1)take any node
2)go up while parent has the same colour
3)as soon as colour changes save the result
4)check if result is good enough
5)if no, then it's unsolvable
6)else -- print result
'''
'''even better plan:
1)take any edge than connects two different colour nodes
2)if imbossible -- we won
3)else check if one of two nodes in the picked edge is good enough
4)we have ans
'''
possible_roots = []
for edge in edges:
one, two = edge
if colours[one - 1] != colours[two - 1]:
possible_roots.append(edge)
if len(possible_roots) == 0:
print('YES')
print(1)
one, two = possible_roots[0]
is_one_root = False
is_two_root = False
for edge in possible_roots[1:]:
if one in edge:
is_one_root = True
if two in edge:
is_two_root = True
if is_one_root and is_two_root:
print('NO')
exit()
print('YES')
if is_one_root:
print(one)
else:
print(two)
```
No
| 14,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Submitted Solution:
```
from collections import Counter
def dfs(graph, start):
c = colors[start]
top = set()
visited, stack = [], [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
if vertex not in graph:
top.add(vertex)
else:
if colors[vertex] == c:
visited.append(vertex)
stack.extend(graph[vertex] - set(visited))
else:
top.add(vertex)
return visited, top
n = int(input())
tree = {}
tops = []
possible = True
for _ in range(n-1):
a, b = map(int, input().split())
tree[a] = tree.get(a, set()).union({b})
tree[b] = tree.get(b, set()).union({a})
colors = [0] + list(map(int, input().split()))
ncolors = Counter(colors)
del ncolors[0]
tree2 = tree.copy()
while tree:
i = list(tree.keys())[0]
vs, top = dfs(tree, i)
tops.append(top)
for k in vs:
tree.pop(k, None)
# print(vs, i)
# print(tops)
count = Counter([item for sublist in tops for item in sublist])
# print(count)
# print(ncolors)
if len(ncolors) == 1:
print(1)
else:
if max(count, key=lambda x: count[x]) >= len(tops) - 1:
print('YES')
print(max(count, key=lambda x: count[x]))
else:
print('NO')
# print(Counter(colors))
# print(tree)
# print(dfs(tree, 1))
```
No
| 14,686 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Submitted Solution:
```
n=int(input())
graph=dict()
for i in range(1,n+1):
graph[i]=[]
parent=dict()
diff=[]
for i in range(n-1):
u,v=map(int,input().split())
graph[u].append(v)
parent[v]=u
color=list(map(int,input().split()))
# print(color)
# print(graph)
flag=0 # used to indicate if two different colors nodes are present in an edge
for i in range(1,n+1):
if(graph[i]!=[]):
for j in graph[i]:
if(color[i-1]!=color[j-1]):
diff.append(i)
diff.append(j)
flag=1
break
if(flag==1):
break
# print(diff)
def dfs(graph,node,col):
# print(node,col,color[node-1])
if(color[node-1]!=col):
return -1
if(graph[node]!=[]):
for i in graph[node]:
f1=dfs(graph,i,col)
if(f1==-1):
return -1
return 1
if(flag==0): # single color nodes are present in the entire tree
print("YES")
print(1)
else:
f=0
for i in graph[diff[0]]:
f=dfs(graph,i,color[i-1])
# print(f,i)
if(f==-1): # some of the children nodes are of different color
break
if(f!=-1):
print("YES")
print(diff[0])
else: # the checking of the children node has started
f2=0
for i in graph[diff[1]]:
f2=dfs(graph,i,color[i-1])
# print(f2,i)
if(f2==-1):
break
if(f2!=-1):
print("YES")
print(diff[1])
else:
print("NO")
```
No
| 14,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 2
Output
NO
Submitted Solution:
```
n=int(input())
ip=[[] for i in range(n)]
for i in range(n-1):
a,b=map(int,input().split())
a-=1
b-=1
ip[a].append(b)
ip[b].append(a)
col=list(map(int,input().split()))
cs=[0 for i in range(n)]
for i in range(n):
count=0
for j in ip[i]:
if col[j]!=col[i]:
count+=1
cs[i]=count
#print(cs)
#print(ip)
count=0
c1=0
for i in range(n):
if cs[i]==0:
continue
elif cs[i]==1:
c1+=1
ans1=i+1
else:
#print("csi",cs[i])
count+=1
ans=i+1
#print(count)
if count==0:
if c1==0:
print('YES')
print(1)
elif c1==1:
print('YES')
print(ans1)
else:
print('NO')
elif count==1:
if c1<=2:
print('YES')
print(ans)
else:
print('NO')
else:
print('NO')
```
No
| 14,688 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem. In the output section below you will see the information about flushing the output.
On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building.
In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of n dishes. It is interesting that all dishes in the menu are numbered with integers from 1 to n. After a little thought, the girl ordered exactly k different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better.
The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers x and y (1 ≤ x, y ≤ n). After that Noora chooses some dish a for the number x such that, at first, a is among the dishes Noora ordered (x can be equal to a), and, secondly, the value <image> is the minimum possible. By the same rules the girl chooses dish b for y. After that Noora says «TAK» to Leha, if <image>, and «NIE» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than 60 questions. After that he should name numbers of any two dishes Noora ordered.
Help Leha to solve this problem!
Input
There are two numbers n and k (2 ≤ k ≤ n ≤ 105) in the single line of input denoting the number of dishes in the menu and the number of dishes Noora ordered.
Output
If you want to provide an answer, output a string of the form 2 x y (1 ≤ x, y ≤ n, x ≠ y), if you think the dishes x and y was among dishes ordered by Noora. After that, flush the output and terminate your program.
Interaction
While helping Leha, you can ask queries to Noora no more than 60 times. Each query should be printed in it's own line and have the form 1 x y (1 ≤ x, y ≤ n). You have to both print the end-of-line character and flush the output. After flushing you should read the answer for this query from input.
After each query jury's program will print one line «TAK» or «NIE» (without quotes) in input stream depending on the girl's answer.
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* see the documentation for other languages.
Hacking
For hacking you should write numbers n and k (2 ≤ k ≤ n ≤ 105) in the first line and, for describing dishes Noora ordered, k different integers a1, a2, ..., ak (1 ≤ ai ≤ n), written in ascending order in the second line. Of course, solution you want to hack won't be able to read the numbers of ordered dishes.
Example
Input
3 2
NIE
TAK
NIE
TAK
TAK
TAK
Output
1 1 2
1 2 1
1 1 3
1 3 1
1 2 3
1 3 2
2 2 3
Note
There are three dishes in sample. Noora ordered dished numberes 2 and 3, which Leha should guess. If Noora receive requests for the first dish (x = 1), then she'll choose the second dish (a = 2) as the dish with the minimum value <image>. For the second (x = 2) and the third (x = 3) dishes themselves will be optimal, because in that case <image>.
Let Leha asks Noora about the next couple of dishes:
* x = 1, y = 2, then he'll recieve «NIE» answer, because |1 - 2| > |2 - 2|
* x = 2, y = 1, then he'll recieve «TAK» answer, because |2 - 2| ≤ |1 - 2|
* x = 1, y = 3, then he'll recieve «NIE» answer, because |1 - 2| > |3 - 3|
* x = 3, y = 1, then he'll recieve «TAK» answer, because |3 - 3| ≤ |1 - 2|
* x = 2, y = 3, then he'll recieve «TAK» answer, because |2 - 2| ≤ |3 - 3|
* x = 3, y = 2, then he'll recieve «TAK» answer, because |3 - 3| ≤ |2 - 2|
According to the available information, it is possible to say that Nura ordered dishes with numbers 2 and 3.
Submitted Solution:
```
from sys import *
def check(x) :
if x==-1:
return False
print (1, x, x+1)
stdout. flush ()
ans=input ()
return (ans =="TAK")
def search (left, right) :
if left>right:
return - 1
tmp_left, tmp_right=left-1, right
while tmp_right-tmp_left>1:
mid=(tmp_left+tmp_right)//2
ans=check(mid)
if(ans):
tmp_right=mid
else:
tmp_left=mid
return tmp_left+1
n, k=map (int, input (). split ())
x=search (1,n)
y=search (1,x-1)
if not check(y) :
y=search (x+1,n)
print (2, x, y)
stdout. flush()
exit ()
```
No
| 14,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem. In the output section below you will see the information about flushing the output.
On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building.
In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of n dishes. It is interesting that all dishes in the menu are numbered with integers from 1 to n. After a little thought, the girl ordered exactly k different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better.
The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers x and y (1 ≤ x, y ≤ n). After that Noora chooses some dish a for the number x such that, at first, a is among the dishes Noora ordered (x can be equal to a), and, secondly, the value <image> is the minimum possible. By the same rules the girl chooses dish b for y. After that Noora says «TAK» to Leha, if <image>, and «NIE» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than 60 questions. After that he should name numbers of any two dishes Noora ordered.
Help Leha to solve this problem!
Input
There are two numbers n and k (2 ≤ k ≤ n ≤ 105) in the single line of input denoting the number of dishes in the menu and the number of dishes Noora ordered.
Output
If you want to provide an answer, output a string of the form 2 x y (1 ≤ x, y ≤ n, x ≠ y), if you think the dishes x and y was among dishes ordered by Noora. After that, flush the output and terminate your program.
Interaction
While helping Leha, you can ask queries to Noora no more than 60 times. Each query should be printed in it's own line and have the form 1 x y (1 ≤ x, y ≤ n). You have to both print the end-of-line character and flush the output. After flushing you should read the answer for this query from input.
After each query jury's program will print one line «TAK» or «NIE» (without quotes) in input stream depending on the girl's answer.
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* see the documentation for other languages.
Hacking
For hacking you should write numbers n and k (2 ≤ k ≤ n ≤ 105) in the first line and, for describing dishes Noora ordered, k different integers a1, a2, ..., ak (1 ≤ ai ≤ n), written in ascending order in the second line. Of course, solution you want to hack won't be able to read the numbers of ordered dishes.
Example
Input
3 2
NIE
TAK
NIE
TAK
TAK
TAK
Output
1 1 2
1 2 1
1 1 3
1 3 1
1 2 3
1 3 2
2 2 3
Note
There are three dishes in sample. Noora ordered dished numberes 2 and 3, which Leha should guess. If Noora receive requests for the first dish (x = 1), then she'll choose the second dish (a = 2) as the dish with the minimum value <image>. For the second (x = 2) and the third (x = 3) dishes themselves will be optimal, because in that case <image>.
Let Leha asks Noora about the next couple of dishes:
* x = 1, y = 2, then he'll recieve «NIE» answer, because |1 - 2| > |2 - 2|
* x = 2, y = 1, then he'll recieve «TAK» answer, because |2 - 2| ≤ |1 - 2|
* x = 1, y = 3, then he'll recieve «NIE» answer, because |1 - 2| > |3 - 3|
* x = 3, y = 1, then he'll recieve «TAK» answer, because |3 - 3| ≤ |1 - 2|
* x = 2, y = 3, then he'll recieve «TAK» answer, because |2 - 2| ≤ |3 - 3|
* x = 3, y = 2, then he'll recieve «TAK» answer, because |3 - 3| ≤ |2 - 2|
According to the available information, it is possible to say that Nura ordered dishes with numbers 2 and 3.
Submitted Solution:
```
import sys
# print("2333", file = sys.stderr)
def ask(x, y) :
print("1", x, y)
sys.stdout.flush()
return input()
def solve(L, R) :
if L > R :
return -1
while L < R :
mid = (L + R) >> 1
if ask(mid, mid + 1) == "TAK" :
R = mid
else :
L = mid + 1
return L
n, k = list(map(int, input().split()))
a = solve(1, n)
b = solve(1, a - 1)
if b == -1 or ask(a, b) == "NIE" :
b = solve(a + 1, n)
print("2", 2, 3)
sys.stdout.flush()
```
No
| 14,690 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem. In the output section below you will see the information about flushing the output.
On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building.
In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of n dishes. It is interesting that all dishes in the menu are numbered with integers from 1 to n. After a little thought, the girl ordered exactly k different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better.
The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers x and y (1 ≤ x, y ≤ n). After that Noora chooses some dish a for the number x such that, at first, a is among the dishes Noora ordered (x can be equal to a), and, secondly, the value <image> is the minimum possible. By the same rules the girl chooses dish b for y. After that Noora says «TAK» to Leha, if <image>, and «NIE» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than 60 questions. After that he should name numbers of any two dishes Noora ordered.
Help Leha to solve this problem!
Input
There are two numbers n and k (2 ≤ k ≤ n ≤ 105) in the single line of input denoting the number of dishes in the menu and the number of dishes Noora ordered.
Output
If you want to provide an answer, output a string of the form 2 x y (1 ≤ x, y ≤ n, x ≠ y), if you think the dishes x and y was among dishes ordered by Noora. After that, flush the output and terminate your program.
Interaction
While helping Leha, you can ask queries to Noora no more than 60 times. Each query should be printed in it's own line and have the form 1 x y (1 ≤ x, y ≤ n). You have to both print the end-of-line character and flush the output. After flushing you should read the answer for this query from input.
After each query jury's program will print one line «TAK» or «NIE» (without quotes) in input stream depending on the girl's answer.
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* see the documentation for other languages.
Hacking
For hacking you should write numbers n and k (2 ≤ k ≤ n ≤ 105) in the first line and, for describing dishes Noora ordered, k different integers a1, a2, ..., ak (1 ≤ ai ≤ n), written in ascending order in the second line. Of course, solution you want to hack won't be able to read the numbers of ordered dishes.
Example
Input
3 2
NIE
TAK
NIE
TAK
TAK
TAK
Output
1 1 2
1 2 1
1 1 3
1 3 1
1 2 3
1 3 2
2 2 3
Note
There are three dishes in sample. Noora ordered dished numberes 2 and 3, which Leha should guess. If Noora receive requests for the first dish (x = 1), then she'll choose the second dish (a = 2) as the dish with the minimum value <image>. For the second (x = 2) and the third (x = 3) dishes themselves will be optimal, because in that case <image>.
Let Leha asks Noora about the next couple of dishes:
* x = 1, y = 2, then he'll recieve «NIE» answer, because |1 - 2| > |2 - 2|
* x = 2, y = 1, then he'll recieve «TAK» answer, because |2 - 2| ≤ |1 - 2|
* x = 1, y = 3, then he'll recieve «NIE» answer, because |1 - 2| > |3 - 3|
* x = 3, y = 1, then he'll recieve «TAK» answer, because |3 - 3| ≤ |1 - 2|
* x = 2, y = 3, then he'll recieve «TAK» answer, because |2 - 2| ≤ |3 - 3|
* x = 3, y = 2, then he'll recieve «TAK» answer, because |3 - 3| ≤ |2 - 2|
According to the available information, it is possible to say that Nura ordered dishes with numbers 2 and 3.
Submitted Solution:
```
def bsearch(l, r):
while l < r:
mid = (l + r) // 2
print(1, mid, mid + 1)
x = 1 if input() == 'TAK' else 0
if x:
r = mid
else:
l = mid + 1
return l
n, k = map(int, input().split())
x = bsearch(1, n)
print(1, x)
a = bsearch(1, x - 1)
print(2, x, a)
if input() == 'TAK':
print(1, a)
else:
print(1, bsearch(x + 1, n))
```
No
| 14,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem. In the output section below you will see the information about flushing the output.
On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building.
In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of n dishes. It is interesting that all dishes in the menu are numbered with integers from 1 to n. After a little thought, the girl ordered exactly k different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better.
The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers x and y (1 ≤ x, y ≤ n). After that Noora chooses some dish a for the number x such that, at first, a is among the dishes Noora ordered (x can be equal to a), and, secondly, the value <image> is the minimum possible. By the same rules the girl chooses dish b for y. After that Noora says «TAK» to Leha, if <image>, and «NIE» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than 60 questions. After that he should name numbers of any two dishes Noora ordered.
Help Leha to solve this problem!
Input
There are two numbers n and k (2 ≤ k ≤ n ≤ 105) in the single line of input denoting the number of dishes in the menu and the number of dishes Noora ordered.
Output
If you want to provide an answer, output a string of the form 2 x y (1 ≤ x, y ≤ n, x ≠ y), if you think the dishes x and y was among dishes ordered by Noora. After that, flush the output and terminate your program.
Interaction
While helping Leha, you can ask queries to Noora no more than 60 times. Each query should be printed in it's own line and have the form 1 x y (1 ≤ x, y ≤ n). You have to both print the end-of-line character and flush the output. After flushing you should read the answer for this query from input.
After each query jury's program will print one line «TAK» or «NIE» (without quotes) in input stream depending on the girl's answer.
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* see the documentation for other languages.
Hacking
For hacking you should write numbers n and k (2 ≤ k ≤ n ≤ 105) in the first line and, for describing dishes Noora ordered, k different integers a1, a2, ..., ak (1 ≤ ai ≤ n), written in ascending order in the second line. Of course, solution you want to hack won't be able to read the numbers of ordered dishes.
Example
Input
3 2
NIE
TAK
NIE
TAK
TAK
TAK
Output
1 1 2
1 2 1
1 1 3
1 3 1
1 2 3
1 3 2
2 2 3
Note
There are three dishes in sample. Noora ordered dished numberes 2 and 3, which Leha should guess. If Noora receive requests for the first dish (x = 1), then she'll choose the second dish (a = 2) as the dish with the minimum value <image>. For the second (x = 2) and the third (x = 3) dishes themselves will be optimal, because in that case <image>.
Let Leha asks Noora about the next couple of dishes:
* x = 1, y = 2, then he'll recieve «NIE» answer, because |1 - 2| > |2 - 2|
* x = 2, y = 1, then he'll recieve «TAK» answer, because |2 - 2| ≤ |1 - 2|
* x = 1, y = 3, then he'll recieve «NIE» answer, because |1 - 2| > |3 - 3|
* x = 3, y = 1, then he'll recieve «TAK» answer, because |3 - 3| ≤ |1 - 2|
* x = 2, y = 3, then he'll recieve «TAK» answer, because |2 - 2| ≤ |3 - 3|
* x = 3, y = 2, then he'll recieve «TAK» answer, because |3 - 3| ≤ |2 - 2|
According to the available information, it is possible to say that Nura ordered dishes with numbers 2 and 3.
Submitted Solution:
```
def check(x, y) :
if x==-1:
return False
print (1," ", x," ", y)
ans=input ()
return (ans =="TAK")
def search (left, right) :
if left>right :
return - 1
while left<right :
mid=(left+right) //2
if(check (mid,mid+1)):
right=mid
else:
left=mid
return left
n, k=map (int, input (). split ())
x=search (1,n)
y=search (1,x-1)
if not check(y+1) :
y=search (x+1,n)
print (2," ", x," ", y)
```
No
| 14,692 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
It is well-known that the best decoration for a flower bed in Sweetland are vanilla muffins. Seedlings of this plant need sun to grow up. Slastyona has m seedlings, and the j-th seedling needs at least kj minutes of sunlight to grow up.
Most of the time it's sunny in Sweetland, but sometimes some caramel clouds come, the i-th of which will appear at time moment (minute) li and disappear at time moment ri. Of course, the clouds make shadows, and the seedlings can't grow when there is at least one cloud veiling the sun.
Slastyona wants to grow up her muffins as fast as possible. She has exactly C candies, which is the main currency in Sweetland.
One can dispel any cloud by paying ci candies. However, in order to comply with Sweetland's Department of Meteorology regulations, one can't dispel more than two clouds.
Slastyona hasn't decided yet which of the m seedlings will be planted at the princess' garden, so she needs your help. For each seedling determine the earliest moment it can grow up if Slastyona won't break the law and won't spend more candies than she has. Note that each of the seedlings is considered independently.
The seedlings start to grow at time moment 0.
Input
The first line contains two integers n and C (0 ≤ n ≤ 3·105, 0 ≤ C ≤ 109) – the number of caramel clouds and the number of candies Slastyona has.
The next n lines contain three integers each: li, ri, ci (0 ≤ li < ri ≤ 109, 0 ≤ ci ≤ 109), describing one caramel cloud.
The next line contains single integer m (1 ≤ m ≤ 3·105) – the number of seedlings. Each of the seedlings is described with one integer kj (1 ≤ kj ≤ 109) – the required number of sunny minutes.
Output
For each seedling print one integer – the minimum minute Slastyona can grow it up.
Examples
Input
3 5
1 7 1
1 6 2
1 7 1
3
7
2
5
Output
12
7
10
Input
3 15
1 4 17
2 8 6
4 8 9
2
5
1
Output
8
1
Input
2 10
3 7 9
10 90 10
2
10
100
Output
10
104
Note
Consider the first example. For each k it is optimal to dispel clouds 1 and 3. Then the remaining cloud will give shadow on time segment [1..6]. So, intervals [0..1] and [6..inf) are sunny.
<image>
In the second example for k = 1 it is not necessary to dispel anything, and for k = 5 the best strategy is to dispel clouds 2 and 3. This adds an additional sunny segment [4..8], which together with [0..1] allows to grow up the muffin at the eight minute.
<image> <image>
If the third example the two seedlings are completely different. For the first one it is necessary to dispel cloud 1 and obtain a sunny segment [0..10]. However, the same strategy gives answer 180 for the second seedling. Instead, we can dispel cloud 2, to make segments [0..3] and [7..inf) sunny, and this allows up to shorten the time to 104.
Submitted Solution:
```
class my_sum:
_a = [(0, -1), (0, -1)]
def add(self, id, value):
if self._a[0][1] == id:
_tmp = max(self._a[0][0], value)
self._a[0] = (_tmp, self._a[0][1])
elif self._a[1][0] < value:
self._a[1] = (value, id)
if self._a[0][0] < self._a[1][0]:
_tmp = self._a[0]
self._a[0], self._a[1] = self._a[1], _tmp
def ask(self, id):
return self._a[0][0] if self._a[0][1] != id else self._a[1][0]
cost = []
toupd = [0 for _ in range(300000)]
if __name__ == '__main__':
_first_line = input().split(' ')
n = int(_first_line[0])
budget = int(_first_line[1])
# cost[n] = 0
events = [(0, n), (2000000000, n)]
for _i in range(n):
_line = input().split(' ')
_l, _r, _cost = int(_line[0]), int(_line[1]), int(_line[2])
cost.append(_cost)
events.append((_l, _i))
events.append((_r, _i))
events.sort()
_values = cost[0:n]
_values.sort()
values = []
while len(_values) > 0:
_first = _values[0]
_values.remove(_first)
if len(values) == 0 or _first != values[-1]:
values.append(_first)
covers = set([])
if events[0][1] < n:
covers.add(events[0][1])
curmx = 0
parts = []
bit = []
for i in range(len(values)):
bit.append(my_sum())
_length = dict()
for _t in range(1, len(events)):
mxlen = events[_t][0] - events[_t - 1][0]
if mxlen > 0 and len(covers) <= 2:
p, q = n, n
if len(covers) > 0:
p = list(covers)[0]
if len(covers) > 1:
q = list(covers)[-1]
_start = -1
if p == n:
_start = curmx
else:
if q == n:
if cost[p] <= budget:
_start = toupd[p]
k = len(values) - 1
for _index, _v in enumerate(values):
if _v > cost[p] - values[0]:
k = _index - 1
break
while k >= 0:
_start = max(_start, bit[k].ask(p))
k -= ~k & k + 1
if (p, q) not in _length:
_length[(p, q)] = 0
_tmp_value = _length[(p, q)] + mxlen
k = len(values) - 1
for _index, _v in enumerate(values):
if _v < cost[p] - values[0]:
k = _index
break
while k < len(values):
bit[k].add(p, _tmp_value)
k += ~k & k + 1
elif cost[p] + cost[q] <= budget:
if (p, n) not in _length:
_length[(p, n)] = 0
if (q, n) not in _length:
_length[(q, n)] = 0
_start = _length[(p, n)] + _length[(q, n)]
if (p, q) not in _length:
_length[(p, q)] = 0
toupd[p] = max(toupd[p], _length[(q, n)] + _length[(p, q)] + mxlen)
toupd[q] = max(toupd[q], _length[(p, n)] + _length[(p, q)] + mxlen)
if ~_start:
if (p, q) not in _length:
_length[(p, q)] = 0
if (n, n) not in _length:
_length[(n, n)] = 0
_start += _length[(p, q)] + _length[(n, n)]
if ~_start and _start + mxlen > curmx:
curmx = _start + mxlen
parts.append((curmx, events[_t][0]))
if (p, q) not in _length:
_length[(p, q)] = 0
_length[(p, q)] += + mxlen
_tmp_i = events[_t][1]
if _tmp_i < n:
if _tmp_i in covers:
covers.remove(_tmp_i)
else:
covers.add(_tmp_i)
q = int(input())
t = 0
for _ in range(q):
t = int(input())
for _first, _second in parts:
if _first >= t:
print(_second - (_first - t))
break
```
No
| 14,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Tags: greedy
Correct Solution:
```
# from debug import debug
from heapq import heappush, heappop, heapify
n, k = map(int, input().split())
c = list(map(int, input().split()))
q = [(-c[i], i) for i in range(k)]
heapify(q)
ans = 0
lis = [0]*n
for i in range(k, n):
heappush(q, (-c[i], i))
a, p = heappop(q)
ans += a*(i-p)
lis[p] = i+1
for i in range(n, n+k):
a, p = heappop(q)
ans += a*(i-p)
lis[p] = i+1
print(-ans)
print(*lis)
```
| 14,694 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Tags: greedy
Correct Solution:
```
from heapq import heappush, heappop, heapify
n, k = map(int, input().split())
a = list(map(int, input().split()))
q = [(-a[i], i) for i in range(k)]
heapify(q)
res, s = [0] * n, 0
for i in range(k, n):
heappush(q, (-a[i], i))
x, j = heappop(q)
s -= x * (i-j)
res[j] = i+1
for i in range(n, n+k):
x, j = heappop(q)
s -= x * (i-j)
res[j] = i+1
print(s)
print(*res)
```
| 14,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Tags: greedy
Correct Solution:
```
from heapq import heappush,heappop,heapify
n,k=map(int,input().split())
*l,=map(int,input().split())
q=[(-l[i],i)for i in range(k)];heapify(q)
a=[0]*n
s=0
for i in range(k,n):
heappush(q,(-l[i],i))
x,j=heappop(q)
s-=x*(i-j)
a[j]=i+1
for i in range(n,n+k):
x,j=heappop(q)
s-=x*(i-j)
a[j]=i+1
print(s)
print(' '.join(map(str,a)))
```
| 14,696 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Tags: greedy
Correct Solution:
```
import heapq
n,k = map(int,input().split())
l = list(map(int,input().split()))
ans = [0]*n
h = []
for i in range(k):
h.append((-1*l[i],i))
heapq.heapify(h)
som = 0
for i in range(k,n+k):
if i < n:
heapq.heappush(h, (-1 * l[i], i))
x = heapq.heappop(h)
s = -1*x[0]*(i-x[1])
som += s
ans[x[1]] = i+1
print(som)
print(*ans)
```
| 14,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Tags: greedy
Correct Solution:
```
"""
Author - Satwik Tiwari .
15th Dec , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
def safe(x,y):
global n,m
return (0<=x<n and 0<=y<m)
def solve(case):
n,k = sep()
a = lis()
if(k >= n):
h = []
ans = 0
order = [0]*n
for i in range(n):
ans += (k-i)*a[i]
# print(ans)
h = []
for i in range(n):
heappush(h,(-a[i],i))
temp = heappop(h)
order[temp[1]] = k
for i in range(n-1):
temp,j = heappop(h)
temp*=-1
ans += (i+1)*temp
order[j] = k+i+1
print(ans)
print(' '.join(str(order[i]+1) for i in range(len(order))))
else:
ans = 0
for i in range(k+1):
ans += (k-i)*a[i]
h = []
sum = 0
for i in range(k+1):
heappush(h,(-a[i],i))
sum += a[i]
order = [0]*n
for i in range(k,k+n):
temp,j = heappop(h)
sum+=temp
ans += sum
order[j] = i
if(i+1 < n):
heappush(h,(-a[i+1],i+1))
sum += a[i+1]
print(ans)
print(' '.join(str(order[i]+1) for i in range(len(order))))
# chck = 0
# for i in range(n):
# chck += (order[i]-i)*a[i]
# # print(chck)
# print(chck)
n,m = 0,0
testcase(1)
# testcase(int(inp()))
```
| 14,698 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Tags: greedy
Correct Solution:
```
# https://codeforces.com/problemset/problem/853/A
from heapq import heappush, heappop
n, k = list(map(int, input().rstrip().split()))
c = list(map(int, input().rstrip().split()))
li = [0] * n
cost = 0
q = []
for i in range(k):
heappush(q, (-c[i], i))
for i in range(k,n):
heappush(q, (-c[i], i))
v, j = heappop(q)
li[j] = i + 1
cost += -v * (i - j)
for i in range(k):
v, j = heappop(q)
li[j] = n + i + 1
cost += -v * (n + i - j)
print(cost)
print(*li)
```
| 14,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.