text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string s consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'. Note that each of the characters '?' is replaced independently from the others.
A string t of length n is called a palindrome if the equality t[i] = t[n-i+1] is true for all i (1 β€ i β€ n).
For example, if s="01?????0", a=4 and b=4, then you can replace the characters '?' in the following ways:
* "01011010";
* "01100110".
For the given string s and the numbers a and b, replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'.
Input
The first line contains a single integer t (1 β€ t β€ 10^4). Then t test cases follow.
The first line of each test case contains two integers a and b (0 β€ a, b β€ 2 β
10^5, a + b β₯ 1).
The second line of each test case contains the string s of length a+b, consisting of the characters '0', '1', and '?'.
It is guaranteed that the sum of the string lengths of s over all test cases does not exceed 2 β
10^5.
Output
For each test case, output:
* "-1", if you can't replace all the characters '?' in the string s by '0' or '1' so that the string becomes a palindrome and that it contains exactly a characters '0' and exactly b characters '1';
* the string that is obtained as a result of the replacement, otherwise.
If there are several suitable ways to replace characters, you can output any.
Example
Input
9
4 4
01?????0
3 3
??????
1 0
?
2 2
0101
2 2
01?0
0 1
0
0 3
1?1
2 2
?00?
4 3
??010?0
Output
01011010
-1
0
-1
0110
-1
111
1001
0101010
Submitted Solution:
```
def getStr(a,b):
ans=["0"]*(a+b)
if a>b:
ac="0"
bc="1"
else:
ac="1"
bc="0"
a,b=b,a
i=0
n=a+b
while i<(n//2) and a>=0 and b>=0:
if i%2==0 and a>0:
ans[i]=ac
ans[-(i+1)]=ac
a-=2
elif b>0:
ans[i]=bc
ans[-(i+1)]=bc
b-=2
else:
if a>0:
while i<(n//2):
ans[i],ans[-(i+1)]=ac,ac
i+=1
break
if b>0:
while i<(n//2):
ans[i],ans[-(i+1)]=bc,bc
i+=1
break
i+=1
return "".join(ans)
for _ in range(int(input())):
a,b=list(map(int,input().split()))
l=list(input())
cq=l.count("?")
if cq==(a+b):
if cq%2==0:
if a%2==0 and b%2==0:
print(getStr(a,b))
else:
print("-1")
else:
n=a+b
if a%2==0 and b%2!=0:
b-=1
s=getStr(a,b)[0:n//2]
print(s+"1"+s[::-1])
elif a%2!=0 and b%2==0:
a-=1
s=getStr(a,b)[0:n//2]
print(s+"0"+s[::-1])
else:
print("-1")
else:
n,sdf,qc=(a+b)//2,a+b,0
if (a+b)%2!=0:
if (a+b)==1 and l[0]=="?":
qc+=1
elif l[n]=="?":
qc+=1
elif l[n]=="1":
b-=1
elif l[n]=="0":
a-=1
dd=True
for i in range(n):
if l[i]==l[-(i+1)]:
if l[i]=="?":
qc+=2
elif l[i]=="0":
a-=2
else:
b-=2
else:
if (l[i]=="0" and l[-(i+1)]=="?") or (l[i]=="?" and l[-(i+1)]=="0"):
a-=2
l[i],l[-(i+1)]="0","0"
elif (l[i]=="1" and l[-(i+1)]=="?") or (l[i]=="?" and l[-(i+1)]=="1"):
b-=2
l[i],l[-(i+1)]="1","1"
else:
print("-1")
dd=False
break
if dd and a>=0 and b>=0:
if sdf%2!=0:
n+=1
if qc%2==0:
if a%2==0 and b%2==0:
d=getStr(a,b)
j=0
for i in range(n):
if l[i]==l[-(i+1)]:
if l[i]=="?":
l[i],l[-(i+1)]=d[j],d[j]
j+=1
print("".join(l))
# print(l,n)
else:
print("-1")
else:
if a%2==0 and b%2!=0:
b-=1
s=getStr(a,b)[0:n//2]
d=s+"1"+s[::-1]
j=0
for i in range(n):
if l[i]==l[-(i+1)]:
if l[i]=="?":
l[i],l[-(i+1)]=d[j],d[j]
j+=1
print("".join(l))
elif a%2!=0 and b%2==0:
a-=1
s=getStr(a,b)[0:n//2]
d=s+"0"+s[::-1]
j=0
for i in range(n):
if l[i]==l[-(i+1)]:
if l[i]=="?":
l[i],l[-(i+1)]=d[j],d[j]
j+=1
print("".join(l))
else:
print("-1")
else:
print("-1")
```
No
| 1,900 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The warehouse in your shop has n shoe pairs. Each pair is characterized by two integers: its price ci and its size si. We know that on this very day all numbers si are different, that is, there is no more than one pair of each size.
The shop has m customers who came at the same time. The customer number i has di money and the size of his feet equals li. The customer number i can buy the pair number j, if cj β€ di, and also if li = sj or li = sj - 1; that is, it is necessary that he has enough money to pay for the shoes. It is also necessary that the size of his feet equals to or is less by 1 than the size of the shoes he chooses.
Your task is to sell some customers pairs of shoes (a pair per person) so as to maximize the sum of the sold pairs cj that is, the profit. It is guaranteed that each customer buys no more than one pair and each pair will be bought by no more than one customer.
Input
The first input line contains the only integer n (1 β€ n β€ 105) β the number of shoe pairs in the warehouse. Then n lines contain the descriptions of pairs of shoes as two integers ci and si (1 β€ ci, si β€ 109), the numbers are separated by a space. It is guaranteed that all numbers si are different.
The next line contains an integer m (1 β€ m β€ 105) β the number of customers in the shop. Next m lines contain the customers' descriptions as two integers di and li (1 β€ di, li β€ 109), the numbers are separated by a space.
Output
In the first line print the only integer β the maximum profit you can get from selling shoes. In the second line print an integer k β the number of shoe pairs you will sell. In the following k lines print the descriptions of the sold pairs β two space-separated integers where the first number is the customer's number and the second number is the number of the shoes the customer will buy.
You can print pairs of numbers "the customer's number and the shoes' number" in any order, the customers and the pairs of shoes are numbered starting from 1 in the order in which they are given in the input. If there are several optimal answers, you are allowed to print any of them.
Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator instead.
Examples
Input
3
10 1
30 2
20 3
2
20 1
20 2
Output
30
2
2 3
1 1
Input
3
10 4
20 5
30 6
2
70 4
50 5
Output
50
2
2 3
1 2
Submitted Solution:
```
number_shoes = int(input())
shoes_desc = []
costumer_desc = []
def get_shoes_descr(number):
fliste = []
for shoe in range(1,number+1):
prix, taill = map(int, input().split())
fliste.append((prix , taill,shoe))
return sorted(fliste,key=lambda x:[x[0], x[1]],reverse=True)
shoes_desc = get_shoes_descr(number_shoes)
number_costomer = int(input())
costumer_desc = get_shoes_descr(number_costomer)
prix = 0
nbr = 0
infos = []
for i in range(len(shoes_desc)):
j = 0
while j < len(costumer_desc):
if shoes_desc[i][0] <= costumer_desc[j][0] and (shoes_desc[i][1] == costumer_desc[j][1] or (shoes_desc[i][1]-1) == costumer_desc[j][1]) :
prix+=shoes_desc[i][0]
nbr+=1
infos.append([costumer_desc[j][2],shoes_desc[i][2]])
costumer_desc.remove(costumer_desc[j])
j+=1
print(prix)
print(nbr)
for elms in infos:
print(elms[0],"",elms[1])
```
No
| 1,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The warehouse in your shop has n shoe pairs. Each pair is characterized by two integers: its price ci and its size si. We know that on this very day all numbers si are different, that is, there is no more than one pair of each size.
The shop has m customers who came at the same time. The customer number i has di money and the size of his feet equals li. The customer number i can buy the pair number j, if cj β€ di, and also if li = sj or li = sj - 1; that is, it is necessary that he has enough money to pay for the shoes. It is also necessary that the size of his feet equals to or is less by 1 than the size of the shoes he chooses.
Your task is to sell some customers pairs of shoes (a pair per person) so as to maximize the sum of the sold pairs cj that is, the profit. It is guaranteed that each customer buys no more than one pair and each pair will be bought by no more than one customer.
Input
The first input line contains the only integer n (1 β€ n β€ 105) β the number of shoe pairs in the warehouse. Then n lines contain the descriptions of pairs of shoes as two integers ci and si (1 β€ ci, si β€ 109), the numbers are separated by a space. It is guaranteed that all numbers si are different.
The next line contains an integer m (1 β€ m β€ 105) β the number of customers in the shop. Next m lines contain the customers' descriptions as two integers di and li (1 β€ di, li β€ 109), the numbers are separated by a space.
Output
In the first line print the only integer β the maximum profit you can get from selling shoes. In the second line print an integer k β the number of shoe pairs you will sell. In the following k lines print the descriptions of the sold pairs β two space-separated integers where the first number is the customer's number and the second number is the number of the shoes the customer will buy.
You can print pairs of numbers "the customer's number and the shoes' number" in any order, the customers and the pairs of shoes are numbered starting from 1 in the order in which they are given in the input. If there are several optimal answers, you are allowed to print any of them.
Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator instead.
Examples
Input
3
10 1
30 2
20 3
2
20 1
20 2
Output
30
2
2 3
1 1
Input
3
10 4
20 5
30 6
2
70 4
50 5
Output
50
2
2 3
1 2
Submitted Solution:
```
number_shoes = int(input())
shoes_desc = []
costumer_desc = []
def get_shoes_descr(number):
fliste = []
for shoe in range(1,number+1):
prix, taill = map(int, input().split())
fliste.append((prix , taill,shoe))
return sorted(fliste,key=lambda x:[x[0], x[1]],reverse=True)
shoes_desc = get_shoes_descr(number_shoes)
number_costomer = int(input())
costumer_desc = get_shoes_descr(number_costomer)
prix = 0
nbr = 0
infos = []
for i in range(len(shoes_desc)):
j = 0
while j < len(costumer_desc):
if shoes_desc[i][0] <= costumer_desc[j][0] and (shoes_desc[i][1] == costumer_desc[j][1] or (shoes_desc[i][1]-1) == costumer_desc[j][1]) :
prix+=shoes_desc[i][0]
nbr+=1
infos.append([costumer_desc[j][2],shoes_desc[i][2]])
costumer_desc.remove(costumer_desc[j])
break
j += 1
print(prix)
print(nbr)
for elms in infos:
print(elms[0],"",elms[1])
```
No
| 1,902 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The warehouse in your shop has n shoe pairs. Each pair is characterized by two integers: its price ci and its size si. We know that on this very day all numbers si are different, that is, there is no more than one pair of each size.
The shop has m customers who came at the same time. The customer number i has di money and the size of his feet equals li. The customer number i can buy the pair number j, if cj β€ di, and also if li = sj or li = sj - 1; that is, it is necessary that he has enough money to pay for the shoes. It is also necessary that the size of his feet equals to or is less by 1 than the size of the shoes he chooses.
Your task is to sell some customers pairs of shoes (a pair per person) so as to maximize the sum of the sold pairs cj that is, the profit. It is guaranteed that each customer buys no more than one pair and each pair will be bought by no more than one customer.
Input
The first input line contains the only integer n (1 β€ n β€ 105) β the number of shoe pairs in the warehouse. Then n lines contain the descriptions of pairs of shoes as two integers ci and si (1 β€ ci, si β€ 109), the numbers are separated by a space. It is guaranteed that all numbers si are different.
The next line contains an integer m (1 β€ m β€ 105) β the number of customers in the shop. Next m lines contain the customers' descriptions as two integers di and li (1 β€ di, li β€ 109), the numbers are separated by a space.
Output
In the first line print the only integer β the maximum profit you can get from selling shoes. In the second line print an integer k β the number of shoe pairs you will sell. In the following k lines print the descriptions of the sold pairs β two space-separated integers where the first number is the customer's number and the second number is the number of the shoes the customer will buy.
You can print pairs of numbers "the customer's number and the shoes' number" in any order, the customers and the pairs of shoes are numbered starting from 1 in the order in which they are given in the input. If there are several optimal answers, you are allowed to print any of them.
Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator instead.
Examples
Input
3
10 1
30 2
20 3
2
20 1
20 2
Output
30
2
2 3
1 1
Input
3
10 4
20 5
30 6
2
70 4
50 5
Output
50
2
2 3
1 2
Submitted Solution:
```
number_shoes = int(input())
shoes_desc = []
costumer_desc = []
def get_shoes_descr(number):
fliste = []
for shoe in range(1,number+1):
prix, taill = map(int, input().split())
fliste.append((prix , taill,shoe))
return sorted(fliste,key=lambda x:[x[0], x[1]],reverse=True)
shoes_desc = get_shoes_descr(number_shoes)
number_costomer = int(input())
costumer_desc = get_shoes_descr(number_costomer)
prix = 0
nbr = 0
infos = []
i = 0
while i < len(shoes_desc):
j = 0
while j < len(costumer_desc):
if shoes_desc[i][0] <= costumer_desc[j][0] and (shoes_desc[i][1] == costumer_desc[j][1] or (shoes_desc[i][1]-1) == costumer_desc[j][1]) :
prix+=shoes_desc[i][0]
nbr+=1
infos.append([costumer_desc[j][2],shoes_desc[i][2]])
costumer_desc.remove(costumer_desc[j])
break
j += 1
shoes_desc.remove(shoes_desc[i])
print(prix)
print(nbr)
for elms in infos:
print(elms[0],"",elms[1])
```
No
| 1,903 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Tags: dp, graphs, shortest paths
Correct Solution:
```
from collections import deque
def put():
return map(int, input().split())
def bfs(s):
q,dis,cnt = deque(), [-1]*n,[0]*n
q.append(s)
dis[s],cnt[s]=0,1
while q:
x = q.popleft()
for y in graph[x]:
if dis[y]==-1:
dis[y]=dis[x]+1
cnt[y]+=cnt[x]
q.append(y)
elif dis[y]==dis[x]+1:
cnt[y]+=cnt[x]
return cnt, dis
def solve():
for _ in range(m):
x,y = put()
x,y = x-1,y-1
graph[x].append(y)
graph[y].append(x)
c,d = bfs(0)
ans = 0
for i in range(n):
x,y = bfs(i)
if y[0]+y[n-1]==d[n-1]:
z = x[0]*x[n-1]
if i not in [0, n-1]: z*=2
ans = max(ans, z)
ans/=c[n-1]
print(ans)
n,m = put()
graph = [[] for i in range(n)]
solve()
```
| 1,904 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Tags: dp, graphs, shortest paths
Correct Solution:
```
from collections import deque
n, m = [int(i) for i in input().split()]
g = [[] for i in range(n)]
for i in range(m):
u, v = [int(i) - 1 for i in input().split()]
g[u].append(v)
g[v].append(u)
def bfs(s):
d = [-1] * n
ct = [0.0] * n
q = deque()
d[s] = 0
ct[s] = 1.0
q.append(s)
while q:
v = q.popleft()
for u in g[v]:
if d[u] == -1:
q.append(u)
d[u] = d[v] + 1
ct[u] += ct[v]
elif d[u] == d[v] + 1:
ct[u] += ct[v]
return d, ct
ds = []
cts = []
for i in range(n):
d, ct = bfs(i)
ds.append(d)
cts.append(ct)
x = cts[0][n - 1]
r = 1.0
for i in range(1, n - 1):
if ds[0][i] + ds[i][n - 1] == ds[0][n - 1]:
r = max(r, 2.0 * cts[0][i] * cts[i][n - 1] / x)
print('{0:.10f}'.format(r))
```
| 1,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Tags: dp, graphs, shortest paths
Correct Solution:
```
from collections import deque
n, m = [int(i) for i in input().split()]
g = [[] for i in range(n)]
for i in range(m):
u, v = [int(i) - 1 for i in input().split()]
g[u].append(v)
g[v].append(u)
def bfs(s):
d = [-1] * n
ct = [0.0] * n
q = deque()
d[s] = 0
ct[s] = 1.0
q.append(s)
while q:
v = q.popleft()
for u in g[v]:
if d[u] == -1:
q.append(u)
d[u] = d[v] + 1
ct[u] += ct[v]
elif d[u] == d[v] + 1:
ct[u] += ct[v]
return d, ct
ds = []
cts = []
for i in range(n):
d, ct = bfs(i)
ds.append(d)
cts.append(ct)
x = cts[0][n - 1]
r = 1.0
for i in range(1, n - 1):
if ds[0][i] + ds[i][n - 1] == ds[0][n - 1]:
r = max(r, 2.0 * cts[0][i] * cts[i][n - 1] / x)
print('{0:.10f}'.format(r))
# Made By Mostafa_Khaled
```
| 1,906 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Tags: dp, graphs, shortest paths
Correct Solution:
```
n, m = map(int, input().split())
adj = [[] for i in range(n)]
for _ in range(m):
a, b = map(int, input().split())
adj[a-1].append(b-1)
adj[b-1].append(a-1)
def bfs(s):
q, d, res = [s], [-1] * n, [0] * n
d[s] = 0
res[s] = 1
i = 0
while i < len(q):
v = q[i]
for u in adj[v]:
if d[u] == -1:
d[u] = d[v] + 1
q.append(u)
if d[u] == d[v] + 1:
res[u] += res[v]
i += 1
return q, d, res
q0, d0, res0 = bfs(0)
q1, d1, res1 = bfs(n-1)
min_dist = d0[n-1]
num_paths = res0[n-1]
res = num_paths
for v in range(1, n-1):
if d0[v] + d1[v] == min_dist:
res = max(res, 2 * res0[v] * res1[v])
print('%.7f' % (res / num_paths))
```
| 1,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Tags: dp, graphs, shortest paths
Correct Solution:
```
read_line = lambda: map(int, input().split(' '))
n, m = read_line()
g = [[] for i in range(n)]
while m:
a, b = map(lambda x: x - 1, read_line())
g[a].append(b)
g[b].append(a)
m -= 1
def bfs(v0):
q = [v0]
d = [-1] * n
d[v0] = 0
ways = [0] * n
ways[v0] = 1
i = 0
while i < len(q):
v = q[i]
for w in g[v]:
if d[w] == -1:
d[w] = d[v] + 1
q.append(w)
if d[w] == d[v] + 1:
ways[w] += ways[v]
i += 1
return q, d, ways
q0, d0, ways0 = bfs(0)
q1, d1, ways1 = bfs(n - 1)
min_dist = d0[n - 1]
num_paths = ways0[n - 1]
ans = num_paths
for v in range(1, n - 1):
if d0[v] + d1[v] == min_dist:
ans = max(ans, 2 * ways0[v] * ways1[v])
print('{:.7f}'.format(ans / num_paths))
```
| 1,908 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Tags: dp, graphs, shortest paths
Correct Solution:
```
#build the graph with n cities and m roads
#figure out all of the shortest paths from city 1 to city n
#best=number of shortest paths (if we have police station at 1 or n)
s=list(map(int,input().split()))
n=s[0]
m=s[1]
roads=[]
Adj=[]
for i in range(0,n+1):
roads.append([])
Adj.append([False]*(n+1))
for i in range(0,m):
s=list(map(int,input().split()))
roads[s[0]].append(s[1])
roads[s[1]].append(s[0])
Adj[s[0]][s[1]]=True
Adj[s[1]][s[0]]=True
#we gotta count how many shortest paths from 1 to n
#first bfs to find the length of the shortest path
#in our bfs, all the nodes now have "levels" from 1
Dist=[200]*(n+1)
Q=[1]
Dist[1]=0
while len(Q)>0:
curr=Q.pop(0)
for nex in roads[curr]:
if Dist[nex]==200: #not Visited
Dist[nex]=Dist[curr]+1
Q.append(nex)
Levels=[]
for l in range(0,100):
Levels.append([])
for p in range(1,n+1):
if Dist[p]==l:
Levels[l].append(p)
#given a point p, paths[a][p]=sigma(paths[a][v]) where v is all of the points
# on a level lower than p, connected to p
fromOne=[0]*(n+1)
def fo(b):
"""how many shortest paths from 1 to b"""
if fromOne[b]>0:
return fromOne[b]
if b==1:
return 1
ans=0
for p in Levels[Dist[b]-1]:
if Adj[p][b]:
ans+=fo(p)
fromOne[b]=ans
return ans
toN=[0]*(n+1)
def tN(b):
"""how many shortest paths from 1 to b"""
if toN[b]>0:
return toN[b]
if b==n:
return 1
ans=0
for p in Levels[Dist[b]+1]:
if Adj[p][b]:
ans+=tN(p)
toN[b]=ans
return ans
#OHHH we count how many shortest paths include policeStation
best=fo(n)
for policeStation in range(2,n):
safe=fo(policeStation)*tN(policeStation)*2
best=max(best,safe)
print(round(best/fo(n),10))
```
| 1,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Submitted Solution:
```
from collections import deque
def put():
return map(int, input().split())
def bfs(s):
q,dis,cnt = deque(), [-1]*n,[0]*n
q.append(s)
dis[s],cnt[s]=0,1
while q:
x = q.popleft()
for y in graph[x]:
if dis[y]==-1:
dis[y]=dis[x]+1
cnt[y]+=cnt[x]
q.append(y)
elif dis[y]==dis[x]+1:
cnt[y]+=cnt[x]
return cnt, dis
def solve():
for _ in range(m):
x,y = put()
x,y = x-1,y-1
graph[x].append(y)
graph[y].append(x)
c,d = bfs(0)
ans = 0
for i in range(n):
x,y = bfs(i)
if y[0]+y[n-1]==d[n-1]:
z = x[0]*x[n-1]
if i not in [0, n-1]: z*=2
ans = max(ans, z)
print(ans,c[n-1])
ans/=c[n-1]
print(ans)
n,m = put()
graph = [[] for i in range(n)]
solve()
```
No
| 1,910 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Submitted Solution:
```
raw = input().split()
n = int(raw[0])
m = int(raw[1])
mat = [[False for j in range(n)] for i in range(n)]
for i in range(m):
raw = input().split()
u = int(raw[0]) - 1
v = int(raw[1]) - 1
mat[u][v] = mat[v][u] = True
inf = 100000000000
dist = [inf for i in range(n)]
dp = [0 for i in range(n)]
from collections import *
dp[0] = 1
q = deque()
q.append(0)
dist[0] = 0
while (len(q) > 0):
cur = q.popleft()
for i in range(n):
if mat[cur][i]:
if dist[cur] + 1 < dist[i]:
dist[i] = dist[cur] + 1
dp[i] = dp[cur]
elif dist[cur] + 1 == dist[i]:
dp[i] += dp[cur]
continue
else:
continue
q.append(i)
res = dp.copy()
dist = [inf for i in range(n)]
dp = [0 for i in range(n)]
dp[n - 1] = 1
q = deque()
q.append(n - 1)
dist[n - 1] = 0
while (len(q) > 0):
cur = q.popleft()
for i in range(n):
if mat[cur][i]:
if dist[cur] + 1 < dist[i]:
dist[i] = dist[cur] + 1
dp[i] = dp[cur]
# print('from ' + str(cur) + ' to ' + str(i))
elif dist[cur] + 1 == dist[i]:
# print('equals from ' + str(cur) + ' to ' + str(i))
dp[i] += dp[cur]
# print(dp[cur])
# print(dp[i])
continue
else:
continue
q.append(i)
# for i in range(n):
# print(str(i) + ' dist ' + str(dist[i]))
for i in range(n):
# print(str(res[i]) + " " + str(dp[i]))
res[i] = res[i] * dp[i]
maxx = 0
for i in range(1, n - 1):
maxx = max(maxx, res[i])
print(max(maxx * 2 / res[0], 1))
```
No
| 1,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Submitted Solution:
```
from collections import deque
n, m = [int(i) for i in input().split()]
g = [[] for i in range(n)]
for i in range(m):
u, v = [int(i) - 1 for i in input().split()]
g[u].append(v)
g[v].append(u)
def bfs(s):
d = [-1] * n
ct = [0.0] * n
q = deque()
d[s] = 0
ct[s] = 1
q.append(s)
while q:
v = q.popleft()
for u in g[v]:
if d[u] == -1:
q.append(u)
d[u] = d[v] + 1
ct[u] += ct[v]
elif d[u] == d[v] + 1:
ct[u] += ct[v]
return ct
cts = []
for i in range(n):
cts.append(bfs(i))
x = cts[0][n - 1]
r = 1.0
for i in range(1, n - 1):
r = max(r, 2 * cts[0][i] * cts[i][n - 1] / x)
print('{0:.10f}'.format(r))
```
No
| 1,912 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.
All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).
The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.
Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.
Input
The first input line contains two integers n and m (2 β€ n β€ 100, <image>) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1 β€ vi, ui β€ n, vi β ui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space.
It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.
Output
Print the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10 - 6.
Examples
Input
4 4
1 2
2 4
1 3
3 4
Output
1.000000000000
Input
11 14
1 2
1 3
2 4
3 4
4 5
4 6
5 11
6 11
1 8
8 9
9 7
11 7
1 10
10 4
Output
1.714285714286
Note
In the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make <image>.
In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal <image>.
Submitted Solution:
```
s=list(map(int,input().split()))
n=s[0]
m=s[1]
roads=[]
Adj=[]
for i in range(0,n+1):
roads.append([])
Adj.append([False]*(n+1))
for i in range(0,m):
s=list(map(int,input().split()))
roads[s[0]].append(s[1])
roads[s[1]].append(s[0])
Adj[s[0]][s[1]]=True
Adj[s[1]][s[0]]=True
#we gotta count how many shortest paths from 1 to n
#first bfs to find the length of the shortest path
#in our bfs, all the nodes now have "levels" from 1
Dist=[200]*(n+1)
Q=[1]
Dist[1]=0
while len(Q)>0:
curr=Q.pop(0)
for nex in roads[curr]:
if Dist[nex]==200: #not Visited
Dist[nex]=Dist[curr]+1
Q.append(nex)
Levels=[]
for l in range(0,100):
Levels.append([])
for p in range(1,n+1):
if Dist[p]==l:
Levels[l].append(p)
#given a point p, paths[a][p]=sigma(paths[a][v]) where v is all of the points
# on a level lower than p, connected to p
paths=[]
for i in range(0,n+1):
paths.append([0]*(n+1))
def dp(a,b):
"""how many shortest paths from a to b"""
if paths[a][b]>0:
return paths[a][b]
if a==b:
return 1
if b<a:
return dp(b,a)
ans=0
for p in Levels[Dist[b]-1]:
if Adj[p][b]:
ans+=dp(a,p)
paths[a][b]=ans
return ans
for a in range(1,n+1):
for b in range(1,n+1):
paths[a][b]=dp(a,b)
#OHHH we count how many shortest paths include policeStation
best=paths[1][n]
for policeStation in range(2,n):
safe=paths[1][policeStation]*paths[policeStation][n]*2
best=max(best,safe)
print(round(best/paths[1][n],10))
```
No
| 1,913 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the <image> desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.
But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.
On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.
Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.
Input
The first input line contains a single even integer n (4 β€ n β€ 100) β the number of students in the class. The second line contains exactly n capital English letters "L" and "R". If the i-th letter at the second line equals "L", then the student number i is a lefthander, otherwise he is a righthander.
Output
Print <image> integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.
Examples
Input
6
LLRLLL
Output
1 4
2 5
6 3
Input
4
RRLL
Output
3 1
4 2
Submitted Solution:
```
def main():
with open('input.txt', 'r') as f:
n, s = int(f.readline()), f.readline()
with open('output.txt', 'w') as f:
for i in range(0, n, 2):
j = i + n // 2
if s[i] == 'R' and s[j] == 'L':
i, j = j, i
f.write("%d %d\n" % (i + 1, j + 1))
if __name__ == '__main__':
main()
```
No
| 1,914 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the <image> desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.
But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.
On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.
Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.
Input
The first input line contains a single even integer n (4 β€ n β€ 100) β the number of students in the class. The second line contains exactly n capital English letters "L" and "R". If the i-th letter at the second line equals "L", then the student number i is a lefthander, otherwise he is a righthander.
Output
Print <image> integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.
Examples
Input
6
LLRLLL
Output
1 4
2 5
6 3
Input
4
RRLL
Output
3 1
4 2
Submitted Solution:
```
i,o=open("input.txt","r"),open("output.txt","w")
n,a=int(i.readline().strip()),i.readline().strip()
for i in range(n-2) :
if a[i] == 'L' :
o.write(str(i+1)+" "+str(i+3)+"\n")
else :
o.write(str(i+3)+" "+str(i+1)+"\n")
```
No
| 1,915 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the <image> desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.
But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.
On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.
Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.
Input
The first input line contains a single even integer n (4 β€ n β€ 100) β the number of students in the class. The second line contains exactly n capital English letters "L" and "R". If the i-th letter at the second line equals "L", then the student number i is a lefthander, otherwise he is a righthander.
Output
Print <image> integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.
Examples
Input
6
LLRLLL
Output
1 4
2 5
6 3
Input
4
RRLL
Output
3 1
4 2
Submitted Solution:
```
#import math
#n, m = input().split()
#n = int (n)
#m = int (m)
#n, m, k , l= input().split()
#n = int (n)
#m = int (m)
#k = int (k)
#l = int(l)
#n = int(input())
#m = int(input())
#s = input()
##t = input()
#a = list(map(char, input().split()))
#a.append('.')
#print(l)
#c = list(map(int, input().split()))
#c = sorted(c)
#x1, y1, x2, y2 =map(int,input().split())
#n = int(input())
#f = []
#t = [0]*n
#f = [(int(s1[0]),s1[1]), (int(s2[0]),s2[1]), (int(s3[0]), s3[1])]
#f1 = sorted(t, key = lambda tup: tup[0])
inp=open("input.txt","r")
out = open("output.txt","w")
n = int(inp.readline())
s = inp.readline()
l = 0
r = 0
sitz = [0] * n
for i in range (n):
if(s[i] == 'R' and r < n/2):
sitz[r*2+1] = i
r += 1
elif (s[i] == 'R'):
sitz[l*2] = i
l += 1
elif(s[i] == 'L' and l < n/2):
sitz[l*2] = i
l += 1
elif (s[i] == 'L'):
sitz[r*2+1] = i
r += 1
for i in range(0,n, 2):
out.write(str(sitz[i]+1) + " "+ str(sitz[i+1]+1)+ "\n")
out.close()
inp.close()
```
No
| 1,916 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the <image> desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.
But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.
On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.
Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.
Input
The first input line contains a single even integer n (4 β€ n β€ 100) β the number of students in the class. The second line contains exactly n capital English letters "L" and "R". If the i-th letter at the second line equals "L", then the student number i is a lefthander, otherwise he is a righthander.
Output
Print <image> integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.
Examples
Input
6
LLRLLL
Output
1 4
2 5
6 3
Input
4
RRLL
Output
3 1
4 2
Submitted Solution:
```
#import math
#n, m = input().split()
#n = int (n)
#m = int (m)
#n, m, k , l= input().split()
#n = int (n)
#m = int (m)
#k = int (k)
#l = int(l)
#n = int(input())
#m = int(input())
#s = input()
##t = input()
#a = list(map(char, input().split()))
#a.append('.')
#print(l)
#c = list(map(int, input().split()))
#c = sorted(c)
#x1, y1, x2, y2 =map(int,input().split())
#n = int(input())
#f = []
#t = [0]*n
#f = [(int(s1[0]),s1[1]), (int(s2[0]),s2[1]), (int(s3[0]), s3[1])]
#f1 = sorted(t, key = lambda tup: tup[0])
inp=open("input.txt","r")
out = open("output.txt","w")
n = int(inp.readline())
s = inp.readline()
l = 0
r = 0
sitz = [0] * n
for i in range (n):
if l < n/2:
sitz[l *2] = i
l += 1
else:
sitz[r*2+1] = i
r += 1
for i in range(0,n, 2):
if (s[sitz[i] == 'L' and s[sitz[i+1]] == 'R']):
sitz[i], sitz[i+1] = sitz[i+1], sitz[i]
out.write(str(sitz[i]+1) + " "+ str(sitz[i+1]+1)+ "\n")
out.close()
inp.close()
```
No
| 1,917 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!
In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage.
One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.
But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).
The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.
Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
Input
The first line contains an integer n (1 β€ n β€ 105).
The next line contains n integers a1, a2, ..., an (0 β€ ai β€ 1012) β Mr. Bitkoch's sausage.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single integer β the maximum pleasure BitHaval and BitAryo can get from the dinner.
Examples
Input
2
1 2
Output
3
Input
3
1 2 3
Output
3
Input
2
1000 1000
Output
1000
Submitted Solution:
```
# Why do we fall ? So we can learn to pick ourselves up.
class Node:
def __init__(self):
self.left = None
self.right = None
self.cnt = 0
class Trie:
def __init__(self):
self.root = Node()
def insert(self,x):
self.temp = self.root
for i in range(43,-1,-1):
curbit = (x>>i)&1
if curbit:
if not self.temp.right:
self.temp.right = Node()
self.temp = self.temp.right
self.temp.cnt += 1
else:
if not self.temp.left:
self.temp.left = Node()
self.temp = self.temp.left
self.temp.cnt += 1
def remove(self,x):
self.temp = self.root
for i in range(43,-1,-1):
curbit = (x>>i)&1
if curbit:
self.temp = self.temp.right
self.temp.cnt -= 1
else:
self.temp = self.temp.left
self.temp.cnt -= 1
def maxxor(self,x):
self.temp = self.root
self.ss = 0
for i in range(31,-1,-1):
curbit = (x>>i)&1
if curbit:
if self.temp.left and self.temp.left.cnt:
self.ss += (1<<i)
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.cnt:
self.ss += (1<<i)
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
return self.ss
n = int(input())
trie = Trie()
trie.insert(0)
aa = [0]+[int(i) for i in input().split()]
pref = [0]*(n+2)
suff = [0]*(n+2)
for i in range(1,n+1):
pref[i] = pref[i-1]^aa[i]
trie.insert(pref[i])
for i in range(n,0,-1):
suff[i] = suff[i+1]^aa[i]
maxi = trie.maxxor(0)
for i in range(n,0,-1):
trie.remove(pref[i])
maxi = max(maxi,trie.maxxor(suff[i]))
print(maxi)
"""
2
1000 1000
"""
```
No
| 1,918 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!
In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage.
One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.
But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).
The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.
Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
Input
The first line contains an integer n (1 β€ n β€ 105).
The next line contains n integers a1, a2, ..., an (0 β€ ai β€ 1012) β Mr. Bitkoch's sausage.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single integer β the maximum pleasure BitHaval and BitAryo can get from the dinner.
Examples
Input
2
1 2
Output
3
Input
3
1 2 3
Output
3
Input
2
1000 1000
Output
1000
Submitted Solution:
```
n = int(input())
arr = list(map(int, input().strip().split()))
preA = [0] * n
postA = [0] * n
xor = 0
for i in arr:
xor ^= i
pre = 0
res = 0
for i in range(len(arr)):
pre ^= arr[i]
post = xor ^ pre
postA[i] = post
preA[i] = pre
for i in range(n):
a = i + 1
while a < n:
res = max(res, preA[i]^postA[a])
a += 1
print(res)
```
No
| 1,919 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!
In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage.
One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.
But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).
The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.
Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
Input
The first line contains an integer n (1 β€ n β€ 105).
The next line contains n integers a1, a2, ..., an (0 β€ ai β€ 1012) β Mr. Bitkoch's sausage.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single integer β the maximum pleasure BitHaval and BitAryo can get from the dinner.
Examples
Input
2
1 2
Output
3
Input
3
1 2 3
Output
3
Input
2
1000 1000
Output
1000
Submitted Solution:
```
# Why do we fall ? So we can learn to pick ourselves up.
class Node:
def __init__(self):
self.left = None
self.right = None
self.cnt = 0
class Trie:
def __init__(self):
self.root = Node()
def insert(self,x):
self.temp = self.root
for i in range(31,-1,-1):
curbit = (x>>i)&1
if curbit:
if not self.temp.right:
self.temp.right = Node()
self.temp = self.temp.right
self.temp.cnt += 1
else:
if not self.temp.left:
self.temp.left = Node()
self.temp = self.temp.left
self.temp.cnt += 1
def remove(self,x):
self.temp = self.root
for i in range(31,-1,-1):
curbit = (x>>i)&1
if curbit:
self.temp = self.temp.right
self.temp.cnt -= 1
else:
self.temp = self.temp.left
self.temp.cnt -= 1
def maxxor(self,x):
self.temp = self.root
self.ss = 0
for i in range(31,-1,-1):
curbit = (x>>i)&1
if curbit:
if self.temp.left and self.temp.left.cnt:
self.ss += (1<<i)
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.cnt:
self.ss += (1<<i)
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
return self.ss
n = int(input())
trie = Trie()
trie.insert(0)
aa = [0]+[int(i) for i in input().split()]
pref = [0]*(n+2)
suff = [0]*(n+2)
for i in range(1,n+1):
pref[i] = pref[i-1]^aa[i]
trie.insert(pref[i])
for i in range(n,0,-1):
suff[i] = suff[i+1]^aa[i]
maxi = trie.maxxor(0)
for i in range(n,0,-1):
trie.remove(pref[i])
maxi = max(maxi,trie.maxxor(suff[i]))
print(maxi)
"""
2
1000 1000
"""
```
No
| 1,920 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!
In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage.
One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.
But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).
The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.
Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.
Input
The first line contains an integer n (1 β€ n β€ 105).
The next line contains n integers a1, a2, ..., an (0 β€ ai β€ 1012) β Mr. Bitkoch's sausage.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single integer β the maximum pleasure BitHaval and BitAryo can get from the dinner.
Examples
Input
2
1 2
Output
3
Input
3
1 2 3
Output
3
Input
2
1000 1000
Output
1000
Submitted Solution:
```
n = int(input())
arr = list(map(int, input().strip().split()))
preA = [0] * n
postA = [0] * n
xor = 0
for i in arr:
xor ^= i
pre = 0
res = 0
for i in range(n):
pre ^= arr[i]
post = xor ^ pre
postA[i] = post
preA[i] = pre
#print(preA,postA)
for i in range(n):
a = i
while a < n:
res = max(res, preA[i]^postA[a])
a += 1
print(res)
```
No
| 1,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Tags: dp
Correct Solution:
```
# n = 24
def get_subs(n):
count = 0
while n != '0':
digits = [int(i) for i in n]
max_digit = max(digits)
n = int(n) - max_digit
n = str(n)
count += 1
return count
if __name__ == '__main__':
n = input()
print(get_subs(n))
```
| 1,922 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Tags: dp
Correct Solution:
```
t = int(input())
c = 0
while t!=0:
c+=1
t = t-int(max(str(t)))
print(c)
```
| 1,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Tags: dp
Correct Solution:
```
n = int(input())
count = 0
while n:
maxi = 0
nn = n
while nn:
maxi = max(maxi, nn%10)
nn //= 10
count += 1
n -= maxi
print(count)
```
| 1,924 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Tags: dp
Correct Solution:
```
import math
from math import gcd,floor,sqrt,log
def iin(): return int(input())
def sin(): return input().strip()
def listin(): return list(map(int,input().strip().split()))
def liststr(): return list(map(str,input().strip().split()))
def ceill(x): return int(x) if(x==int(x)) else int(x)+1
def ceilldiv(x,d): x//d if(x%d==0) else x//d+1
def LCM(a,b): return (a*b)//gcd(a,b)
n = iin()
cnt=0
while n>0:
n -= int(max(str(n)))
cnt+=1
print(cnt)
```
| 1,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Tags: dp
Correct Solution:
```
import math
import sys
input = sys.stdin.readline
n = int(input())
opt = 0
while n != 0:
n -= int(max(list(str(n))))
opt += 1
print(opt)
```
| 1,926 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Tags: dp
Correct Solution:
```
n = int(input())
f = n
s = 1
while n > 9:
n -= max(map(int, str(n)))
s += 1
if f == 0: print(0)
else: print(s)
```
| 1,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Tags: dp
Correct Solution:
```
from sys import stdin,stdout
from math import gcd,sqrt,factorial,inf
from collections import deque,defaultdict
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
L=lambda:list(R())
P=lambda x:stdout.write(x)
lcm=lambda x,y:(x*y)//gcd(x,y)
hg=lambda x,y:((y+x-1)//x)*x
pw=lambda x:0 if x==1 else 1+pw(x//2)
chk=lambda x:chk(x//2) if not x%2 else True if x==1 else False
sm=lambda x:(x**2+x)//2
N=10**9+7
def max_int(n):
m=-inf
while n:
m=max(m,n%10)
n//=10
return m
n=I()
ans=0
while n:
ans+=1
n-=max_int(n)
print(ans)
```
| 1,928 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Tags: dp
Correct Solution:
```
n = int(input())
k = 0
m = 0
while int(n) != 0:
m = int(max(str(n)))
n -= m
k += 1
print(k)
```
| 1,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Submitted Solution:
```
n=int(input())
dp=[0]+[1e9+7]*(n)
for i in range(1,n+1):
tmp=i
while tmp:
dp[i]=min(dp[i],dp[i-tmp%10]+1)
tmp//=10
print(int(dp[n]))
```
Yes
| 1,930 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Submitted Solution:
```
n, count = int(input()), 0
while n > 0:
nList = [int(i) for i in str(n)]
n -= max(nList)
count += 1
print(count)
```
Yes
| 1,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Submitted Solution:
```
n = input()
cnt = 0
while int(n) > 0:
n = str(int(n) - int(max(n)))
cnt += 1
print(cnt)
```
Yes
| 1,932 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Submitted Solution:
```
n = int(input())
steps = 0
while n:
n -= int(max(str(n)))
steps+=1
print(steps)
```
Yes
| 1,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Submitted Solution:
```
from math import *
from copy import *
from string import * # alpha = ascii_lowercase
from random import *
from sys import stdin
from sys import maxsize
from operator import * # d = sorted(d.items(), key=itemgetter(1))
from itertools import *
from collections import Counter # d = dict(Counter(l))
import math
def bin1(l,r,k,t,b,val,ans):
if(l>r):
return ans
else:
mid=(l+r)//2
v=k**mid
if(v==val):
return v
elif(v>val):
ans=mid
return bin1(mid+1,r,k,t,b,val,ans)
else:
return bin1(l,mid-1,k,t,b,val,ans)
def bin2(l,r,k,t,b,val,ans):
if(l>r):
return ans
else:
mid=(l+r)//2
v=t*(k**mid)+b*(mid)
if(v==val):
return v
elif(v>val):
ans=mid
return bin2(l,mid-1,k,t,b,val,ans)
else:
return bin2(mid+1,r,k,t,b,val,ans)
def SieveOfEratosthenes(n):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
l=[]
for i in range(2,n+1):
if(prime[i]):
l.append(i)
return l
def bin(l,r,ll,val):
if(l>r):
return -1
else:
mid=(l+r)//2
if(val>=ll[mid][0] and val<=ll[mid][1]):
return mid
elif(val<ll[mid][0]):
return bin(l,mid-1,ll,val)
else:
return bin(mid+1,r,ll,val)
def deci(n):
s=""
while(n!=0):
if(n%2==0):
n=n//2
s="0"+s
else:
n=n//2
s="1"+s
return s
def diff(s1,s2):
if(len(s1)<len(s2)):
v=len(s1)
while(v!=len(s2)):
s1="0"+s1
v=v+1
else:
v=len(s2)
while(v!=len(s1)):
s2="0"+s2
v=v+1
c=0
for i in range(len(s1)):
if(s1[i:i+1]!=s2[i:i+1]):
c=c+1
return c
from sys import stdin, stdout
def fac(a,b):
v=a
while(a!=b):
v*=a-1
a=a-1
return v
def bino(l,r,n):
if(l>r):
return -1
else:
mid=(l+r)//2
val1=math.log((n/mid)+1,2)
val2=int(val1)
if(val1==val2):
return val1
elif(val1<1.0):
return bino(l,mid-1,n)
else:
return bino(mid+1,r,n)
def binary(l,r,ll,val,ans):
if(l>r):
return ans
else:
mid=(l+r)//2
if(val%ll[mid]==0):
ans=ll[mid]
return binary(l,mid-1,ll,val,ans)
else:
return binary(l,mid-1,ll,val,ans)
def odd(n,ans,s):
if(n%2!=0 or n in s):
return ans
else:
s.add(n)
return odd(n//2,ans+1,s)
if __name__ == '__main__':
dp=[]
for i in range(1000001):
dp.append(0)
for i in range(len(dp)):
if(i<10):
dp[i]=1
else:
val=i
count=0
while(True):
maxa=0
s=str(val)
for j in range(len(s)):
if(int(s[j:j+1])>maxa):
maxa=int(s[j:j+1])
val-=maxa
count+=1
if(val<=len(dp)):
dp[i]=count+dp[val]
break
else:
continue
# print(len(dp))
n=int(input())
if(n<=len(dp)):
print(dp[n])
else:
val=n
count=0
while(True):
maxa=0
s=str(val)
for j in range(len(s)):
if(int(s[j:j+1])>maxa):
maxa=int(s[j:j+1])
val-=maxa
count+=1
if(val<=len(dp)):
count=count+dp[val]
break
else:
continue
print(count)
```
No
| 1,934 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Submitted Solution:
```
n=int(input())
lis=list(str(n))
sizz= len(lis)
count=0
while(len(lis)!=1):
m=0
for i in lis:
m=max(m,int(i))
temp=int(''.join(lis))
temp-=m
lis=list(str(temp))
count+=1
print(count+1)
```
No
| 1,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Submitted Solution:
```
n = int(input())
d = {1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:1}
for i in range(10,1001):
p = str(i).find("9")
if p==-1:
m = max([int(k) for k in str(i)])
d[i] = 1 + d[i - m]
else:
q = 1+int(int("0"+str(i)[(p+1):])/9)
d[i] = q+d[i-9*q]
c=0
while n!=0:
if n <= 1000:
c+=d[n]
n=0
else:
c+=153
n-=1000
print(c)
```
No
| 1,936 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.
The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:
"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"
Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.
Input
The single line contains the magic integer n, 0 β€ n.
* to get 20 points, you need to solve the problem with constraints: n β€ 106 (subproblem C1);
* to get 40 points, you need to solve the problem with constraints: n β€ 1012 (subproblems C1+C2);
* to get 100 points, you need to solve the problem with constraints: n β€ 1018 (subproblems C1+C2+C3).
Output
Print a single integer β the minimum number of subtractions that turns the magic number to a zero.
Examples
Input
24
Output
5
Note
In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:
24 β 20 β 18 β 10 β 9 β 0
Submitted Solution:
```
def main():
n = int(input())
res = 20 * (n // 100)
i = n % 100
dec = False
while i % 10 != 0 and i % 9 != 0:
i -= 1
dec = True
if dec:
res += 1
if i % 10 == 0:
m = i // 10
res += 2 * m
elif i % 9 == 0:
m = i // 9
res += 2 * m - 1
print(res)
if __name__ == '__main__':
main()
```
No
| 1,937 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Tags: implementation, math, number theory
Correct Solution:
```
n = int(input())
nums = list(map(int, input().split()))
s = input()
ans = 0
for i in range(n):
if s[i] == '1':
ans += nums[i]
cur = 0
pa = ans
for i in range(n):
if s[i] == '1':
ans = max(ans, pa+cur-nums[i])
else:
cur += nums[i]
print(ans)
```
| 1,938 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Tags: implementation, math, number theory
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
k = input()
pref = [a[0]]
for i in range(1, n):
pref.append(pref[-1] + a[i])
cur = 0
ans = 0
for i in range(n - 1, -1, -1):
if k[i] == '0':
continue
if cur + (pref[i - 1] if i > 0 else 0) > ans:
ans = cur + (pref[i - 1] if i > 0 else 0)
cur += a[i]
cur = 0
for i in range(n):
if k[i] == '1':
cur += a[i]
ans = max(ans, cur)
print(ans)
```
| 1,939 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Tags: implementation, math, number theory
Correct Solution:
```
from sys import stdin
from itertools import accumulate
def arr_enu():
return [[i, int(x)] for i, x in enumerate(stdin.readline().split())]
def get_col(arr, i):
return [row[i] for row in arr]
def arr_sum(arr):
arr.insert(0, 0)
return list(accumulate(arr, lambda x, y: x + y))
def fun(x, y):
return int(x) * y[1]
n, a, s = int(stdin.readline()), arr_enu(), stdin.readline()
cum, cum2 = arr_sum(get_col(a, 1)), arr_sum(list(map(fun, s, a)))
ans = cum2[-1]
for i in range(n - 1, -1, -1):
if s[i] == '1':
ans = max(ans, cum[i] + (cum2[-1] - cum2[i + 1]))
print(ans)
```
| 1,940 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Tags: implementation, math, number theory
Correct Solution:
```
import sys
from math import gcd,sqrt,ceil,log2
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
import math
import heapq
from itertools import permutations
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# import sys
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def get_sum(bit,i):
s = 0
i+=1
while i>0:
s+=bit[i]
i-=i&(-i)
return s
def update(bit,n,i,v):
i+=1
while i<=n:
bit[i]+=v
i+=i&(-i)
def modInverse(b,m):
g = math.gcd(b, m)
if (g != 1):
return -1
else:
return pow(b, m - 2, m)
def primeFactors(n):
sa = set()
sa.add(n)
while n % 2 == 0:
sa.add(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
sa.add(i)
n = n // i
# sa.add(n)
return sa
def seive(n):
pri = [True]*(n+1)
p = 2
while p*p<=n:
if pri[p] == True:
for i in range(p*p,n+1,p):
pri[i] = False
p+=1
return pri
def check_prim(n):
if n<0:
return False
for i in range(2,int(sqrt(n))+1):
if n%i == 0:
return False
return True
def getZarr(string, z):
n = len(string)
# [L,R] make a window which matches
# with prefix of s
l, r, k = 0, 0, 0
for i in range(1, n):
# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i
# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
else:
# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l
# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]
# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:
# else start from R and check manually
l = i
while r < n and string[r - l] == string[r]:
r += 1
z[i] = r - l
r -= 1
def search(text, pattern):
# Create concatenated string "P$T"
concat = pattern + "$" + text
l = len(concat)
z = [0] * l
getZarr(concat, z)
ha = []
for i in range(l):
if z[i] == len(pattern):
ha.append(i - len(pattern) - 1)
return ha
# n,k = map(int,input().split())
# l = list(map(int,input().split()))
#
# n = int(input())
# l = list(map(int,input().split()))
#
# hash = defaultdict(list)
# la = []
#
# for i in range(n):
# la.append([l[i],i+1])
#
# la.sort(key = lambda x: (x[0],-x[1]))
# ans = []
# r = n
# flag = 0
# lo = []
# ha = [i for i in range(n,0,-1)]
# yo = []
# for a,b in la:
#
# if a == 1:
# ans.append([r,b])
# # hash[(1,1)].append([b,r])
# lo.append((r,b))
# ha.pop(0)
# yo.append([r,b])
# r-=1
#
# elif a == 2:
# # print(yo,lo)
# # print(hash[1,1])
# if lo == []:
# flag = 1
# break
# c,d = lo.pop(0)
# yo.pop(0)
# if b>=d:
# flag = 1
# break
# ans.append([c,b])
# yo.append([c,b])
#
#
#
# elif a == 3:
#
# if yo == []:
# flag = 1
# break
# c,d = yo.pop(0)
# if b>=d:
# flag = 1
# break
# if ha == []:
# flag = 1
# break
#
# ka = ha.pop(0)
#
# ans.append([ka,b])
# ans.append([ka,d])
# yo.append([ka,b])
#
# if flag:
# print(-1)
# else:
# print(len(ans))
# for a,b in ans:
# print(a,b)
def mergeIntervals(arr):
# Sorting based on the increasing order
# of the start intervals
arr.sort(key = lambda x: x[0])
# array to hold the merged intervals
m = []
s = -10000
max = -100000
for i in range(len(arr)):
a = arr[i]
if a[0] > max:
if i != 0:
m.append([s,max])
max = a[1]
s = a[0]
else:
if a[1] >= max:
max = a[1]
#'max' value gives the last point of
# that particular interval
# 's' gives the starting point of that interval
# 'm' array contains the list of all merged intervals
if max != -100000 and [s, max] not in m:
m.append([s, max])
return m
# n = int(input())
# dp = defaultdict(bool)
# n,m,k = map(int,input().split())
# l = []
#
# for i in range(n):
# la = list(map(int,input().split()))
# l.append(la)
# dp = defaultdict(int)
#
# for i in range(n):
# for j in range(m):
# for cnt in range(m//2-1,-1,-1):
# for rem in range(k):
# dp[(i,cnt+1,rem)] = max(dp[(i,cnt+1,rem)],dp[(i,cnt,rem)])
# dp[(i,cnt+1,(rem+l[i][j])%k)] = max(dp[(i,cnt+1,(rem+l[i][j])%k)],dp[(i,cnt,rem)]+l[i][j])
#
#
# print(dp[(n-1,m//2,0)])
#
#
# n,m = map(int,input().split())
#
# l = []
# for i in range(n):
# la = list(input())
# l.append(la)
# q = int(input())
# qu = []
# for i in range(q):
# a,b = map(str,input().split())
# qu.append([a,int(b)])
# ans = []
# row = [[] for i in range(n)]
# col = [[] for i in range(m)]
# # print(log2(26*10**5))
# for i in range(n):
# for j in range(m):
# if l[i][j] == '#':
#
#
# row[i].append(j)
# col[j].append(i)
#
#
#
# for i in range(n):
# for j in range(m):
#
# if l[i][j] != '.' and l[i][j]!='#':
# x,y = i,j
# flag = 0
#
#
# for a,b in qu:
#
# # z1 = bisect_right(row[x],y)
# # z2 = bisect_right(col[y],x)
#
# if a == 'N':
# z2 = bisect_right(col[y],x)
# x-=b
# if x>=n or y>=m or x<0 or y<0:
# flag = 1
#
# break
# if l[x][y] == '#':
# flag = 1
# break
# if col[y] == []:
# continue
# if z2 == len(col[y]):
#
# if x<=col[y][z2-1]:
# flag = 1
#
# break
#
# elif col[y][z2-1]<x<col[y][z2]:
#
# continue
# else:
# flag = 1
# break
#
#
# if a == 'S':
# z2 = bisect_right(col[y],x)
# x+=b
#
# if x>=n or y>=m or x<0 or y<0:
# flag = 1
#
# break
# if l[x][y] == '#':
# flag = 1
# break
# if col[y] == []:
# continue
# if z2 == len(col[y]):
# if x<=col[y][z2-1]:
# flag = 1
#
# break
#
# elif col[y][z2-1]<x<col[y][z2]:
# continue
# else:
# flag = 1
# break
#
# if a == 'E':
# z1 = bisect_right(row[x],y)
# y+=b
# # print(z1,y,row[x])
# if x>=n or y>=m or x<0 or y<0:
# flag = 1
# break
# if l[x][y] == '#':
# flag = 1
# if row[x] == []:
# continue
#
# if z1 == len(row[x]):
# if y<=row[x][z1-1]:
# flag = 1
#
# break
# elif row[x][z1-1]<y<row[x][z1]:
# continue
# else:
# flag = 1
# break
# if a == 'W':
# z1 = bisect_right(row[x],y)
# y-=b
#
# if x>=n or y>=m or x<0 or y<0:
# flag = 1
# break
# if l[x][y] == '#':
# flag = 1
# if row[x] == []:
# continue
# if z1 == len(row[x]):
# if y<=row[x][z1-1]:
# flag = 1
#
# break
# elif row[x][z1-1]<y<row[x][z1]:
# continue
# else:
# flag = 1
# break
#
#
#
#
#
# if flag == 0:
# ans.append(l[i][j])
# if ans!=[]:
# ans.sort()
# print(''.join(ans))
#
# else:
# print('no solution')
#
#
n = int(input())
l = list(map(int,input().split()))
l.reverse()
# print(l)
m = input()[::-1]
# print(m)
ans = 0
z = sum(l)
yo = 0
# print(m,l)
flag = 0
for i in range(n):
z-=l[i]
if m[i] == '1' :
ans = max(z+yo,ans)
yo+=l[i]
ans = max(z+yo,ans)
print(ans)
```
| 1,941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Tags: implementation, math, number theory
Correct Solution:
```
#!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, = readln()
a = readln()
s = [0] * (n + 1)
sm = [0] * (n + 1)
m = list(input())
for i in range(n):
s[i + 1] = s[i] + a[i]
sm[i + 1] = sm[i] + (a[i] if m[i] == '1' else 0)
ans = sm[n]
for i in range(n - 1, -1, -1):
if m[i] == '1':
ans = max(ans, s[i] + sm[n] - sm[i + 1])
print(ans)
```
| 1,942 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Tags: implementation, math, number theory
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
s = input()
ans = 0
sm = 0
for i in range(n):
if s[i] == '1':
ans = max(ans + a[i], sm)
sm += a[i]
print(ans)
```
| 1,943 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Tags: implementation, math, number theory
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
s = input()
m = len(s)
prevSum = [0]*n
prevSum[0] = a[0]
for i in range(1,n):
prevSum[i] = prevSum[i-1]+a[i]
dp = [0]*m
lastOne = -1
if (s[0]!="0"):
lastOne = 0
dp[0] = a[0]
for i in range(1,m):
if (s[i]=="0"):
dp[i] = dp[i-1]
else:
y = 0
if (lastOne!=-1):
y = dp[lastOne]
dp[i] = max(prevSum[i-1],y+a[i])
lastOne = i
print(dp[m-1])
```
| 1,944 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Tags: implementation, math, number theory
Correct Solution:
```
import sys
class DFSHelper:
mxNum = 0
d = DFSHelper()
def backTrack(maxval, curval, binPos, maxBinPos, arr, total):
if binPos > maxBinPos:
if maxval >= curval:
d.mxNum = max(d.mxNum, total)
return
# Try 1
nxtVal = (1 << binPos) + curval
backTrack(maxval, nxtVal, binPos + 1, maxBinPos, arr, total + arr[binPos])
# Try 0
nxtVal = curval
backTrack(maxval, nxtVal, binPos + 1, maxBinPos, arr, total)
def constructM(m):
mult = 0
total = 0
for char in m:
if char == "1":
total += 2 ** mult
mult += 1
return total
def solve(arr, m):
maxval = constructM(m)
curval = 0
binPos = 0
maxBinPos = len(m) - 1
backTrack(maxval, curval, binPos, maxBinPos, arr, 0)
return d.mxNum
def solve2(arr, m):
DPTable = [[0 for _ in range(3)] for _ in range(len(arr) + 1)]
for i in range(len(arr)):
if m[i] == "0":
DPTable[i + 1][2] = DPTable[i][2] # max between ones and zeroes
DPTable[i + 1][1] = max(
DPTable[i][1], DPTable[i][1] + arr[i]
) # max of both ones and zeroes
if m[i] == "1":
DPTable[i + 1][2] = max(
DPTable[i][2] + arr[i], DPTable[i][1]
) # best of '01' chains leading up to here and either the 1 or max of 0000 for this chain
DPTable[i + 1][1] = max(
DPTable[i][1], DPTable[i][1] + arr[i]
) # max of both ones and zeroes
return DPTable[-1][2]
def readinput():
n = int(sys.stdin.readline().rstrip())
arr = list(map(int, (sys.stdin.readline().rstrip().split(" "))))
m = str(sys.stdin.readline().rstrip())
print(solve2(arr, m))
readinput()
```
| 1,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
b = [0] + a
for i in range(1, n + 1):
b[i] += b[i - 1]
t = input()
s, m, i = 0, 0, t.rfind('1')
while i >= 0:
d = b[i] + s
if d > m: m = d
if d + a[i] < m: break
s += a[i]
i = t[: i].rfind('1')
print(max(m, s))
```
Yes
| 1,946 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Submitted Solution:
```
import sys
N=int(sys.stdin.readline())
A=list(map(int,sys.stdin.readline().split()))
Sums=[0]*(N)
m=sys.stdin.readline()
maxx=0
s=0
for i in range(N):
s+=A[i]
Sums[i]=s
if(m[i]=="1"):
maxx+=A[i]
ind=N-1
for i in range(N):
if(m[i]!="1"):
ind=i
break
temp_ans=0
conf=""
for i in range(N-1,0,-1):
if(i==ind):
break
if(m[i]=="1"):
temp_ans+=A[i]
if(A[i]<Sums[i-1]):
ans=temp_ans-A[i]+Sums[i-1]
if(ans>maxx):
maxx=ans
print(maxx)
```
Yes
| 1,947 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Submitted Solution:
```
def makePref(a):
pref = a[:]
for i in range(1,len(pref)):
pref[i] += pref[i-1]
return pref
def makeSuff(a, m):
suff = a[:]
for i in range(len(suff)):
suff[i] *= m[i]
for i in range(len(suff)-2, -1, -1):
suff[i] += suff[i+1]
return suff
def solve(pref, suff, m):
ans = suff[0]
for i in range(1,len(m)):
if m[i] == 1:
if i == len(m)-1:
ans = max(ans, pref[i-1])
else:
ans = max(ans, pref[i-1] + suff[i+1])
return ans
n = int(input())
a = [int(x) for x in input().split()]
m = [int(x) for x in input()]
pref = makePref(a)
suff = makeSuff(a, m)
print(solve(pref, suff, m))
```
Yes
| 1,948 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Submitted Solution:
```
import sys
input=sys.stdin.readline
n=int(input())
a=list(map(int,input().split()))
s=list(input().rstrip())
for i in range(len(s)):
s[i]=int(s[i])
ans,x=0,0
for i in range(n):
if s[i]==1:
ans=max(ans+a[i],x)
x+=a[i]
print(ans)
```
Yes
| 1,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Submitted Solution:
```
n = int(input())
a = [int(i) for i in input().split()]
m = input()
target = 0
k = 0
for i in range(len(m)):
target += (2**i)*int(m[i])
if m[i] == '1':
k = i
total = sum(a[0:k+1])
ele = []
for i in range(k+1):
ele.append([a[i], i])
ele.sort()
num = 2**(k+1) - 1
for i in range(n):
if num > target:
num -= 2**ele[i][1]
total -= ele[i][0]
else:
break
print(total)
```
No
| 1,950 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Submitted Solution:
```
m = int(input())
listValue = input().split()
x = input().rstrip('\n')
reverse_x = list(x)
reverse_int = [int(s) for s in reverse_x]
while reverse_int[-1] == 0 and len(reverse_int) > 1:
reverse_int.pop(-1)
reverse_len = len(reverse_int)
values = [int(ele) for ele in listValue]
sum_primary = 0
sum_total = 0
for i in range(reverse_len):
sum_total += values[i]
if reverse_int[i] == 1:
sum_primary += values[i]
index = reverse_len - 1
mini = values[index]
while reverse_int[index] == 1 and index >= 1:
mini = min(mini, values[index])
index -= 1
sum_total -= mini
print(max(sum_primary, sum_total))
```
No
| 1,951 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Submitted Solution:
```
n = int(input())
a = [int(i) for i in input().split()]
m = input()
i = n-1
while i >= 0:
if m[i] == '1':
break
else:
i -= 1
total_1 = 0
for j in range(i):
total_1 += a[j]
total_2 = 0
for j in range(n):
if m[j] == '1':
total_2 += a[j]
print(max(total_1, total_2))
```
No
| 1,952 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula <image>, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 β€ x β€ m.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 β€ ai β€ 104) β elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β the binary representation of number m. Number m equals <image>.
Output
Print a single integer β the maximum value of function f(x) for all <image>.
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
s = input()
ans = 0
sm = 0
for i in range(n):
if s[i] == '1':
ans = max(ans + a[i], sm)
sm += i
print(ans)
```
No
| 1,953 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired n workers of staff. Now he wants to pick n workers from the staff who will be directly responsible for developing a game.
Each worker has a certain skill level vi. Besides, each worker doesn't want to work with the one whose skill is very different. In other words, the i-th worker won't work with those whose skill is less than li, and with those whose skill is more than ri.
Pavel understands that the game of his dream isn't too hard to develop, so the worker with any skill will be equally useful. That's why he wants to pick a team of the maximum possible size. Help him pick such team.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of workers Pavel hired.
Each of the following n lines contains three space-separated integers li, vi, ri (1 β€ li β€ vi β€ ri β€ 3Β·105) β the minimum skill value of the workers that the i-th worker can work with, the i-th worker's skill and the maximum skill value of the workers that the i-th worker can work with.
Output
In the first line print a single integer m β the number of workers Pavel must pick for developing the game.
In the next line print m space-separated integers β the numbers of the workers in any order.
If there are multiple optimal solutions, print any of them.
Examples
Input
4
2 8 9
1 4 7
3 6 8
5 8 10
Output
3
1 3 4
Input
6
3 5 16
1 6 11
4 8 12
7 9 16
2 10 14
8 13 15
Output
4
1 2 3 5
Tags: data structures
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
def inp():
return sys.stdin.readline().rstrip()
def mpint():
return map(int, inp().split(' '))
def itg():
return int(inp())
# ############################## import
# 2020/12/17
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the lazy segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
"""push query on idx to its children"""
# Let the children know of the queries
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
"""updates the node idx to know of all queries applied to it via its ancestors"""
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
"""make the changes to idx be known to its ancestors"""
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
idx >>= 1
def add(self, start, stop, value):
"""lazily add value to [start, stop)"""
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
# Tell all nodes above of the updated area of the updates
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=None):
"""func of data[start, stop)"""
start += self._size
stop += self._size
# Apply all the lazily stored queries
self._update(start)
self._update(stop - 1)
res = self._default if default is None else default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({})".format(list(map(lambda i: self.query(i, i + 1), range(self._len))))
class SweepLine:
def __init__(self, data=None, inclusive=True):
"""
:param data: [((1, 2), (3, 4)), (left_bottom, right_top), ...]
:param inclusive: include the right bound
"""
if data:
# [((1, 2), (3, 4), 0), ...]
self.data = [(*pair, i) for i, pair in enumerate(data)]
else:
self.data = []
self.discrete_dict = self.restore = None
self.INCLUSIVE = inclusive
def add_rectangle(self, rectangle):
self.data.append((*rectangle, len(self.data)))
def _discrete(self):
st = set()
operations = []
for p1, p2, i in self.data:
st |= {*p1, *p2}
# we want add operation go first, so *= -1
# we calculate the line intersect
operations.append((p1[1], -1, p1[0], p2[0], i)) # add
operations.append((p2[1], 1, p1[0], p2[0], i)) # subtract
self.restore = sorted(st)
self.discrete_dict = dict(zip(self.restore, range(len(st))))
self.operations = sorted(operations)
# print(*self.operations, sep='\n')
def max_intersect(self, get_points=False):
"""
:return intersect, i (ith rectangle)
:return intersect, i, x
"""
if not self.restore:
self._discrete()
d = self.discrete_dict
tree = LazySegmentTree([0] * len(self.restore))
result = 0, None
for y, v, left, right, i in self.operations:
# print(f"left={left}, right={right}")
left, right, v = d[left], d[right], -v
# print(f"dis -> left={left}, right={right}")
tree.add(left, right + self.INCLUSIVE, v)
if v == 1:
intersect = tree.query(left, right + self.INCLUSIVE)
if intersect > result[0]:
result = intersect, i
tree = LazySegmentTree([0] * len(self.restore))
if get_points:
for y, v, left, right, i in self.operations:
left, right, v = d[left], d[right], -v
tree.add(left, right + self.INCLUSIVE, v)
if i == result[1]:
for lf in range(left, right + self.INCLUSIVE):
if tree.query(lf, lf + 1) == result[0]:
return result[0], i, self.restore[lf]
return result
# ############################## main
def main():
n = itg()
data = []
for _ in range(n):
lf, md, rg = mpint()
data.append(((lf, md), (md, rg)))
sweep = SweepLine(data)
ans1, idx, left = sweep.max_intersect(True)
right = data[idx][0][1]
print(ans1)
# print(idx)
# print(f"intersect = {ans1}")
# print(f"left = {left}, right = {right}")
ans2 = []
for i, pair in enumerate(data):
lf, md, rg = pair[0][0], pair[0][1], pair[1][1]
if lf <= left <= md <= right <= rg:
ans2.append(i + 1)
if len(ans2) != ans1:
print(AssertionError, len(ans2))
else:
print(*ans2)
DEBUG = 0
URL = 'https://codeforces.com/contest/377/problem/D'
if __name__ == '__main__':
# 0: normal, 1: runner, 2: interactive, 3: debug
if DEBUG == 1:
import requests
from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
runner = TestCaseRunner(main, URL)
inp = runner.input_stream
print = runner.output_stream
runner.checking()
else:
if DEBUG != 3:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
if DEBUG:
_print = print
def print(*args, **kwargs):
_print(*args, **kwargs)
sys.stdout.flush()
main()
# Please check!
```
| 1,954 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired n workers of staff. Now he wants to pick n workers from the staff who will be directly responsible for developing a game.
Each worker has a certain skill level vi. Besides, each worker doesn't want to work with the one whose skill is very different. In other words, the i-th worker won't work with those whose skill is less than li, and with those whose skill is more than ri.
Pavel understands that the game of his dream isn't too hard to develop, so the worker with any skill will be equally useful. That's why he wants to pick a team of the maximum possible size. Help him pick such team.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of workers Pavel hired.
Each of the following n lines contains three space-separated integers li, vi, ri (1 β€ li β€ vi β€ ri β€ 3Β·105) β the minimum skill value of the workers that the i-th worker can work with, the i-th worker's skill and the maximum skill value of the workers that the i-th worker can work with.
Output
In the first line print a single integer m β the number of workers Pavel must pick for developing the game.
In the next line print m space-separated integers β the numbers of the workers in any order.
If there are multiple optimal solutions, print any of them.
Examples
Input
4
2 8 9
1 4 7
3 6 8
5 8 10
Output
3
1 3 4
Input
6
3 5 16
1 6 11
4 8 12
7 9 16
2 10 14
8 13 15
Output
4
1 2 3 5
Tags: data structures
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
def inp():
return sys.stdin.readline().rstrip()
def mpint():
return map(int, inp().split(' '))
def itg():
return int(inp())
# ############################## import
# 2020/11/17
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the lazy segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
"""push query on idx to its children"""
# Let the children know of the queries
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
"""updates the node idx to know of all queries applied to it via its ancestors"""
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
"""make the changes to idx be known to its ancestors"""
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
idx >>= 1
def add(self, start, stop, value):
"""lazily add value to [start, stop)"""
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
# Tell all nodes above of the updated area of the updates
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=None):
"""func of data[start, stop)"""
start += self._size
stop += self._size
# Apply all the lazily stored queries
self._update(start)
self._update(stop - 1)
res = self._default if default is None else default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({})".format(list(map(lambda i: self.query(i, i + 1), range(self._len))))
class SweepLine:
def __init__(self, data=None, inclusive=True):
"""
:param data: [((1, 2), (3, 4)), (left_bottom, right_top), ...]
:param inclusive: include the right bound
"""
if data:
# [((1, 2), (3, 4), 0), ...]
self.data = [(pair[0], pair[1], i) for i, pair in enumerate(data)]
else:
self.data = []
self.discrete_dict = self.restore = None
self.INCLUSIVE = inclusive
def add_rectangle(self, rectangle):
self.data.append((rectangle[0], rectangle[1], len(self.data)))
def _discrete(self):
st = set()
operations = []
for p1, p2, i in self.data:
st |= {p1[0], p1[1], p2[0], p2[1]}
# we want add operation go first, so *= -1
# we calculate the line intersect
operations.append((p1[1], -1, p1[0], p2[0], i)) # add
operations.append((p2[1], 1, p1[0], p2[0], i)) # subtract
self.restore = sorted(st)
self.discrete_dict = dict(zip(self.restore, range(len(st))))
self.operations = sorted(operations)
# print(*self.operations, sep='\n')
def max_intersect(self, get_points=False):
"""
:return intersect, i (ith rectangle)
:return intersect, i, x
"""
if not self.restore:
self._discrete()
d = self.discrete_dict
tree = LazySegmentTree([0] * len(self.restore))
result = 0, None
for y, v, left, right, i in self.operations:
# print(f"left={left}, right={right}")
left, right, v = d[left], d[right], -v
# print(f"dis -> left={left}, right={right}")
tree.add(left, right + self.INCLUSIVE, v)
if v == 1:
intersect = tree.query(left, right + self.INCLUSIVE)
if intersect > result[0]:
result = intersect, i
tree = LazySegmentTree([0] * len(self.restore))
if get_points:
for y, v, left, right, i in self.operations:
left, right, v = d[left], d[right], -v
tree.add(left, right + self.INCLUSIVE, v)
if i == result[1]:
for lf in range(left, right + self.INCLUSIVE):
if tree.query(lf, lf + 1) == result[0]:
return result[0], i, self.restore[lf]
return result
# ############################## main
def main():
n = itg()
data = []
for _ in range(n):
lf, md, rg = mpint()
data.append(((lf, md), (md, rg)))
sweep = SweepLine(data)
ans1, idx, left = sweep.max_intersect(True)
right = data[idx][0][1]
print(ans1)
# print(idx)
# print(f"intersect = {ans1}")
# print(f"left = {left}, right = {right}")
ans2 = []
for i, pair in enumerate(data):
lf, md, rg = pair[0][0], pair[0][1], pair[1][1]
if lf <= left <= md <= right <= rg:
ans2.append(i + 1)
if len(ans2) != ans1:
print(AssertionError, len(ans2))
else:
print(*ans2)
DEBUG = 0
URL = 'https://codeforces.com/contest/377/problem/D'
if __name__ == '__main__':
# 0: normal, 1: runner, 2: interactive, 3: debug
if DEBUG == 1:
import requests
from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
runner = TestCaseRunner(main, URL)
inp = runner.input_stream
print = runner.output_stream
runner.checking()
else:
if DEBUG != 3:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
if DEBUG:
_print = print
def print(*args, **kwargs):
_print(*args, **kwargs)
sys.stdout.flush()
main()
# Please check!
```
| 1,955 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired n workers of staff. Now he wants to pick n workers from the staff who will be directly responsible for developing a game.
Each worker has a certain skill level vi. Besides, each worker doesn't want to work with the one whose skill is very different. In other words, the i-th worker won't work with those whose skill is less than li, and with those whose skill is more than ri.
Pavel understands that the game of his dream isn't too hard to develop, so the worker with any skill will be equally useful. That's why he wants to pick a team of the maximum possible size. Help him pick such team.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of workers Pavel hired.
Each of the following n lines contains three space-separated integers li, vi, ri (1 β€ li β€ vi β€ ri β€ 3Β·105) β the minimum skill value of the workers that the i-th worker can work with, the i-th worker's skill and the maximum skill value of the workers that the i-th worker can work with.
Output
In the first line print a single integer m β the number of workers Pavel must pick for developing the game.
In the next line print m space-separated integers β the numbers of the workers in any order.
If there are multiple optimal solutions, print any of them.
Examples
Input
4
2 8 9
1 4 7
3 6 8
5 8 10
Output
3
1 3 4
Input
6
3 5 16
1 6 11
4 8 12
7 9 16
2 10 14
8 13 15
Output
4
1 2 3 5
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
def inp():
return sys.stdin.readline().rstrip()
def mpint():
return map(int, inp().split(' '))
def itg():
return int(inp())
# ############################## import
# 2020/11/17
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the lazy segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
"""push query on idx to its children"""
# Let the children know of the queries
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
"""updates the node idx to know of all queries applied to it via its ancestors"""
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
"""make the changes to idx be known to its ancestors"""
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
idx >>= 1
def add(self, start, stop, value):
"""lazily add value to [start, stop)"""
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
# Tell all nodes above of the updated area of the updates
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=None):
"""func of data[start, stop)"""
start += self._size
stop += self._size
# Apply all the lazily stored queries
self._update(start)
self._update(stop - 1)
res = self._default if default is None else default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({})".format(list(map(lambda i: self.query(i, i + 1), range(self._len))))
class SweepLine:
def __init__(self, data=None, inclusive=True):
"""
:param data: [((1, 2), (3, 4)), (left_bottom, right_top), ...]
:param inclusive: include the right bound
"""
if data:
# [((1, 2), (3, 4), 0), ...]
self.data = [(*pair, i) for i, pair in enumerate(data)]
else:
self.data = []
self.discrete_dict = self.restore = None
self.INCLUSIVE = inclusive
def add_rectangle(self, rectangle):
self.data.append((*rectangle, len(self.data)))
def _discrete(self):
st = set()
operations = []
for p1, p2, i in self.data:
st |= {*p1, *p2}
# we want add operation go first, so *= -1
# we calculate the line intersect
operations.append((p1[1], -1, p1[0], p2[0], i)) # add
operations.append((p2[1], 1, p1[0], p2[0], i)) # subtract
self.restore = sorted(st)
self.discrete_dict = dict(zip(st, range(len(st))))
self.operations = sorted(operations)
# print(*self.operations, sep='\n')
def max_intersect(self, get_points=False):
"""
:return intersect, i (ith rectangle)
:return intersect, i, x
"""
if not self.restore:
self._discrete()
d = self.discrete_dict
tree = LazySegmentTree([0] * len(self.restore))
result = 0, None
for y, v, left, right, i in self.operations:
# print(f"left={left}, right={right}")
left, right, v = d[left], d[right], -v
# print(f"dis -> left={left}, right={right}")
tree.add(left, right + self.INCLUSIVE, v)
if v == 1:
intersect = tree.query(left, right + self.INCLUSIVE)
if intersect > result[0]:
result = intersect, i
tree = LazySegmentTree([0] * len(self.restore))
if get_points:
for y, v, left, right, i in self.operations:
left, right, v = d[left], d[right], -v
tree.add(left, right + self.INCLUSIVE, v)
if i == result[1]:
for lf in range(left, right + self.INCLUSIVE):
if tree.query(lf, lf + 1) == result[0]:
return result[0], i, self.restore[lf]
return result
# ############################## main
def main():
n = itg()
data = []
for _ in range(n):
lf, md, rg = mpint()
data.append(((lf, md), (md, rg)))
sweep = SweepLine(data)
ans1, idx, left = sweep.max_intersect(True)
right = data[idx][0][1]
print(ans1)
# print(idx)
# print(f"intersect = {ans1}")
# print(f"left = {left}, right = {right}")
ans2 = []
for i, pair in enumerate(data):
lf, md, rg = pair[0][0], pair[0][1], pair[1][1]
if lf <= left <= md <= right <= rg:
ans2.append(i + 1)
if len(ans2) != ans1:
print(AssertionError, len(ans2))
else:
print(*ans2)
DEBUG = 0
URL = 'https://codeforces.com/contest/377/problem/D'
if __name__ == '__main__':
# 0: normal, 1: runner, 2: interactive, 3: debug
if DEBUG == 1:
import requests
from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
runner = TestCaseRunner(main, URL)
inp = runner.input_stream
print = runner.output_stream
runner.checking()
else:
if DEBUG != 3:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
if DEBUG:
_print = print
def print(*args, **kwargs):
_print(*args, **kwargs)
sys.stdout.flush()
main()
# Please check!
```
No
| 1,956 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired n workers of staff. Now he wants to pick n workers from the staff who will be directly responsible for developing a game.
Each worker has a certain skill level vi. Besides, each worker doesn't want to work with the one whose skill is very different. In other words, the i-th worker won't work with those whose skill is less than li, and with those whose skill is more than ri.
Pavel understands that the game of his dream isn't too hard to develop, so the worker with any skill will be equally useful. That's why he wants to pick a team of the maximum possible size. Help him pick such team.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of workers Pavel hired.
Each of the following n lines contains three space-separated integers li, vi, ri (1 β€ li β€ vi β€ ri β€ 3Β·105) β the minimum skill value of the workers that the i-th worker can work with, the i-th worker's skill and the maximum skill value of the workers that the i-th worker can work with.
Output
In the first line print a single integer m β the number of workers Pavel must pick for developing the game.
In the next line print m space-separated integers β the numbers of the workers in any order.
If there are multiple optimal solutions, print any of them.
Examples
Input
4
2 8 9
1 4 7
3 6 8
5 8 10
Output
3
1 3 4
Input
6
3 5 16
1 6 11
4 8 12
7 9 16
2 10 14
8 13 15
Output
4
1 2 3 5
Submitted Solution:
```
import sys
def swap(a_list, u, v):
a_list[u], a_list[v] = a_list[v], a_list[u]
def update(it, i, l, r, u, v, c):
mid = (l + r) >> 1
left_child = i << 1
right_child = left_child + 1
if l < r:
it[left_child] += t[i]
it[right_child] += t[i]
t[left_child] += t[i]
t[right_child] += t[i]
t[i] = 0
if u <= l and r <= v:
it[i] += c
t[i] += c
return
if u <= mid:
update(it, left_child, l, mid, u, v, c)
if v > mid:
update(it, right_child, mid + 1, r, u, v, c)
it[i] = max(it[left_child], it[right_child])
data_in = [int(i) for i in sys.stdin.read().split()]
n = data_in[0]
a = [[None] * 3 for i in range(n)]
b = [None] * (3 * n)
c = [None] * (3 * n)
left = 0
right = (3 * n) - 1
size = 0
maxC = 0
for i in range(n):
for j in range(3):
a[i][j] = data_in[3 * i + j + 1]
b[size] = (i, 0)
size += 1
b[size] = (i, 2)
swap(b, size, left)
b[right] = (i, 1)
size += 1
left += 1
right -= 1
maxC = max(maxC, a[i][2])
it = [0] * (5 * maxC + 1)
t = [0] * (5 * maxC + 1)
head = [0] * (maxC + 1)
for i in b:
head[a[i[0]][i[1]]] += 1
for i in range(1, maxC + 1):
head[i] += head[i - 1]
for i in b:
c[head[a[i[0]][i[1]]] - 1] = i
head[a[i[0]][i[1]]] -= 1
res = 0
res_lower = 0
for i in c:
id = i[0]
if i[1] == 0:
update(it, 1, 1, maxC, a[id][1], a[id][2], 1)
elif i[1] == 1:
update(it, 1, 1, maxC, a[id][1], a[id][2], -1)
if it[1] > res:
res = it[1]
res_lower = a[id][i[1]]
mark = [False] * n
open_num = 0
for i in c:
id = i[0]
if a[id][1] < res_lower or a[id][0] > res_lower or a[id][2] < res_lower:
continue
if i[1] == 0:
continue
if i[1] == 1:
mark[id] = True
open_num += 1
else:
mark[id] = False
open_num -= 1
if open_num == res:
break
print(res)
res_list = [0] * res
j = 0
for i in range(n):
if mark[i]:
res_list[j] = str(i + 1)
j += 1
print(" ".join(res_list))
```
No
| 1,957 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired n workers of staff. Now he wants to pick n workers from the staff who will be directly responsible for developing a game.
Each worker has a certain skill level vi. Besides, each worker doesn't want to work with the one whose skill is very different. In other words, the i-th worker won't work with those whose skill is less than li, and with those whose skill is more than ri.
Pavel understands that the game of his dream isn't too hard to develop, so the worker with any skill will be equally useful. That's why he wants to pick a team of the maximum possible size. Help him pick such team.
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of workers Pavel hired.
Each of the following n lines contains three space-separated integers li, vi, ri (1 β€ li β€ vi β€ ri β€ 3Β·105) β the minimum skill value of the workers that the i-th worker can work with, the i-th worker's skill and the maximum skill value of the workers that the i-th worker can work with.
Output
In the first line print a single integer m β the number of workers Pavel must pick for developing the game.
In the next line print m space-separated integers β the numbers of the workers in any order.
If there are multiple optimal solutions, print any of them.
Examples
Input
4
2 8 9
1 4 7
3 6 8
5 8 10
Output
3
1 3 4
Input
6
3 5 16
1 6 11
4 8 12
7 9 16
2 10 14
8 13 15
Output
4
1 2 3 5
Submitted Solution:
```
n=int(input())
lprime, rprime=-1, -1
list1=[]
for i in range(n):
l, s, r=[int(k) for k in input().split()]
if i==0:
lprime=l
rprime=r
else:
if l>lprime: lprime=l
if r<rprime: rprime=r
if lprime<=s<=rprime:
list1.append(i+1)
print(len(list1))
for i in range(len(list1)):
print(list1[i], end=" ")
```
No
| 1,958 |
Provide tags and a correct Python 3 solution for this coding contest problem.
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 β€ a β€ 1000) β the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number β the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
Tags: expression parsing, greedy
Correct Solution:
```
import re
class Term:
def __init__(self, factor, type):
self.factor = factor
self.type = type
def __str__(self):
return '(%d * %s)' % (self.factor, self.type)
a = int(input())
s = '+' + input().strip()
terms = []
pos = 0
while pos != len(s):
sign = 1
if s[pos] == '-':
sign = -1
factor = 1
if re.match('\d', s[pos + 1]):
start = pos + 1
pos = start + 1
while s[pos] != '*':
pos += 1
factor = int(s[start:pos])
pos += 4
term_type = 'pre'
if s[pos - 3: pos] == 'a++':
term_type = 'post'
terms.append(Term(sign * factor, term_type))
terms.sort(key = lambda term: term.factor)
#print(', '.join(map(str, terms)))
result = 0
for term in terms:
if term.type == 'pre':
a += 1
result += term.factor * a
if term.type == 'post':
a += 1
print(result)
```
| 1,959 |
Provide tags and a correct Python 3 solution for this coding contest problem.
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 β€ a β€ 1000) β the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number β the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
Tags: expression parsing, greedy
Correct Solution:
```
import re
u = int
G = input
X = sorted
y = print
A = re.findall
a = u(G())
b = X([[u((i[0]or '+')+(i[1]or '1')), i[3]]
for i in A('(\+|-)?(\d{0,4})(\*)?(a\+\+|\+\+a)', G())])
z = 0
for i in b:
if i[1] == 'a++':
z += i[0]*a
else:
z += i[0]*(a+1)
a += 1
y(z)
```
| 1,960 |
Provide tags and a correct Python 3 solution for this coding contest problem.
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 β€ a β€ 1000) β the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number β the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
Tags: expression parsing, greedy
Correct Solution:
```
import re
n = int(input())
v = input()
f1, f2 = v.count('a++'), v.count('++a')
s = []
i = 0
while i < len(v) - 2:
if v[i] + v[i + 1] + v[i + 2] == '++a':
s.append('b')
i += 3
elif v[i] + v[i + 1] + v[i + 2] == 'a++':
s.append('a')
i += 3
else:
if i == len(v) - 2:
s.extend(v[i:])
i = len(v)
else:
s.append(v[i])
i += 1
a, m = [], []
z = 1
t = ''
for i in s:
if i in ['-', '+']:
if z:
a.append(t)
else:
m.append(t)
t = ''
z = 0 if i == '-' else 1
else:
t += i
if t != '':
if z:
a.append(t)
else:
m.append(t)
for i in range(len(a)):
t = a[i].split('*')
r = 1
k1 = k2 = 0
for j in t:
if not j.isalpha():
r *= int(j)
elif j == 'a':
k1 += 1
else:
k2 += 1
a[i] = (r, k1, k2)
for i in range(len(m)):
t = m[i].split('*')
r = 1
k1 = k2 = 0
for j in t:
if j.isnumeric():
r *= int(j)
elif j == 'a':
k1 += 1
else:
k2 += 1
m[i] = (r, k1, k2)
a.sort(key=lambda x: x[0])
m.sort(key=lambda x: -x[0])
ans = 0
t = n
for i in m:
if i[1] + i[2] == 0:
ans += i[0]
continue
z = i[0]
for j in range(i[1]):
z *= t
t += 1
for j in range(i[2]):
t += 1
z *= t
ans += z
res = 0
for i in a:
if i[1] + i[2] == 0:
res += i[0]
continue
z = i[0]
for j in range(i[1]):
z *= t
t += 1
for j in range(i[2]):
t += 1
z *= t
res += z
print(res - ans)
```
| 1,961 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 β€ a β€ 1000) β the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number β the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
Submitted Solution:
```
import re
n = int(input())
s = input()
f1, f2 = s.count('a++'), s.count('++a')
res = 0
if s.startswith('844*a++'):
res += 1
s = s.replace('a++', 'a')
s = s.replace('++a', 'b')
a, m = [], []
z = 1
t = ''
for i in s:
if i in ['-', '+']:
if z:
a.append(t)
else:
m.append(t)
t = ''
z = 0 if i == '-' else 1
else:
t += i
if t != '':
if z:
a.append(t)
else:
m.append(t)
for i in range(len(a)):
t = a[i].split('*')
r = 1
k1 = k2 = 0
for j in t:
if not j.isalpha():
r *= int(j)
elif j == 'a':
k1 += 1
else:
k2 += 1
a[i] = (r, k1, k2)
for i in range(len(m)):
t = m[i].split('*')
r = 1
k1 = k2 = 0
for j in t:
if j.isnumeric():
r *= int(j)
elif j == 'a':
k1 += 1
else:
k2 += 1
m[i] = (r, k1, k2)
a.sort(key=lambda x: x[0])
m.sort(key=lambda x: -x[0])
ans = 0
t = n
for i in m:
if i[1] + i[2] == 0:
ans += i[0]
continue
z = i[0]
for j in range(i[1]):
z *= t
t += 1
for j in range(i[2]):
t += 1
z *= t
ans += z
for i in a:
if i[1] + i[2] == 0:
res += i[0]
continue
z = i[0]
for j in range(i[1]):
z *= t
t += 1
for j in range(i[2]):
t += 1
z *= t
res += z
print(res - ans)
```
No
| 1,962 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 β€ a β€ 1000) β the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number β the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
Submitted Solution:
```
import re
class Term:
def __init__(self, factor, type):
self.factor = factor
self.type = type
def __str__(self):
return '(%d * %s)' % (self.factor, self.type)
a = int(input())
s = input().strip()
s = re.sub('\+\+a', 'pre', s)
s = re.sub('a\+\+', 'post', s)
parts = re.split('([+-])', s)
terms = []
for i in range(0, len(parts), 2):
part = parts[i]
sign = 1
if i != 0 and parts[i - 1] == '-':
sign = -1
if '*' not in part:
terms.append(Term(sign * 1, part))
else:
factor, type = part.split('*')
terms.append(Term(sign * int(factor), type))
terms.sort(key = lambda term: term.factor)
#print(', '.join(map(str, terms)))
result = 0
for term in terms:
if term.type == 'pre':
a += 1
result += term.factor * a
if term.type == 'post':
a += 1
print(result)
```
No
| 1,963 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 β€ a β€ 1000) β the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number β the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
Submitted Solution:
```
import re
n = int(input())
s = input()
f1, f2 = s.count('a++'), s.count('++a')
s = s.replace('a++', 'a')
s = s.replace('++a', 'b')
a, m = [], []
z = 1
t = ''
for i in s:
if i in ['-', '+']:
if z:
a.append(t)
else:
m.append(t)
t = ''
z = 0 if i == '-' else 1
else:
t += i
if t != '':
if z:
a.append(t)
else:
m.append(t)
for i in range(len(a)):
t = a[i].split('*')
r = 1
k1 = k2 = 0
for j in t:
if not j.isalpha():
r *= int(j)
elif j == 'a':
k1 += 1
else:
k2 += 1
a[i] = (r, k1, k2)
for i in range(len(m)):
t = m[i].split('*')
r = 1
k1 = k2 = 0
for j in t:
if j.isnumeric():
r *= int(j)
elif j == 'a':
k1 += 1
else:
k2 += 1
m[i] = (r, k1, k2)
a.sort(key=lambda x: x[0])
m.sort(key=lambda x: -x[0])
ans = 0
t = n
for i in m:
if i[1] + i[2] == 0:
ans += i[0]
continue
z = i[0]
for j in range(i[1]):
z *= t
t += 1
for j in range(i[2]):
t += 1
z *= t
ans += z
res = 0
for i in a:
if i[1] + i[2] == 0:
res += i[0]
continue
z = i[0]
for j in range(i[1]):
z *= t
t += 1
for j in range(i[2]):
t += 1
z *= t
res += z
print(res - ans)
```
No
| 1,964 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 β€ a β€ 1000) β the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number β the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
Submitted Solution:
```
import re
n = int(input())
s = input()
f1, f2 = s.count('a++'), s.count('++a')
s = s.replace('a++', 'a')
s = s.replace('++a', 'b')
a, m = [], []
z = 1
t = ''
for i in s:
if i in ['-', '+']:
if z:
a.append(t)
else:
m.append(t)
t = ''
z = 0 if i == '-' else 1
else:
t += i
if t != '':
if z:
a.append(t)
else:
m.append(t)
for i in range(len(a)):
t = a[i].split('*')
r = 1
k1 = k2 = 0
for j in t:
if not j.isalpha():
r *= int(j)
elif j == 'a':
k1 += 1
else:
k2 += 1
a[i] = (r, k1, k2)
for i in range(len(m)):
t = m[i].split('*')
r = 1
k1 = k2 = 0
for j in t:
if j.isnumeric():
r *= int(j)
elif j == 'a':
k1 += 1
else:
k2 += 1
m[i] = (r, k1, k2)
a.sort(key=lambda x: x[0])
m.sort(key=lambda x: -x[0])
ans = 0
t = n
for i in m:
if i[1] + i[2] == 0:
ans += i[0]
continue
for j in range(i[1]):
ans += i[0] * t
t += 1
for j in range(i[2]):
t += 1
ans += i[0] * t
res = 0
for i in a:
if i[1] + i[2] == 0:
res += i[0]
continue
for j in range(i[1]):
res += i[0] * t
t += 1
for j in range(i[2]):
t += 1
res += i[0] * t
print(res - ans)
```
No
| 1,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Tags: binary search, greedy, implementation, sortings
Correct Solution:
```
import math
n, s = [int(x) for x in input().split()]
cities = []
for i in range(n):
x, y, k = [int(x) for x in input().split()]
d2 = x ** 2 + y ** 2
cities.append((d2, k))
cities.sort(key=lambda x: x[0])
if s >= int(1E6):
print(0)
exit()
while cities:
t = cities.pop(0)
s += t[1]
if s >= int(1E6):
print(math.sqrt(t[0]))
exit()
print(-1)
```
| 1,966 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Tags: binary search, greedy, implementation, sortings
Correct Solution:
```
from math import sqrt
MEGA_POPULATION = int(1e6)
class Location:
def __init__(self, x, y, population):
self.x = x
self.y = y
self.population = population
self.dist = sqrt(x ** 2 + y ** 2)
n, population = map(int, input().split())
locations = []
for _ in range(n):
x, y, k = map(int, input().split())
locations.append(Location(x, y, k))
locations.sort(key=lambda l: l.dist)
radius = -1
for location in locations:
x, y, k, r = location.x, location.y, location.population, location.dist
if population + k >= MEGA_POPULATION:
radius = r
break
else:
population += k
print('{:.7f}'.format(radius))
```
| 1,967 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Tags: binary search, greedy, implementation, sortings
Correct Solution:
```
# maa chudaaye duniya
n, s = map(int,input().split())
arr = []
for _ in range(n):
a, b, c = map(int, input().split())
arr.append([(a, b), c])
arr.sort(key=lambda x : x[0][0]**2 + x[0][1]**2)
# print(*arr)
pt = [-1, -1]
for i in range(n):
if s + arr[i][1] >= 10**6:
pt = arr[i][0]
break
s += arr[i][1]
if pt == [-1, -1]:
print(-1)
else:
print(pow(pt[0]**2 + pt[1]**2, 0.5))
```
| 1,968 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Tags: binary search, greedy, implementation, sortings
Correct Solution:
```
import sys
import math
import bisect
def query_value(m, dist, population, r):
n = len(dist)
ans = m
for i in range(n):
if r >= dist[i] - 10 ** -8:
ans += population[i]
#print('m: %d, dist: %s, population: %s, r; %f, ans: %d' % (m, str(dist), str(population), r, ans))
return ans
def solve(m, dist, population):
n = len(dist)
left = 0
right = 10 ** 18
if query_value(m, dist, population, right) < 10 ** 6:
return -1
cnt = 128
while cnt:
cnt -= 1
mid = (left + right) / 2
if query_value(m, dist, population, mid) >= 10 ** 6:
right = mid
else:
left = mid
return right
def main():
n, m = map(int, input().split())
dist = []
population = []
for i in range(n):
x, y, a = map(int, input().split())
dist.append(math.sqrt(x ** 2 + y ** 2))
population.append(a)
print(solve(m, dist, population))
if __name__ == "__main__":
main()
```
| 1,969 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Tags: binary search, greedy, implementation, sortings
Correct Solution:
```
from math import sqrt
def sort_fun(el):
return sqrt(el[0] ** 2 + el[1] ** 2)
def main():
cities, population = [int(x) for x in input().split(" ")]
data = []
for _ in range(cities):
data.append([int(x) for x in input().split(" ")])
data.sort(key=sort_fun)
for x, y, inc_pop in data:
population += inc_pop
if population >= 1000000:
print(sqrt(x ** 2 + y ** 2))
return
print(-1)
main()
```
| 1,970 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Tags: binary search, greedy, implementation, sortings
Correct Solution:
```
from math import *
R = lambda:map(int, input().split())
n, s = R()
x = sorted((hypot(x, y), k) for x, y, k in (R() for i in range(n)))
for t in x:
s += t[1]
if s >= 1000000:
print(t[0])
exit()
print(-1)
```
| 1,971 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Tags: binary search, greedy, implementation, sortings
Correct Solution:
```
n,pop = list(map(int,input().split()))
arr = []
d = {}
cnt = 0
for i in range(n):
x,y,p = list(map(int,input().split()))
x,y = abs(x),abs(y)
cnt+=p
r = (x**2 + y**2)**(0.5)
arr.append([r,x,y,p])
arr.sort()
if pop+cnt<1000000:
print(-1)
else:
cnt = 0
for i in arr:
r,x,y,p = i[0],i[1],i[2],i[3]
cnt+=p
if cnt+pop>=10**6:
u,v = x,y
break
r = (u**2 + v**2)**(0.5)
print(r)
```
| 1,972 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Tags: binary search, greedy, implementation, sortings
Correct Solution:
```
from math import *
a,b=map(int,input().split())
s=sorted([hypot(i,j),k] for (i,j,k) in (map(int,input().split()) for _ in " "*a))
for i in range(1,a):
s[i][1]+=s[i-1][1]
lo=0;hi=a-1;ans=-1
while lo<=hi:
mid=(lo+hi)//2
if ((b+s[mid][1])>=10**6):ans=mid;hi=mid-1
else:lo=mid+1
if (ans!=-1) :print(s[ans][0])
else:print(-1)
```
| 1,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Submitted Solution:
```
from math import sqrt
import sys
n, m = map(int, input().split())
d = dict()
for _ in range(n):
x,y,z = map(int, input().split())
r = round(sqrt(x*x + y*y),7)
if r in d:
d[r] = z + d[r]
else:
d[r] = z
d = sorted(d.items(), key=lambda x: x[0])
N = len(d)
dt = 0
for key in d:
m += key[1]
if m >= 10**6:
print(key[0])
sys.exit()
print(-1)
## Complexity O(Nlog(N))
```
Yes
| 1,974 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Submitted Solution:
```
n, s = map(int, input().split())
vals = [tuple(map(int, input().split())) for i in range(n)]
vals.sort(key = lambda e: e[0]*e[0] + e[1]*e[1])
b = True
for v in vals:
s += v[2]
if s >= 1000000:
print((v[0]*v[0] + v[1]*v[1])**0.5)
b = False
break
if b:
print(-1)
```
Yes
| 1,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Submitted Solution:
```
def distanciaAlCero(x, y):
return (x**2 + y**2)**0.5
POBLACION_MINIMA = 1_000_000
# Lista de tuplas
# Tupla: (distancia, k)
ubicaciones = []
# Asumiendo que todos los inputs son correctos
n, s = map(int, input().split())
for i in range(n):
x, y, k = map(int, input().split())
ubicaciones.append((distanciaAlCero(x, y), k))
ubicaciones.sort()
for distancia, k in ubicaciones:
s += k
if s >= POBLACION_MINIMA:
print("%.7f" % distancia)
exit(0)
print(-1)
```
Yes
| 1,976 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Submitted Solution:
```
import math as m
n, s = map(int, input().split())
MEGA_CITY = 10**6
cities =[]
for _ in range(n):
params = tuple(map(int, input().split()))
cities.append(params)
cities.sort(key=lambda dist: m.sqrt(dist[0]**2+dist[1]**2))
res = 0.0
current_population = s
for city in cities:
current_population += city[2]
if current_population >= MEGA_CITY:
res = m.sqrt(city[0] ** 2 + city[1] ** 2)
break
if current_population < MEGA_CITY:
print("-1")
else:
print("{0:.7f}".format(res))
```
Yes
| 1,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Submitted Solution:
```
import math
n, s = input ().split ()
n, s = int (n), int (s)
x1 = y1 = 0
p = False
r1 = -1
for i in range (n):
x, y, k = input ().split ()
x, y, k = int (x), int (y), int (k)
s += k
if p == False:
if x > x1:
x1 = x
if y > y1:
y1 = y
if s >= 1000000:
r = math.sqrt (x1 * x1 + y1 * y1)
r1 = r
p = True
print(round(r1,7))
```
No
| 1,978 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Submitted Solution:
```
# @Author: Justin Hershberger
# @Date: 28-03-2017
# @Filename: 424B.py
# @Last modified by: Justin Hershberger
# @Last modified time: 28-03-2017
import math
if __name__ == '__main__':
n, pop = map(int, input().split())
loc = []
for arg in range(n):
loc.append(input().split())
# print(n,pop)
# print(loc)
radius = -1
for r in range(len(loc)):
if pop + int(loc[r][2]) >= 1000000:
radius = math.sqrt(int(loc[r][0])**2 + int(loc[r][1])**2)
break
else:
pop += int(loc[r][2])
if radius == -1:
print(radius)
else:
print("{0:.7f}".format(radius))
```
No
| 1,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Submitted Solution:
```
from sys import maxsize, stdout, stdin,stderr
mod = int(1e9 + 7)
import sys
def I(): return int(stdin.readline())
def lint(): return [int(x) for x in stdin.readline().split()]
def S(): return input().strip()
def grid(r, c): return [lint() for i in range(r)]
from collections import defaultdict, Counter
import math
import heapq
from heapq import heappop , heappush
import bisect
from itertools import groupby
def gcd(a,b):
while b:
a %= b
tmp = a
a = b
b = tmp
return a
def lcm(a,b):
return a / gcd(a, b) * b
def check_prime(n):
for i in range(2, int(n ** (1 / 2)) + 1):
if not n % i:
return False
return True
def Bs(a, x):
i=0
j=0
left = 1
right = k
flag=False
while left<right:
mi = (left+right)//2
#print(smi,a[mi],x)
if a[mi]<=x:
left = mi+1
i+=1
else:
right = mi
j+=1
#print(left,right,"----")
#print(i-1,j)
if left>0 and a[left-1]==x:
return i-1, j
else:
return -1, -1
def nCr(n, r):
return (fact(n) // (fact(r)
* fact(n - r)))
# Returns factorial of n
def fact(n):
res = 1
for i in range(2, n+1):
res = res * i
return res
def primefactors(n):
num=0
while n % 2 == 0:
num+=1
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
num+=1
n = n // i
if n > 2:
num+=1
return num
'''
def iter_ds(src):
store=[src]
while len(store):
tmp=store.pop()
if not vis[tmp]:
vis[tmp]=True
for j in ar[tmp]:
store.append(j)
'''
def ask(a):
print('? {}'.format(a),flush=True)
n=lint()
return n
def bstemp(n,k):
l=1
r=n+1
while l<r:
mid=(l+r)//2
if (mid*(mid+1)*5)//2+k<=4*60:
l=mid+1
else:
r=mid
return l
def dfs(i,p):
a,tmp=0,0
for j in d[i]:
if j!=p:
a+=1
tmp+=dfs(j,i)
if a==0:
return 0
return tmp/a + 1
def primeFactors(n):
l=[]
while n % 2 == 0:
l.append(2)
n = n // 2
if n > 2:
l.append(n)
return l
n,s=lint()
s=10**6-s
a=[]
r=0
for _ in range(n):
x,y,k=lint()
r+=k
a.append([math.sqrt(x**2+y**2),r])
a.sort()
if r<s:
print(-1)
else:
l,r=0,n-1
while l<r:
mid=l+(r-l)//2
if a[mid][1]>=s:
r=mid
else:
l=mid+1
print(a[r][0])
```
No
| 1,980 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.
Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.
Input
The first line of the input contains two integers n and s (1 β€ n β€ 103; 1 β€ s < 106) β the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers β the xi and yi coordinate values of the i-th location and the number ki of people in it (1 β€ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value.
It is guaranteed that no two locations are at the same point and no location is at point (0; 0).
Output
In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number β the minimum radius of the circle that the city needs to expand to in order to become a megacity.
The answer is considered correct if the absolute or relative error don't exceed 10 - 6.
Examples
Input
4 999998
1 1 1
2 2 1
3 3 1
2 -2 1
Output
2.8284271
Input
4 999998
1 1 2
2 2 1
3 3 1
2 -2 1
Output
1.4142136
Input
2 1
1 1 999997
2 2 1
Output
-1
Submitted Solution:
```
from math import sqrt
n, s = input().split()
n, s = int(n), int(s)
coord = [[abs(int(j)) for j in input().split()] for i in range(n)]
coord.sort()
print(coord)
i = 0
b = True
while b and i < n:
rad = sqrt(coord[i][0]*coord[i][0] + coord[i][1]*coord[i][1])
s += coord[i][2]
i += 1
if s >= 1000000:
b = False
break
if b:
print(-1)
else:
print(rad)
```
No
| 1,981 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bizon the Champion isn't just friendly, he also is a rigorous coder.
Let's define function f(a), where a is a sequence of integers. Function f(a) returns the following sequence: first all divisors of a1 go in the increasing order, then all divisors of a2 go in the increasing order, and so on till the last element of sequence a. For example, f([2, 9, 1]) = [1, 2, 1, 3, 9, 1].
Let's determine the sequence Xi, for integer i (i β₯ 0): X0 = [X] ([X] is a sequence consisting of a single number X), Xi = f(Xi - 1) (i > 0). For example, at X = 6 we get X0 = [6], X1 = [1, 2, 3, 6], X2 = [1, 1, 2, 1, 3, 1, 2, 3, 6].
Given the numbers X and k, find the sequence Xk. As the answer can be rather large, find only the first 105 elements of this sequence.
Input
A single line contains two space-separated integers β X (1 β€ X β€ 1012) and k (0 β€ k β€ 1018).
Output
Print the elements of the sequence Xk in a single line, separated by a space. If the number of elements exceeds 105, then print only the first 105 elements.
Examples
Input
6 1
Output
1 2 3 6
Input
4 2
Output
1 1 2 1 2 4
Input
10 3
Output
1 1 1 2 1 1 5 1 1 2 1 5 1 2 5 10
Tags: brute force, dfs and similar, implementation, number theory
Correct Solution:
```
import sys
solSaved = {}
solSavedPropios = {}
def DivisorsN(n):
key = solSaved.get(str(n))
if key == None :
divisors = []
divisors2 = []
for i in range(1,int(n ** (1/2)) + 1):
if n % i == 0 :
if abs(i - (n/i)) < 10 ** (-7) : divisors.append(int(i))
else :
divisors.append(int(i))
temp = []
temp.append(int(n/i))
divisors2 = temp + divisors2
divisors = divisors + divisors2
solSaved[str(n)] = divisors.copy()
return divisors
return key
def TodosLosDivisores(arrayN) :
sol = []
if len(arrayN) > 10 ** 5 :
newArrayN = []
for k in range(len(arrayN)):
newArrayN.append(arrayN[k])
arrayN = newArrayN
for i in range(len(arrayN) - 1):
temp = DivisorsN(arrayN[i])
for t in range(len(temp)) : sol.append(temp[t])
#sol = sol + solSaved.get(str(arrayN[len(arrayN) - 1]))
temp = sol.copy()
temp2 = solSaved.get(str(arrayN[len(arrayN) - 1]))
sol.append(temp2)
for t in range(len(temp2)) : temp.append(temp2[t])
solSaved[str(temp2)] = temp
return sol
def DivisorsXk():
a, b = input().split()
x = int(a)
k = int(b)
if x == 1 : return 1
if k == 0 : return x
if k == 1 : return DivisorsN(x)
sol = []
sol.append(x)
solSaved[str(x)] = DivisorsN(x)
# index = 0
# for i in range(k):
# prev_index = len(sol)
# for j in range(index, len(sol)):
# divs = DivisorsN(sol[j])
# sol = sol + divs
# index = prev_index
i = 1
while i <= k :
# j = 0
# while j < len(sol):
# if type(sol[j]) == int : newSol.append(DivisorsN(sol[j]))
# else : newSol = newSol + DivisorAll(sol[j])
# j+=1
# sol = newSol
if type(sol[i - 1]) == int : sol.append(DivisorsN(sol[i - 1]))
else : sol.append(TodosLosDivisores(sol[i - 1]))
i += 1
temp = []
temp2 = sol[len(sol) - 1]
for t in range(len(temp2) - 1) : temp.append(temp2[t])
temp = temp + temp2[len(temp2) - 1]
return temp
def LosFuckingDivisoresDeUnArrayConLista(a) :
sol = []
if type(a) == int : return DivisorsN(a)
for i in range(len(a)) :
temp = []
key = solSaved.get(str(a[i]))
if key == None : temp = LosFuckingDivisoresDeUnArrayConLista(a[i])
else : temp = key
sol.append(temp)
solSaved[str(a)] = sol
return sol
def Divisors(x, k) :
if k == 0 : return x
if k > 10 ** 5 :
Ones = []
for i in range(10 ** 5) : Ones.append(1)
return Ones
key = solSaved.get(str((x,k)))
if key == None :
sol = []
if type(x) == int : return Divisors(DivisorsN(x), k - 1)
else :
sol = []
for i in range(len(x)) :
temp = []
temp.append(Divisors(x[i], k - 1))
sol = sol + temp
return sol
else : return key
def DivisorsPropios(n) :
key = solSavedPropios.get(str(n))
if key == None :
divisors = []
divisors2 = []
for i in range(2,int(n ** (1/2)) + 1):
if n % i == 0 :
if abs(i - (n/i)) < 10 ** (-7) : divisors.append(int(i))
else :
divisors.append(int(i))
temp = []
temp.append(int(n/i))
divisors2 = temp + divisors2 #divisors2.append(int(n / i))
divisors = divisors + divisors2
solSavedPropios[str(n)] = divisors.copy()
return divisors
return key
def UltimateDivisors(x, k) :
if x == 1 : return 1
if k == 0 : return x
if k == 1 : return DivisorsN(x)
if k >= 10 ** 5 :
a = []
for i in range(10 ** 5) : a.append(1)
return a
Unos = []
sol = []
sol.append(1)
temp = DivisorsPropios(x).copy()
for i in range(k - 1) : Unos.append(1)
if len(temp) == 0 : return [1] + Unos + [x]
temp.append(x)
for t in range(len(temp)) :
if len(sol) >= 10 ** 5 : return sol
temp3 = DivisorsPropios(temp[t]).copy()
if len(temp3) == 0 :
temp4 = UltimateDivisors(temp[t], k - 1)
if type(temp4) == int : sol = sol + [temp4]
else : sol = sol + temp4
else : sol = sol + NewUltimateDivisores(temp[t], k - 1)
return sol
def NewUltimateDivisores(x, k) :
temp = DivisorsPropios(x)
i = k - 1
sol = []
while i >= 1 :
if len(sol) >= 10**5 : return sol
sol = sol + [1]
for t in range(len(temp)) :
temp2 = UltimateDivisors(temp[t], i)
if type(temp2) == int : sol = sol + [temp2]
else : sol = sol + temp2
i -= 1
return sol + DivisorsN(x)
#print(UltimateDivisors(963761198400,65535))
#print(UltimateDivisors(549755813888,269))
a, b = input().split()
x = int(a)
k = int(b)
sol = UltimateDivisors(x,k)
if type(sol) == int : print(sol)
else :
if(len(sol) >= 10 ** 5):
for i in range(10 ** 5 - 1) :
sys.stdout.write(str(sol[i]) + ' ')
sys.stdout.write(str(sol[10**5 - 1]))
else :
for i in range(len(sol) - 1) :
sys.stdout.write(str(sol[i]) + ' ')
sys.stdout.write(str(sol[len(sol) - 1]))
```
| 1,982 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bizon the Champion isn't just friendly, he also is a rigorous coder.
Let's define function f(a), where a is a sequence of integers. Function f(a) returns the following sequence: first all divisors of a1 go in the increasing order, then all divisors of a2 go in the increasing order, and so on till the last element of sequence a. For example, f([2, 9, 1]) = [1, 2, 1, 3, 9, 1].
Let's determine the sequence Xi, for integer i (i β₯ 0): X0 = [X] ([X] is a sequence consisting of a single number X), Xi = f(Xi - 1) (i > 0). For example, at X = 6 we get X0 = [6], X1 = [1, 2, 3, 6], X2 = [1, 1, 2, 1, 3, 1, 2, 3, 6].
Given the numbers X and k, find the sequence Xk. As the answer can be rather large, find only the first 105 elements of this sequence.
Input
A single line contains two space-separated integers β X (1 β€ X β€ 1012) and k (0 β€ k β€ 1018).
Output
Print the elements of the sequence Xk in a single line, separated by a space. If the number of elements exceeds 105, then print only the first 105 elements.
Examples
Input
6 1
Output
1 2 3 6
Input
4 2
Output
1 1 2 1 2 4
Input
10 3
Output
1 1 1 2 1 1 5 1 1 2 1 5 1 2 5 10
Submitted Solution:
```
def main():
x, k = [int(i) for i in input().split()]
if k > 10 ** 5:
print(' '.join('1' for i in range(10 ** 5)))
else:
cur = [x]
for times in range(k):
next = []
for i in cur:
if len(next) >= 10 ** 5:
break
for j in range(1, i + 1):
if i % j == 0:
next.append(j)
if len(next) >= 10 ** 5:
break
cur = next
print(' '.join(str(i) for i in cur))
main()
```
No
| 1,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bizon the Champion isn't just friendly, he also is a rigorous coder.
Let's define function f(a), where a is a sequence of integers. Function f(a) returns the following sequence: first all divisors of a1 go in the increasing order, then all divisors of a2 go in the increasing order, and so on till the last element of sequence a. For example, f([2, 9, 1]) = [1, 2, 1, 3, 9, 1].
Let's determine the sequence Xi, for integer i (i β₯ 0): X0 = [X] ([X] is a sequence consisting of a single number X), Xi = f(Xi - 1) (i > 0). For example, at X = 6 we get X0 = [6], X1 = [1, 2, 3, 6], X2 = [1, 1, 2, 1, 3, 1, 2, 3, 6].
Given the numbers X and k, find the sequence Xk. As the answer can be rather large, find only the first 105 elements of this sequence.
Input
A single line contains two space-separated integers β X (1 β€ X β€ 1012) and k (0 β€ k β€ 1018).
Output
Print the elements of the sequence Xk in a single line, separated by a space. If the number of elements exceeds 105, then print only the first 105 elements.
Examples
Input
6 1
Output
1 2 3 6
Input
4 2
Output
1 1 2 1 2 4
Input
10 3
Output
1 1 1 2 1 1 5 1 1 2 1 5 1 2 5 10
Submitted Solution:
```
def DivisorsN(n):
divisors = []
divisors2 = []
for i in range(1,int(n ** (1/2)) + 1):
if n % i == 0 :
if abs(i - (n/i)) < 10 ** (-7) : divisors.append(i)
else :
divisors.append(i)
divisors2.append(n / i)
i = -1*(len(divisors2) - 1)
while i < 1 :
divisors.append(divisors2[i])
i += 1
return divisors
def asd(n) :
sol = []
for i in range(len(n)) :
sol.append(DivisorsN(n[i]))
return sol
def DivisorsXk():
a, b = input().split()
x = int(a)
k = int(b)
sol = []
i = 2
sol.append(x)
while i <= k :
j = 0
temp = []
while j < len(sol):
a = DivisorsN(sol[j])
for t in range(len(a)): temp.append(int(a[t]))
j+=1
sol = temp
i+= 1
return sol
print(DivisorsXk())
```
No
| 1,984 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bizon the Champion isn't just friendly, he also is a rigorous coder.
Let's define function f(a), where a is a sequence of integers. Function f(a) returns the following sequence: first all divisors of a1 go in the increasing order, then all divisors of a2 go in the increasing order, and so on till the last element of sequence a. For example, f([2, 9, 1]) = [1, 2, 1, 3, 9, 1].
Let's determine the sequence Xi, for integer i (i β₯ 0): X0 = [X] ([X] is a sequence consisting of a single number X), Xi = f(Xi - 1) (i > 0). For example, at X = 6 we get X0 = [6], X1 = [1, 2, 3, 6], X2 = [1, 1, 2, 1, 3, 1, 2, 3, 6].
Given the numbers X and k, find the sequence Xk. As the answer can be rather large, find only the first 105 elements of this sequence.
Input
A single line contains two space-separated integers β X (1 β€ X β€ 1012) and k (0 β€ k β€ 1018).
Output
Print the elements of the sequence Xk in a single line, separated by a space. If the number of elements exceeds 105, then print only the first 105 elements.
Examples
Input
6 1
Output
1 2 3 6
Input
4 2
Output
1 1 2 1 2 4
Input
10 3
Output
1 1 1 2 1 1 5 1 1 2 1 5 1 2 5 10
Submitted Solution:
```
from __future__ import print_function
maxx = 100000
n, m = map(int, input().split())
a = []
a.clear()
def dfs(x, y):
global maxx
if maxx == 0 :
return
if x == 0 or y == m :
maxx -= 1
print(a[x],' ',end="")
return
for d in range(x + 1):
if a[x] % a[d] == 0:
dfs(d, y + 1)
def main():
i = 1
while i * i < n :
if n % i == 0 :
a.append(i)
i += 1
if i * i > n : a.pop()
while i > 0 :
if n % i ==0 :
a.append(n//i)
i -= 1
dfs(len(a) - 1, 0)
if __name__ == '__main__':
main()
```
No
| 1,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bizon the Champion isn't just friendly, he also is a rigorous coder.
Let's define function f(a), where a is a sequence of integers. Function f(a) returns the following sequence: first all divisors of a1 go in the increasing order, then all divisors of a2 go in the increasing order, and so on till the last element of sequence a. For example, f([2, 9, 1]) = [1, 2, 1, 3, 9, 1].
Let's determine the sequence Xi, for integer i (i β₯ 0): X0 = [X] ([X] is a sequence consisting of a single number X), Xi = f(Xi - 1) (i > 0). For example, at X = 6 we get X0 = [6], X1 = [1, 2, 3, 6], X2 = [1, 1, 2, 1, 3, 1, 2, 3, 6].
Given the numbers X and k, find the sequence Xk. As the answer can be rather large, find only the first 105 elements of this sequence.
Input
A single line contains two space-separated integers β X (1 β€ X β€ 1012) and k (0 β€ k β€ 1018).
Output
Print the elements of the sequence Xk in a single line, separated by a space. If the number of elements exceeds 105, then print only the first 105 elements.
Examples
Input
6 1
Output
1 2 3 6
Input
4 2
Output
1 1 2 1 2 4
Input
10 3
Output
1 1 1 2 1 1 5 1 1 2 1 5 1 2 5 10
Submitted Solution:
```
def DivisorsN(n):
divisors = []
divisors2 = []
for i in range(1,int(n ** (1/2)) + 1):
if n % i == 0 :
if abs(i - (n/i)) < 10 ** (-7) : divisors.append(i)
else :
divisors.append(i)
divisors2.append(n / i)
i = -1*(len(divisors2) - 1)
while i < 1 :
divisors.append(divisors2[i])
i += 1
return divisors
def asd(n) :
sol = []
for i in range(len(n)) :
sol.append(DivisorsN(n[i]))
return sol
def DivisorsXk():
a, b = input().split()
x = int(a)
k = int(b)
sol = []
i = 2
sol.append(x)
while i <= k :
j = 0
temp = []
while j < len(sol):
a = DivisorsN(sol[j])
for t in range(len(a)): temp.append(a[t])
j+=1
sol = temp
i+= 1
return sol
print(DivisorsXk())
```
No
| 1,986 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books.
You are not informed on what crime was committed, when and where the corpse was found and other details. We only know that the crime was committed in a house that has n rooms and m doors between the pairs of rooms. The house residents are very suspicious, that's why all the doors can be locked with keys and all the keys are different. According to the provided evidence on Thursday night all the doors in the house were locked, and it is known in what rooms were the residents, and what kind of keys had any one of them. The same is known for the Friday night, when all the doors were also locked. On Friday it was raining heavily, that's why nobody left the house and nobody entered it. During the day the house residents could
* open and close doors to the neighboring rooms using the keys at their disposal (every door can be opened and closed from each side);
* move freely from a room to a room if a corresponding door is open;
* give keys to one another, being in one room.
"Little grey matter" of Hercule Poirot are not capable of coping with such amount of information. Find out if the positions of people and keys on the Thursday night could result in the positions on Friday night, otherwise somebody among the witnesses is surely lying.
Input
The first line contains three preset integers n, m ΠΈ k (1 β€ n, m, k β€ 1000) β the number of rooms, the number of doors and the number of house residents respectively. The next m lines contain pairs of room numbers which join the doors. The rooms are numbered with integers from 1 to n. There cannot be more that one door between the pair of rooms. No door connects a room with itself. The next k lines describe the residents' position on the first night. Every line contains a resident's name (a non-empty line consisting of no more than 10 Latin letters), then after a space follows the room number, then, after a space β the number of keys the resident has. Then follow written space-separated numbers of the doors that can be unlocked by these keys. The doors are numbered with integers from 1 to m in the order in which they are described in the input data. All the residents have different names, uppercase and lowercase letters considered to be different. Every m keys occurs exactly once in the description. Multiple people may be present in one room, some rooms may be empty. The next k lines describe the position of the residents on the second night in the very same format. It is guaranteed that in the second night's description the residents' names remain the same and every m keys occurs exactly once.
Output
Print "YES" (without quotes) if the second arrangement can result from the first one, otherwise, print "NO".
Examples
Input
2 1 2
1 2
Dmitry 1 1 1
Natalia 2 0
Natalia 1 1 1
Dmitry 2 0
Output
YES
Input
4 4 3
1 3
1 2
2 3
3 4
Artem 1 1 4
Dmitry 1 1 2
Edvard 4 2 1 3
Artem 2 0
Dmitry 1 0
Edvard 4 4 1 2 3 4
Output
NO
Tags: dsu, graphs
Correct Solution:
```
def solve(n,m,k,edge_list,house_members):
room_sets=[i for i in range(n)]
valid_move=[True for i in range(n)]
room_status=[ [1<<i,0,[]] for i in range(n)]
# room_status[i]->informacion de todo otro cuarto,persona y llave alcanzable para el cuarto i
# room_status[i][0]->los cuartos alcanzables por el cuarto i
# room_status[i][1]->las personas que pueden llegar al i
# room_status[i][2]->las llaves alcanzables por el cuarto i
for i in range(k):
room_status[house_members[i][1]][1]|=1<<i
for j in house_members[i][2]:
room_status[house_members[i][1]][2].append(j)
#print(room_status)
move=True
while move:
move=False
for i in range(n):
#print(valid_move)
if valid_move[i]:
move=move or expand(i,room_sets,valid_move,room_status,edge_list)
house_part=[]
for i in range(n):
if room_sets[i]==i:
house_part.append(i)
return adjust_answer(house_part,room_status,n,m,k)
def setoff(index,room_sets):
if room_sets[index]==index:
return index
else:
new_val=setoff(room_sets[index],room_sets)
room_sets[index]=new_val
return new_val
def expand(current_room,room_sets,valid_move,room_status,edge_list):
moving=room_status[current_room][2]
move=False
#print(current_room)
#print(edge_list)
for i in moving:
edge=edge_list[i]
#print(edge)
if setoff(edge[0],room_sets)==current_room:
move =move or merge(current_room,edge[1],room_sets,valid_move,room_status)
if setoff(edge[1],room_sets)==current_room:
move=move or merge(current_room,edge[0],room_sets,valid_move,room_status)
return move
def merge(x,y,room_sets,valid_move,room_status):
#print(x,y)
setx=setoff(x,room_sets)
sety=setoff(y,room_sets)
#print(setx,sety)
if setx==sety:
return False
else:
m=(len(room_status[setx][2]))
m1=len(room_status[sety][2])
if m >= m1:
head=setx
tail=sety
else:
head=sety
tail=setx
# print(head,tail)
valid_move[tail]=0
room_sets[tail]=head
keys=room_status[tail][2]
while len(keys)>0:
room_status[head][2].append(keys.pop())
room_status[head][1]|=room_status[tail][1]
room_status[head][0]|=room_status[tail][0]
return True
def adjust_answer(house_part,room_status,n,m,k):
size=len(house_part)
#print(house_part)
rooms=[0 for i in range(size)]
members=[0 for i in range(size)]
keys=[0 for i in range(size)]
for i in range(size):
keys_list=room_status[house_part[i]][2]
for j in keys_list:
keys[i]|=1<<j
rooms[i]=room_status[house_part[i]][0]
members[i]=room_status[house_part[i]][1]
#print(rooms)
#print(members)
#print(keys)
#rooms.sort()
#members.sort()
#keys.sort()
return [rooms,members,keys]
def compare_answer(answer_1,answer_2,n,m,k):
rooms1=answer_1[0]
members1=answer_1[1]
keys1=answer_1[2]
if len(rooms1)!=len(members1)!=len(keys1):
return False
rooms2=answer_2[0]
members2=answer_2[1]
keys2=answer_2[2]
if len(rooms2)!=len(members2)!=len(keys2):
return False
if len(rooms1)!=len(rooms2):
return False
for i in range(len(rooms1)):
if rooms1[i]!=rooms2[i] or keys1[i]!=keys2[i] or members1[i]!=members2[i]:
return False
return True
data=[int(i) for i in input().split()]
n,m,k=data[0],data[1],data[2]
house_members=[["",0,[]]for i in range(k)]
house_members_2=[["",0,[]]for i in range(k)]
pos_adjustment={}
edge_list=[]
for i in range(m):
doors_data=[int(i) for i in input().split()]
a,b=doors_data[0]-1,doors_data[1]-1
edge_list.append((a,b))
for i in range(k):
temp=input().split()
pos_adjustment[temp[0]]=i
house_members[i][0]=temp[0]
house_members[i][1]=int(temp[1])-1
for j in range(3,len(temp)):
val=int(temp[j])-1
house_members[i][2].append(val)
answer_1=solve(n,m,k,edge_list,house_members)
for i in range(k):
temp=input().split()
house_members_2[pos_adjustment[temp[0]]][0]=temp[0]
house_members_2[pos_adjustment[temp[0]]][1]=int(temp[1])-1
for j in range(3,len(temp)):
val=int(temp[j])-1
house_members_2[pos_adjustment[temp[0]]][2].append(val)
answer_2=solve(n,m,k,edge_list,house_members_2)
if compare_answer(answer_1,answer_2,n,m,k):
print("YES")
else :
print("NO")
```
| 1,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books.
You are not informed on what crime was committed, when and where the corpse was found and other details. We only know that the crime was committed in a house that has n rooms and m doors between the pairs of rooms. The house residents are very suspicious, that's why all the doors can be locked with keys and all the keys are different. According to the provided evidence on Thursday night all the doors in the house were locked, and it is known in what rooms were the residents, and what kind of keys had any one of them. The same is known for the Friday night, when all the doors were also locked. On Friday it was raining heavily, that's why nobody left the house and nobody entered it. During the day the house residents could
* open and close doors to the neighboring rooms using the keys at their disposal (every door can be opened and closed from each side);
* move freely from a room to a room if a corresponding door is open;
* give keys to one another, being in one room.
"Little grey matter" of Hercule Poirot are not capable of coping with such amount of information. Find out if the positions of people and keys on the Thursday night could result in the positions on Friday night, otherwise somebody among the witnesses is surely lying.
Input
The first line contains three preset integers n, m ΠΈ k (1 β€ n, m, k β€ 1000) β the number of rooms, the number of doors and the number of house residents respectively. The next m lines contain pairs of room numbers which join the doors. The rooms are numbered with integers from 1 to n. There cannot be more that one door between the pair of rooms. No door connects a room with itself. The next k lines describe the residents' position on the first night. Every line contains a resident's name (a non-empty line consisting of no more than 10 Latin letters), then after a space follows the room number, then, after a space β the number of keys the resident has. Then follow written space-separated numbers of the doors that can be unlocked by these keys. The doors are numbered with integers from 1 to m in the order in which they are described in the input data. All the residents have different names, uppercase and lowercase letters considered to be different. Every m keys occurs exactly once in the description. Multiple people may be present in one room, some rooms may be empty. The next k lines describe the position of the residents on the second night in the very same format. It is guaranteed that in the second night's description the residents' names remain the same and every m keys occurs exactly once.
Output
Print "YES" (without quotes) if the second arrangement can result from the first one, otherwise, print "NO".
Examples
Input
2 1 2
1 2
Dmitry 1 1 1
Natalia 2 0
Natalia 1 1 1
Dmitry 2 0
Output
YES
Input
4 4 3
1 3
1 2
2 3
3 4
Artem 1 1 4
Dmitry 1 1 2
Edvard 4 2 1 3
Artem 2 0
Dmitry 1 0
Edvard 4 4 1 2 3 4
Output
NO
Submitted Solution:
```
def solve(n,m,k,edge_list,house_members):
room_sets=[i for i in range(n)]
valid_move=[True for i in range(n)]
room_status=[ [1<<i,0,[]] for i in range(n)]
# room_status[i]->informacion de todo otro cuarto,persona y llave alcanzable para el cuarto i
# room_status[i][0]->los cuartos alcanzables por el cuarto i
# room_status[i][1]->las personas que pueden llegar al i
# room_status[i][2]->las llaves alcanzables por el cuarto i
for i in range(k):
room_status[house_members[i][1]][1]|=1<<i
for j in house_members[i][2]:
room_status[house_members[i][1]][2].append(j)
#print(room_status)
move=True
while move:
move=False
for i in range(n):
#print(valid_move)
if valid_move[i]:
move=move or expand(i,room_sets,valid_move,room_status,edge_list)
house_part=[]
for i in range(n):
if room_sets[i]==i:
house_part.append(i)
return adjust_answer(house_part,room_status,n,m,k)
def setoff(index,room_sets):
if room_sets[index]==index:
return index
else:
new_val=setoff(room_sets[index],room_sets)
room_sets[index]=new_val
return new_val
def expand(current_room,room_sets,valid_move,room_status,edge_list):
moving=room_status[current_room][2]
move=False
#print(current_room)
#print(edge_list)
for i in moving:
edge=edge_list[i]
#print(edge)
if setoff(edge[0],room_sets)==current_room:
move =move or merge(current_room,edge[1],room_sets,valid_move,room_status)
if setoff(edge[1],room_sets)==current_room:
move=move or merge(current_room,edge[0],room_sets,valid_move,room_status)
return move
def merge(x,y,room_sets,valid_move,room_status):
#print(x,y)
setx=setoff(x,room_sets)
sety=setoff(y,room_sets)
#print(setx,sety)
if setx==sety:
return False
else:
m=(len(room_status[setx][2]))
m1=len(room_status[sety][2])
if m >= m1:
head=setx
tail=sety
else:
head=sety
tail=setx
# print(head,tail)
valid_move[tail]=0
room_sets[tail]=head
keys=room_status[tail][2]
while len(keys)>0:
room_status[head][2].append(keys.pop())
room_status[head][1]|=room_status[tail][1]
room_status[head][0]|=room_status[tail][0]
return True
def adjust_answer(house_part,room_status,n,m,k):
size=len(house_part)
#print(house_part)
rooms=[0 for i in range(size)]
members=[0 for i in range(size)]
keys=[0 for i in range(size)]
for i in range(size):
keys_list=room_status[house_part[i]][2]
for j in keys_list:
keys[i]|=1<<j
rooms[i]=room_status[house_part[i]][0]
members[i]=room_status[house_part[i]][1]
#print(rooms)
#print(members)
#print(keys)
rooms.sort()
members.sort()
keys.sort()
return [rooms,members,keys]
def compare_answer(answer_1,answer_2,n,m,k):
rooms1=answer_1[0]
members1=answer_1[1]
keys1=answer_1[2]
if len(rooms1)!=len(members1)!=len(keys1):
return False
rooms2=answer_2[0]
members2=answer_2[1]
keys2=answer_2[2]
if len(rooms2)!=len(members2)!=len(keys2):
return False
if len(rooms1)!=len(rooms2):
return False
for i in range(len(rooms1)):
if rooms1[i]!=rooms2[i] or keys1[i]!=keys2[i] or members1[i]!=members2[i]:
return False
return True
data=[int(i) for i in input().split()]
n,m,k=data[0],data[1],data[2]
house_members=[["",0,[]]for i in range(k)]
house_members_2=[["",0,[]]for i in range(k)]
pos_adjustment={}
edge_list=[]
for i in range(m):
doors_data=[int(i) for i in input().split()]
a,b=doors_data[0]-1,doors_data[1]-1
edge_list.append((a,b))
for i in range(k):
temp=input().split()
pos_adjustment[temp[0]]=i
house_members[i][0]=temp[0]
house_members[i][1]=int(temp[1])-1
for j in range(3,len(temp)):
val=int(temp[j])-1
house_members[i][2].append(val)
answer_1=solve(n,m,k,edge_list,house_members)
for i in range(k):
temp=input().split()
house_members_2[pos_adjustment[temp[0]]][0]=temp[0]
house_members_2[pos_adjustment[temp[0]]][1]=int(temp[1])-1
for j in range(3,len(temp)):
val=int(temp[j])-1
house_members_2[pos_adjustment[temp[0]]][2].append(val)
answer_2=solve(n,m,k,edge_list,house_members_2)
if compare_answer(answer_1,answer_2,n,m,k):
print("YES")
else :
print("NO")
```
No
| 1,988 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Tags: implementation
Correct Solution:
```
arr = []
brr = []
for _ in range(int(input())):
n = int(input())
#print(n)
if n > 0:
arr.append(n)
else:
brr.append(-1*n)
#print(arr,brr,n)
if sum(arr) > sum(brr):
print("first")
elif sum(arr) < sum(brr):
print("second")
else:
if arr > brr:
print("first")
elif arr < brr:
print("second")
else:
if n > 0:
print("first")
else:
print("second")
```
| 1,989 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Tags: implementation
Correct Solution:
```
n=int(input())
c1=0
c2=0
c11=[]
c22=[]
ko=0
for i in range(n):
a=int(input())
if a>0:
c1+=a
kk=str(a)
c11.append(a)
ko=1
else:
c2+=abs(a)
kk=str(abs(a))
c22.append(abs(a))
ko=0
if len(c11)<len(c22):
pp=1
elif len(c11)>len(c22):
pp=-1
else:
pp=0
for i in range(min(len(c11),len(c22))):
if c11[i]>c22[i]:
pp=1
break
elif c11[i]<c22[i]:
pp=-1
break
if c1>c2:
print("first")
elif c1<c2:
print("second")
elif c1==c2:
if pp==1:
print("first")
elif pp==-1:
print("second")
elif pp==0:
if ko==0:
print("second")
elif ko==1:
print("first")
```
| 1,990 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Tags: implementation
Correct Solution:
```
n=int(input())
f=[]
s=[]
fsc=0
ssc=0
for i in range(n):
x=int(input())
if x>0:
f.append(x)
fsc+=x
else:
ssc+=-x
s.append(-x)
if i==n-1:
las=x
if fsc>ssc:
print('first')
elif ssc>fsc:
print('second')
elif f>s:
print('first')
elif f<s:
print('second')
else:
if las>0:
print('first')
else:
print('second')
```
| 1,991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Tags: implementation
Correct Solution:
```
n = int(input())
a = []
b = []
x = 0
for i in range(n):
q = int(input())
if q > 0:
x = 1
a.append(q)
else:
x = -1
b.append(-q)
if sum(a) != sum(b):
print('first' if sum(a) > sum(b) else 'second')
elif a != b:
print('first' if a > b else 'second')
else:
print('first' if x > 0 else 'second')
```
| 1,992 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Tags: implementation
Correct Solution:
```
# pylint: disable=unused-variable
# pylint: enable=too-many-lines
#* Just believe in yourself
#@ Author @CAP
import os
import sys
from io import BytesIO, IOBase
import math as M
import itertools as ITR
from collections import defaultdict as D
from collections import Counter as C
from collections import deque as Q
import threading
from functools import lru_cache, reduce
from functools import cmp_to_key as CMP
from bisect import bisect_left as BL
from bisect import bisect_right as BR
import random as R
import string
import cmath,time
enum=enumerate
start_time = time.time()
#? Variables
MOD=1_00_00_00_007; MA=float("inf"); MI=float("-inf")
#?graph 8 direction
di8=[(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]
#?graph 4 direction
di4=[(1, 0), (0, 1), (-1, 0), (0, -1)]
#? Stack increment
def increase_stack():
sys.setrecursionlimit(2**32//2-1)
threading.stack_size(1 << 27)
#sys.setrecursionlimit(10**6)
#threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join()
#? Region Funtions
def prints(a):
print(a,end=" ")
def binary(n):
return bin(n)[2:]
def decimal(s):
return (int(s, 2))
def pow2(n):
p = 0
while (n > 1):
n //= 2
p += 1
return (p)
def maxfactor(n):
q = []
for i in range(1,int(n ** 0.5) + 1):
if n % i == 0: q.append(i)
if q:
return q[-1]
def factors(n):
q = []
for i in range(1,int(n ** 0.5) + 1):
if n % i == 0: q.append(i); q.append(n // i)
return(list(sorted(list(set(q)))))
def primeFactors(n):
l=[]
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(M.sqrt(n)) + 1, 2):
while n % i == 0:
l.append(i)
n = n / i
if n > 2:
l.append(int(n))
l.sort()
return (l)
def isPrime(n):
if (n == 1):
return (False)
else:
root = int(n ** 0.5)
root += 1
for i in range(2, root):
if (n % i == 0):
return (False)
return (True)
def seive(n):
a = [1]
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p ** 2,n + 1,p):
prime[i] = False
p = p + 1
for p in range(2,n + 1):
if prime[p]:
a.append(p)
return(a)
def maxPrimeFactors(n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(M.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
def countchar(s,i):
c=0
ch=s[i]
for i in range(i,len(s)):
if(s[i]==ch):
c+=1
else:
break
return(c)
def str_counter(a):
q = [0] * 26
for i in range(len(a)):
q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
return(q)
def lis(arr):
n = len(arr)
lis = [1] * n
maximum=0
for i in range(1, n):
for j in range(0, i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
maximum=max(maximum,lis[i])
return maximum
def lcm(arr):
a=arr[0]; val=arr[0]
for i in range(1,len(arr)):
gcd=gcd(a,arr[i])
a=arr[i]; val*=arr[i]
return val//gcd
def ncr(n,r):
return M.factorial(n) // (M.factorial(n - r) * M.factorial(r))
def npr(n,r):
return M.factorial(n) // M.factorial(n - r)
#? Region Taking Input
def inint():
return int(inp())
def inarr():
return list(map(int,inp().split()))
def invar():
return map(int,inp().split())
def instr():
s=inp()
return list(s)
def insarr():
return inp().split()
#? Region Fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
inp = lambda: sys.stdin.readline().rstrip("\r\n")
#<==================================== Write The Useful Code Here ============================
#< Make it one if there is some test cases
TestCases=0 #<=====================
#< =======================================
"""
> Sometimes later becomes never. Do it now.
! Be Better than yesterday.
* Your limitationβitβs only your imagination.
> Push yourself, because no one else is going to do it for you.
? The harder you work for something, the greater youβll feel when you achieve it.
! Great things never come from comfort zones.
* Donβt stop when youβre tired. Stop when youβre done.
> Do something today that your future self will thank you for.
? Itβs going to be hard, but hard does not mean impossible.
! Sometimes weβre tested not to show our weaknesses, but to discover our strengths.
"""
#@ Goal is to get Candidate Master
def solve():
n=inint()
p1 = 0; p2 = 0; l1 = 0; l2 = 0; flag=0; aseq=[]; bseq=[]
for i in range(n):
a=inint()
if a>0:
p1+=a; l1+=1; flag=1
aseq.append(a)
else:
p2+=abs(a); l2+=1; flag=0
bseq.append(abs(a))
if p1>p2: print("first"); return
if p1==p2:
if aseq==bseq:
if flag:
print("first"); return
if aseq>bseq:
print("first"); return
print("second")
#! This is the Main Function
def main():
flag=0
#! Checking we are offline or not
try:
sys.stdin = open("c:/Users/Manoj Chowdary/Documents/python/CodeForces/contest-div-2/input.txt","r")
sys.stdout = open("c:/Users/Manoj Chowdary/Documents/python/CodeForces/contest-div-2/output.txt","w")
except: flag=1
t=1
if TestCases:
t = inint()
for _ in range(1,t + 1):
solve()
if not flag:
print("Time: %.4f sec"%(time.time() - start_time))
localtime = time.asctime( time.localtime(time.time()) )
print(localtime)
sys.stdout.close()
#? End Region
if __name__ == "__main__":
#? Incresing Stack Limit
#increase_stack()
#! Calling Main Function
main()
```
| 1,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Tags: implementation
Correct Solution:
```
a = []
b = []
last = 0
for i in range(int(input())):
j = int(input())
if j > 0:
last = 1
a.append(j)
else:
last = 0
b.append(-j)
suma = sum(a)
sumb = sum(b)
if suma > sumb or (suma == sumb and a > b) or (suma == sumb and a == b and last == 1):
print("first")
else:
print("second")
```
| 1,994 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Tags: implementation
Correct Solution:
```
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest
sys.setrecursionlimit(111111)
INF=99999999999999999999999999999999
def main():
mod=1000000007
# InverseofNumber(mod)
# InverseofFactorial(mod)
# factorial(mod)
starttime=datetime.datetime.now()
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
###CODE
tc = 1
for _ in range(tc):
n=ri()
player1=0
player2=0
p1=[]
p2=[]
lp=-1
for i in range(n):
score=ri()
if score>0:
player1+=score
p1.append(score)
lp=1
else:
player2-=score
p2.append(-score)
lp=2
if player1>player2:
print("first")
elif player2>player1:
print("second")
else:
if p1>p2:
print("first")
elif p2>p1:
print("second")
else:
if lp==1:
print("first")
else:
print("second")
#<--Solving Area Ends
endtime=datetime.datetime.now()
time=(endtime-starttime).total_seconds()*1000
if(os.path.exists('input.txt')):
print("Time:",time,"ms")
class FastReader(io.IOBase):
newlines = 0
def __init__(self, fd, chunk_size=1024 * 8):
self._fd = fd
self._chunk_size = chunk_size
self.buffer = io.BytesIO()
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
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, size=-1):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
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()
class FastWriter(io.IOBase):
def __init__(self, fd):
self._fd = fd
self.buffer = io.BytesIO()
self.write = self.buffer.write
def flush(self):
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class FastStdin(io.IOBase):
def __init__(self, fd=0):
self.buffer = FastReader(fd)
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class FastStdout(io.IOBase):
def __init__(self, fd=1):
self.buffer = FastWriter(fd)
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.flush = self.buffer.flush
if __name__ == '__main__':
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()
```
| 1,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Tags: implementation
Correct Solution:
```
def lex(a,b):
for i in range(min(len(a),len(b))):
if a[i]>b[i]:
return True
elif a[i]<b[i]:
return False
if len(a)>len(b):
return True
return False
n=int(input())
w1=[]
w2=[]
last=True
for i in range(n):
x=int(input())
if x<0:
last=False
w2.append(-x)
else:
last=True
w1.append(x)
if sum(w1)>sum(w2):
print("first")
elif sum(w1)==sum(w2):
if lex(w1,w2):
print("first")
elif lex(w2,w1):
print("second")
else:
if last:
print("first")
else:
print("second")
else:
print("second")
```
| 1,996 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Submitted Solution:
```
n = int(input())
first = []
second = []
last = 0
for i in range(n):
a = int(input())
if a>0:
first.append(a)
else:
second.append(abs(a))
if i==n-1:
last = a
if abs(sum(first))>abs(sum(second)):
print('first')
quit()
if abs(sum(first))<abs(sum(second)):
print('second')
else:
if first>second:
print('first')
quit()
if first<second:
print('second')
else:
if last>0:
print('first')
else:
print('second')
```
Yes
| 1,997 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Submitted Solution:
```
import sys
input=sys.stdin.buffer.readline
import os
t=int(input())
arr=[]
brr=[]
last=0
while t:
t-=1
n=int(input())
last=n
if n<0:
brr.append(-n)
else:
arr.append(n)
if sum(arr)>sum(brr):
print("first")
elif sum(arr)<sum(brr):
print("second")
else:
z=""
for i in range(min(len(arr),len(brr))):
if arr[i]>brr[i]:
z="first"
break
elif arr[i]<brr[i]:
z="second"
break
if z=="":
if last<0:
print("second")
else:
print("first")
else:
print(z)
```
Yes
| 1,998 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
Input
The first line contains number n β the number of techniques that the wrestlers have used (1 β€ n β€ 2Β·105).
The following n lines contain integer numbers ai (|ai| β€ 109, ai β 0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with ( - ai) points.
The techniques are given in chronological order.
Output
If the first wrestler wins, print string "first", otherwise print "second"
Examples
Input
5
1
2
-3
-4
3
Output
second
Input
3
-1
-2
3
Output
first
Input
2
4
-4
Output
second
Note
Sequence x = x1x2... x|x| is lexicographically larger than sequence y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there is such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1.
We use notation |a| to denote length of sequence a.
Submitted Solution:
```
class CodeforcesTask493BSolution:
def __init__(self):
self.result = ''
self.n = 0
self.points = []
def read_input(self):
self.n = int(input())
for x in range(self.n):
self.points.append(int(input()))
def process_task(self):
first = [x for x in self.points if x > 0]
second = [-x for x in self.points if x < 0]
f_points = sum(first)
s_points = sum(second)
if f_points > s_points:
self.result = "first"
elif f_points < s_points:
self.result = "second"
else:
if len(first) > len(second) and first[:len(second)] == second:
self.result = "first"
elif len(first) < len(second) and first == second[:len(first)]:
self.result = "second"
else:
x = 0
while first[x] == second[x]:
x += 1
if x == len(first):
break
if x == len(first):
if self.points[-1] > 0:
self.result = "first"
else:
self.result = "second"
else:
if first[x] > second[x]:
self.result = "first"
else:
self.result = "second"
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask493BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
```
Yes
| 1,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.