message stringlengths 2 65.1k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 0 108k | cluster float64 14 14 | __index_level_0__ int64 0 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sagheer is working at a kindergarten. There are n children and m different toys. These children use well-defined protocols for playing with the toys:
* Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set.
* If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever.
* Children request toys at distinct moments of time. No two children request a toy at the same time.
* If a child is granted a toy, he never gives it back until he finishes playing with his lovely set.
* If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting.
* If two children are waiting for the same toy, then the child who requested it first will take the toy first.
Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy.
Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set.
Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child x that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child x is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child x will make his last request, how many children will start crying?
You will be given the scenario and q independent queries. Each query will be of the form x y meaning that the last request of the child x is for the toy y. Your task is to help Sagheer find the size of the maximal crying set when child x makes his last request.
Input
The first line contains four integers n, m, k, q (1 ≤ n, m, k, q ≤ 105) — the number of children, toys, scenario requests and queries.
Each of the next k lines contains two integers a, b (1 ≤ a ≤ n and 1 ≤ b ≤ m) — a scenario request meaning child a requests toy b. The requests are given in the order they are made by children.
Each of the next q lines contains two integers x, y (1 ≤ x ≤ n and 1 ≤ y ≤ m) — the request to be added to the scenario meaning child x will request toy y just after getting the toy he is waiting for (if any).
It is guaranteed that the scenario requests are consistent and no child is initially crying. All the scenario requests are distinct and no query coincides with a scenario request.
Output
For each query, print on a single line the number of children who will start crying when child x makes his last request for toy y. Please answer all queries independent of each other.
Examples
Input
3 3 5 1
1 1
2 2
3 3
1 2
2 3
3 1
Output
3
Input
5 4 7 2
1 1
2 2
2 1
5 1
3 3
4 4
4 1
5 3
5 4
Output
0
2
Note
In the first example, child 1 is waiting for toy 2, which child 2 has, while child 2 is waiting for top 3, which child 3 has. When child 3 makes his last request, the toy he requests is held by child 1. Each of the three children is waiting for a toy held by another child and no one is playing, so all the three will start crying.
In the second example, at the beginning, child i is holding toy i for 1 ≤ i ≤ 4. Children 1 and 3 have completed their lovely sets. After they finish playing, toy 3 will be free while toy 1 will be taken by child 2 who has just completed his lovely set. After he finishes, toys 1 and 2 will be free and child 5 will take toy 1. Now:
* In the first query, child 5 will take toy 3 and after he finishes playing, child 4 can play.
* In the second query, child 5 will request toy 4 which is held by child 4. At the same time, child 4 is waiting for toy 1 which is now held by child 5. None of them can play and they will start crying.
Submitted Solution:
```
from collections import deque
def dfs(i, matrix):
global stack, time
time += 1
t_in = time
for j in matrix[i]:
dfs(j, matrix)
time += 1
stack.append([i, t_in, time])
n, m, k, q = map(int, input().split())
d = [None for i in range(m)]
roots = set(range(n))
matrix = [[] for i in range(n)]
for i in range(k):
x, y = map(int, input().split())
if d[y - 1] is None:
d[y - 1] = x - 1
else:
matrix[d[y - 1]].append(x - 1)
roots.discard(x - 1)
d[y - 1] = x - 1
location = [None for i in range(n)]
comp_of_conn = []
for i in roots:
stack = []
time = 0
dfs(i, matrix)
stack.reverse()
if len(stack) > 1:
for j in range(len(stack)):
location[stack[j][0]] = [len(comp_of_conn), j]
queue = deque()
queue.append([stack[0][0], 0])
while queue:
stack[location[queue[0][0]][1]].append(queue[0][1])
for j in matrix[queue[0][0]]:
queue.append([j, queue[0][1] + 1])
queue.popleft()
comp_of_conn.append(stack)
for i in range(q):
x, y = map(int, input().split())
x -= 1
y = d[y - 1]
if y is None:
print(0)
elif location[x] is not None and location[y] is not None and location[x][0] == location[y][0]:
c = location[x][0]
ind_x = location[x][1]
ind_y = location[y][1]
if comp_of_conn[c][ind_x][1] < comp_of_conn[c][ind_y][1] and comp_of_conn[c][ind_x][2] > comp_of_conn[c][ind_y][
2]:
print(comp_of_conn[c][ind_y][3] - comp_of_conn[c][ind_x][3] + 1)
else:
print(0)
else:
print(0)
``` | instruction | 0 | 70,396 | 14 | 140,792 |
No | output | 1 | 70,396 | 14 | 140,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sagheer is working at a kindergarten. There are n children and m different toys. These children use well-defined protocols for playing with the toys:
* Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set.
* If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever.
* Children request toys at distinct moments of time. No two children request a toy at the same time.
* If a child is granted a toy, he never gives it back until he finishes playing with his lovely set.
* If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting.
* If two children are waiting for the same toy, then the child who requested it first will take the toy first.
Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy.
Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set.
Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child x that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child x is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child x will make his last request, how many children will start crying?
You will be given the scenario and q independent queries. Each query will be of the form x y meaning that the last request of the child x is for the toy y. Your task is to help Sagheer find the size of the maximal crying set when child x makes his last request.
Input
The first line contains four integers n, m, k, q (1 ≤ n, m, k, q ≤ 105) — the number of children, toys, scenario requests and queries.
Each of the next k lines contains two integers a, b (1 ≤ a ≤ n and 1 ≤ b ≤ m) — a scenario request meaning child a requests toy b. The requests are given in the order they are made by children.
Each of the next q lines contains two integers x, y (1 ≤ x ≤ n and 1 ≤ y ≤ m) — the request to be added to the scenario meaning child x will request toy y just after getting the toy he is waiting for (if any).
It is guaranteed that the scenario requests are consistent and no child is initially crying. All the scenario requests are distinct and no query coincides with a scenario request.
Output
For each query, print on a single line the number of children who will start crying when child x makes his last request for toy y. Please answer all queries independent of each other.
Examples
Input
3 3 5 1
1 1
2 2
3 3
1 2
2 3
3 1
Output
3
Input
5 4 7 2
1 1
2 2
2 1
5 1
3 3
4 4
4 1
5 3
5 4
Output
0
2
Note
In the first example, child 1 is waiting for toy 2, which child 2 has, while child 2 is waiting for top 3, which child 3 has. When child 3 makes his last request, the toy he requests is held by child 1. Each of the three children is waiting for a toy held by another child and no one is playing, so all the three will start crying.
In the second example, at the beginning, child i is holding toy i for 1 ≤ i ≤ 4. Children 1 and 3 have completed their lovely sets. After they finish playing, toy 3 will be free while toy 1 will be taken by child 2 who has just completed his lovely set. After he finishes, toys 1 and 2 will be free and child 5 will take toy 1. Now:
* In the first query, child 5 will take toy 3 and after he finishes playing, child 4 can play.
* In the second query, child 5 will request toy 4 which is held by child 4. At the same time, child 4 is waiting for toy 1 which is now held by child 5. None of them can play and they will start crying.
Submitted Solution:
```
def poss():
x = [int(y) - 1 for y in input().split()]
child_holding_toy = held_toys[x[1]]
if child_holding_toy != -1:
depended[x[0]] = child_holding_toy
held_toys[x[1]] = x[0]
def trace(child_holding,var):
if child_holding == -1:
return 0
if child_holding==var:
return 1
m = trace(depended[child_holding],var)
if m != 0:
return 1 + m
return 0
entry = [int(x) for x in input().split()]
depended = [-1] * entry[0]
held_toys = [-1] * entry[1]
for i in range(entry[2]):
poss()
for i in range(entry[3]):
x = [int(y) - 1 for y in input().split()]
child_holding_toy = held_toys[x[1]]
l = depended[x[0]]
if child_holding_toy != -1:
depended[x[0]] = child_holding_toy
print(trace(child_holding_toy,x[0]))
depended[x[0]] = l
``` | instruction | 0 | 70,397 | 14 | 140,794 |
No | output | 1 | 70,397 | 14 | 140,795 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an airplane which has n rows from front to back. There will be m people boarding this airplane.
This airplane has an entrance at the very front and very back of the plane.
Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.
When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.
Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.
Input
The first line of input will contain two integers n, m (1 ≤ m ≤ n ≤ 1 000 000), the number of seats, and the number of passengers, respectively.
Output
Print a single number, the number of ways, modulo 109 + 7.
Example
Input
3 3
Output
128
Note
Here, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).
For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.
One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat. | instruction | 0 | 70,398 | 14 | 140,796 |
Tags: math, number theory
Correct Solution:
```
MOD = 10 ** 9 + 7
n, m = input().split(' ')
n = int(n)
m = int(m)
ans = pow(2 * (n + 1), m, MOD)
ans = (ans * (n + 1 - m)) % MOD
ans = (ans * pow(n + 1, MOD - 2, MOD)) % MOD
print(ans)
``` | output | 1 | 70,398 | 14 | 140,797 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an airplane which has n rows from front to back. There will be m people boarding this airplane.
This airplane has an entrance at the very front and very back of the plane.
Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.
When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.
Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.
Input
The first line of input will contain two integers n, m (1 ≤ m ≤ n ≤ 1 000 000), the number of seats, and the number of passengers, respectively.
Output
Print a single number, the number of ways, modulo 109 + 7.
Example
Input
3 3
Output
128
Note
Here, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).
For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.
One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat. | instruction | 0 | 70,399 | 14 | 140,798 |
Tags: math, number theory
Correct Solution:
```
mod = 1000000007
def power(a, p):
res = 1
while p > 0:
if p % 2 == 1:
res = (res * a) % mod
a = (a * a) % mod
p //= 2
return res
n, m = map(int, input().split())
n += 1
res = (power(n * 2, m - 1)) * (n - m) * 2
print((res % mod))
``` | output | 1 | 70,399 | 14 | 140,799 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is an airplane which has n rows from front to back. There will be m people boarding this airplane.
This airplane has an entrance at the very front and very back of the plane.
Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.
When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.
Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.
Input
The first line of input will contain two integers n, m (1 ≤ m ≤ n ≤ 1 000 000), the number of seats, and the number of passengers, respectively.
Output
Print a single number, the number of ways, modulo 109 + 7.
Example
Input
3 3
Output
128
Note
Here, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).
For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.
One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat. | instruction | 0 | 70,400 | 14 | 140,800 |
Tags: math, number theory
Correct Solution:
```
n,m=[int(i) for i in input().split()]
print(pow(2*n+2,m-1,1000000007)*2*(n+1-m)%1000000007)
``` | output | 1 | 70,400 | 14 | 140,801 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an airplane which has n rows from front to back. There will be m people boarding this airplane.
This airplane has an entrance at the very front and very back of the plane.
Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.
When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.
Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.
Input
The first line of input will contain two integers n, m (1 ≤ m ≤ n ≤ 1 000 000), the number of seats, and the number of passengers, respectively.
Output
Print a single number, the number of ways, modulo 109 + 7.
Example
Input
3 3
Output
128
Note
Here, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).
For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.
One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat.
Submitted Solution:
```
mod = 1000000007
def power(a, p):
res = 1
while p > 0:
if p % 2 == 1:
res = (res * a) % mod
a = (a * a) % mod
p //= 2
return res
n, m = map(int, input().split())
n += 1
res = (power(n * 2, m))*(n-m)/n
res = res % mod
print(int(res))
``` | instruction | 0 | 70,401 | 14 | 140,802 |
No | output | 1 | 70,401 | 14 | 140,803 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | instruction | 0 | 70,450 | 14 | 140,900 |
Tags: implementation, math
Correct Solution:
```
n, m = map(int, input().split())
p = 1
while m > 0:
if p > n:
p = 1
if p > m:
break
m -= p
p += 1
print(m)
``` | output | 1 | 70,450 | 14 | 140,901 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | instruction | 0 | 70,451 | 14 | 140,902 |
Tags: implementation, math
Correct Solution:
```
a,b=map(int,input().split())
i=1
while b>=i:
b-=i
if i<a:
i+=1
else:
i=1
print(b)
``` | output | 1 | 70,451 | 14 | 140,903 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | instruction | 0 | 70,452 | 14 | 140,904 |
Tags: implementation, math
Correct Solution:
```
n,m = map(int, input().split())
def summation(a):
return (a*(a+1)//2)
x=[]
for i in range(n):
x.append(summation(i+1))
m = m % x[-1]
if m==0:
print(0)
else:
for i in range(n):
if x[i] > m:
m -= x[i-1]
break
elif x[i] == m:
m = 0
break
print(m)
``` | output | 1 | 70,452 | 14 | 140,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | instruction | 0 | 70,453 | 14 | 140,906 |
Tags: implementation, math
Correct Solution:
```
n,m=map(int,input().split())
count=0
i=1
while count!=1:
if i>n:
i=1
if m<i:
print(m)
count=1
break
else:
m=m-i
i+=1
``` | output | 1 | 70,453 | 14 | 140,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | instruction | 0 | 70,454 | 14 | 140,908 |
Tags: implementation, math
Correct Solution:
```
n,m=map(int,input().split())
i=0
while((m-i)>=0):
for i in range(1,n+1):
if m-i>=0:
m=m-i
else:
break
if(i==n):
i=1
break
print(m)
``` | output | 1 | 70,454 | 14 | 140,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | instruction | 0 | 70,455 | 14 | 140,910 |
Tags: implementation, math
Correct Solution:
```
# import os
n,m = map(int,input().split())
r = 0
i = 1
while m >= i:
m -= i
i += 1
if i == n+1:
i = 1
print(m)
``` | output | 1 | 70,455 | 14 | 140,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | instruction | 0 | 70,456 | 14 | 140,912 |
Tags: implementation, math
Correct Solution:
```
x = input().split(' ')
n,m = int(x[0]),int(x[1])
i =1
while i<=n:
if m<i:
break
m-=i
if i==n:
i=1
else:
i+=1
print(m)
``` | output | 1 | 70,456 | 14 | 140,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | instruction | 0 | 70,457 | 14 | 140,914 |
Tags: implementation, math
Correct Solution:
```
n, k = map(int, input().split())
t = 0
while k > 0 and t != 1:
for i in range(n):
if k >= i + 1:
k -= (i + 1)
else:
t = 1
break
print(k)
``` | output | 1 | 70,457 | 14 | 140,915 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
Submitted Solution:
```
import sys
import math
#to read string
get_string = lambda: sys.stdin.readline().strip()
#to read list of integers
get_list = lambda: list( map(int,sys.stdin.readline().strip().split()) )
#to read non spaced string and elements are integers to list of int
get_intList_from_str = lambda: list(map(int,list(sys.stdin.readline().strip())))
#to read non spaced string and elements are character to list of character
get_strList_from_str = lambda: list(sys.stdin.readline().strip())
#to read integers
get_int = lambda: int(sys.stdin.readline().strip())
#to print faster
pt = lambda x: sys.stdout.write(str(x))
#--------------------------------WhiteHat010--------------------------------------#
n,m = get_list()
counter = 1
while m > 0:
if m < counter:
break
else:
m -= counter
if counter == n:
counter = 1
else:
counter += 1
print(m)
``` | instruction | 0 | 70,458 | 14 | 140,916 |
Yes | output | 1 | 70,458 | 14 | 140,917 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
Submitted Solution:
```
n,m=map(int,input().split())
i=1
while(m>=i):
m-=i
i+=1
if(i==n+1):
i=1
print(m)
``` | instruction | 0 | 70,459 | 14 | 140,918 |
Yes | output | 1 | 70,459 | 14 | 140,919 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
Submitted Solution:
```
from sys import stdin,stdout
n,m=map(int,stdin.readline().split())
s=int((n*(n+1))/2)
r=m%s
k=r
#stdout.write(r)
i=1
while(True):
if((r-i)<0):
stdout.write(str(r))
break
else:
r=r-i
i=i+1
``` | instruction | 0 | 70,460 | 14 | 140,920 |
Yes | output | 1 | 70,460 | 14 | 140,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
Submitted Solution:
```
info = input().split()
walrusnum = int(info[0])
chipnum = int(info[1])
done = False
while not done:
for i in range(walrusnum):
if chipnum < 0 or chipnum -(i + 1) < 0:
done = True
break
chipnum -= i + 1
print(chipnum)
``` | instruction | 0 | 70,461 | 14 | 140,922 |
Yes | output | 1 | 70,461 | 14 | 140,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
Submitted Solution:
```
n,m=map(int,input().split())
p=m%(n*(n+1)/2)
for i in range(1,n+1):
if p>=i:
p=p-i
else:
print(p)
exit()
``` | instruction | 0 | 70,462 | 14 | 140,924 |
No | output | 1 | 70,462 | 14 | 140,925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
Submitted Solution:
```
if __name__ == '__main__':
n,m = map(int, input().split())
i = 1
while i <= n:
if m == 0:
print(str(0))
break
if i == n:
m -= i
i = 1
if m < i:
print(str(m))
break
else:
m -= i
i += 1
``` | instruction | 0 | 70,463 | 14 | 140,926 |
No | output | 1 | 70,463 | 14 | 140,927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
Submitted Solution:
```
m,n=input().split(' ')
m,n=int(m),int(n)
res=n%m
l=[t*(t+1)//2 for t in range(0,1000)]
if res in l:
print('0')
else:
for j in range(0,len(l)):
if(res-l[j]>0):
pass
else:
print(res-l[j-1])
break
``` | instruction | 0 | 70,464 | 14 | 140,928 |
No | output | 1 | 70,464 | 14 | 140,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
Submitted Solution:
```
n, m = map(int, input().split())
a = 0
while m >= a:
for i in range(1,n + 1):
a = i
m -= i
if a > m:
a = 1
break
print(m)
``` | instruction | 0 | 70,465 | 14 | 140,930 |
No | output | 1 | 70,465 | 14 | 140,931 |
Provide a correct Python 3 solution for this coding contest problem.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2 | instruction | 0 | 70,712 | 14 | 141,424 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
N=int(input())
ANS=0
for i in range(N):
if input().strip()=="E869120":
ANS+=1
print(ANS)
``` | output | 1 | 70,712 | 14 | 141,425 |
Provide a correct Python 3 solution for this coding contest problem.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2 | instruction | 0 | 70,713 | 14 | 141,426 |
"Correct Solution:
```
N = int(input())
S = [input() for _ in range(N)]
print(S.count('E869120'))
``` | output | 1 | 70,713 | 14 | 141,427 |
Provide a correct Python 3 solution for this coding contest problem.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2 | instruction | 0 | 70,714 | 14 | 141,428 |
"Correct Solution:
```
from itertools import *
from bisect import *
from math import *
from collections import *
from heapq import *
from random import *
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
def MF(): return map(float, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LF(): return list(map(float, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
dij = [(1, 0), (0, 1), (-1, 0), (0, -1)]
def main():
n=II()
ss=[input() for _ in range(n)]
cnt=Counter(ss)
print(cnt["E869120"])
main()
``` | output | 1 | 70,714 | 14 | 141,429 |
Provide a correct Python 3 solution for this coding contest problem.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2 | instruction | 0 | 70,715 | 14 | 141,430 |
"Correct Solution:
```
nin = []
for i in range(int(input())):
s = input()
nin.append(s)
print(nin.count("E869120"))
``` | output | 1 | 70,715 | 14 | 141,431 |
Provide a correct Python 3 solution for this coding contest problem.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2 | instruction | 0 | 70,716 | 14 | 141,432 |
"Correct Solution:
```
n = int(input())
s = [input() for i in range(n)]
print(s.count("E869120"))
``` | output | 1 | 70,716 | 14 | 141,433 |
Provide a correct Python 3 solution for this coding contest problem.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2 | instruction | 0 | 70,717 | 14 | 141,434 |
"Correct Solution:
```
def num():
return int(input())
def nums():
return list(map(int,input().split()))
"""
A,B = nums()
P,Q,R = nums()
first_distance = P * B
pre_runned = (B - A) * Q
time = B + (first_distance - pre_runned) / (R + Q)
print(time)
"""
"""
N = num()
randoms = nums()
ans = 0
for i in range(N):
today = randoms[i]
if i == 0:
continue
if today > randoms[i-1]:
ans += 1
print(ans)
"""
N = num()
members = []
for i in range(N):
members.append(input())
ans = members.count("E869120")
print(ans)
``` | output | 1 | 70,717 | 14 | 141,435 |
Provide a correct Python 3 solution for this coding contest problem.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2 | instruction | 0 | 70,718 | 14 | 141,436 |
"Correct Solution:
```
a=0
for i in range(int(input())):
if input()=="E869120":
a+=1
print(a)
``` | output | 1 | 70,718 | 14 | 141,437 |
Provide a correct Python 3 solution for this coding contest problem.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2 | instruction | 0 | 70,719 | 14 | 141,438 |
"Correct Solution:
```
n = int(input())
l = [input() for i in range(n)]
print(l.count('E869120'))
``` | output | 1 | 70,719 | 14 | 141,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | instruction | 0 | 70,882 | 14 | 141,764 |
Tags: constructive algorithms, graphs, greedy, sortings
Correct Solution:
```
from collections import defaultdict
import os,io
from sys import stdout
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m = list(map(int,input().split()))
adj = defaultdict(set)
l = []
for _ in range(m):
u, v = list(map(int,input().split()))
l.append((u,v))
t = list(map(int,input().split()))
c = sorted([(index+1, value) for index, value in enumerate(t)], key=lambda x: x[1])
def sol():
for (u,v) in l:
adj[u].add(t[v-1])
adj[v].add(t[u-1])
if t[v-1] == t[u-1]:
print(-1)
return
for blog, topic in c:
minimumTopic = 1
while minimumTopic in adj[blog]:
minimumTopic += 1
if topic != minimumTopic:
print(-1)
break
else:
stdout.write(' '.join(str(i[0]) for i in c))
sol()
``` | output | 1 | 70,882 | 14 | 141,765 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | instruction | 0 | 70,883 | 14 | 141,766 |
Tags: constructive algorithms, graphs, greedy, sortings
Correct Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# 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)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa=ifa[::-1]
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def lowbit(n):
return n&-n
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
'''
class SMT:
def __init__(self,arr):
self.n=len(arr)-1
self.arr=[0]*(self.n<<2)
self.lazy=[0]*(self.n<<2)
def Build(l,r,rt):
if l==r:
self.arr[rt]=arr[l]
return
m=(l+r)>>1
Build(l,m,rt<<1)
Build(m+1,r,rt<<1|1)
self.pushup(rt)
Build(1,self.n,1)
def pushup(self,rt):
self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1]
def pushdown(self,rt,ln,rn):#lr,rn表区间数字数
if self.lazy[rt]:
self.lazy[rt<<1]+=self.lazy[rt]
self.lazy[rt<<1|1]+=self.lazy[rt]
self.arr[rt<<1]+=self.lazy[rt]*ln
self.arr[rt<<1|1]+=self.lazy[rt]*rn
self.lazy[rt]=0
def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间
if r==None: r=self.n
if L<=l and r<=R:
self.arr[rt]+=c*(r-l+1)
self.lazy[rt]+=c
return
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
if L<=m: self.update(L,R,c,l,m,rt<<1)
if R>m: self.update(L,R,c,m+1,r,rt<<1|1)
self.pushup(rt)
def query(self,L,R,l=1,r=None,rt=1):
if r==None: r=self.n
#print(L,R,l,r,rt)
if L<=l and R>=r:
return self.arr[rt]
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
ans=0
if L<=m: ans+=self.query(L,R,l,m,rt<<1)
if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1)
return ans
'''
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]<self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
#print(flag)
return flag
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
for v in graph[u]:
if v not in d or d[v]>d[u]+graph[u][v]:
d[v]=d[u]+graph[u][v]
heappush(heap,(d[v],v))
return d
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
@bootstrap
def gdfs(r,p):
if len(g[r])==1 and p!=-1:
yield None
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
t=1
for i in range(t):
n,m=RL()
g=[[] for i in range(n+1)]
for i in range(m):
a,b=RL()
g[a].append(b)
g[b].append(a)
t=RLL()
res=sorted((t[i],i+1) for i in range(n))
c=[1]*(n+1)
p=[]
for order,i in res:
if order!=c[i]:
print(-1)
exit()
for v in g[i]:
if c[v]==order:
c[v]+=1
p.append(i)
print(*p)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
``` | output | 1 | 70,883 | 14 | 141,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | instruction | 0 | 70,884 | 14 | 141,768 |
Tags: constructive algorithms, graphs, greedy, sortings
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
n,m = list(map(int, input().split()))
nodes = [[] for i in range(n)]
small_all = [0 for i in range(n)]
for i in range(m):
a,b = list(map(int, input().split()))
nodes[a-1].append(b-1)
nodes[b-1].append(a-1)
I=lambda:list(map(int,input().split()))
col=I()
colors=list(range(n))
colors.sort(key=lambda x:col[x])
#print(colors)
#print(col)
assigned = [0] * n
order = []
for c in colors:
#check the children of desired node.
tt = col[c]
if small_all[c] + 1!= tt:
print(-1)
exit()
assigned[c] = tt
for child in nodes[c]:
if small_all[child] == tt - 1:
small_all[child] += 1
order.append(c+1)
order = [str(x) for x in order]
print(' '.join(order))
``` | output | 1 | 70,884 | 14 | 141,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | instruction | 0 | 70,885 | 14 | 141,770 |
Tags: constructive algorithms, graphs, greedy, sortings
Correct Solution:
```
import sys
from collections import deque
input = sys.stdin.buffer.readline
print = sys.stdout.write
n, m = map(int, input().split())
e = [ [] for _ in range(n+1) ]
for _ in range(m):
a, b = map(int, input().split())
e[a].append(b); e[b].append(a)
tg = [0] + list(map(int, input().split()))
te = [ [] for _ in range(n+1) ]
incc = [0]*(n+1)
for u in range(1, n+1):
for v in e[u]:
if tg[v] > tg[u]:
te[u].append(v)
incc[v] += 1
res = []
q = deque([ u for u in range(1, n+1) if incc[u] == 0 ])
while q:
u = q.popleft()
res.append(u)
for v in te[u]:
incc[v] -= 1
if incc[v] == 0: q.append(v)
if len(res) != n: print('-1\n'); exit()
topic = [0]*(n+1)
for u in res:
cc, utp = set(), tg[u]
for v in e[u]:
vtp = topic[v]
if vtp != 0 and vtp <= utp: cc.add(vtp)
if not (len(cc) == utp-1 and utp not in cc):
print('-1\n'); exit()
topic[u] = utp
print(' '.join(map(str, res)) + '\n')
``` | output | 1 | 70,885 | 14 | 141,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | instruction | 0 | 70,886 | 14 | 141,772 |
Tags: constructive algorithms, graphs, greedy, sortings
Correct Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m = map(int, input().split())
adj = [[] for i in range(n+1)]
for i in range(m):
u, v = map(int, input().split())
adj[u].append(v)
adj[v].append(u)
topics = [0]+list(map(int, input().split()))
bckt = [10**9]*(n+1)
ans = []
q = []
for i in range(1, n+1):
q.append((i, topics[i]))
q.sort(key=lambda x: x[1], reverse=True)
ok = True
while q:
e, t = q.pop()
ct = 1
s = set()
for j in adj[e]:
s.add(bckt[j])
while ct in s:
ct += 1
if t == ct:
bckt[e] = t
ans.append(e)
else:
ok = False
break
if ok:
print(*ans)
else:
print(-1)
``` | output | 1 | 70,886 | 14 | 141,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | instruction | 0 | 70,887 | 14 | 141,774 |
Tags: constructive algorithms, graphs, greedy, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
n,m=map(int,input().split())
d=[[] for j in range((n+1))]
f=[]
for j in range(m):
a,c=map(int,input().split())
f.append([a,c])
b=list(map(int,input().split()))
for j in f:
a,c=j[0],j[1]
d[a].append(b[c-1])
d[c].append(b[a-1])
h=[0]*(n+1)
j=1
while(j<=n):
d[j]=list(set(d[j]))
e=dict()
for i in d[j]:
e[i]=1
q=1
while(q<=b[j-1]):
if q not in e.keys():
h[j]=q
break
q+=1
j+=1
a=[]
for j in range(n):
a.append([b[j],j+1])
a.sort()
j=0
p=1
f=[]
g=0
while(j<n):
x,y=a[j][0],a[j][1]
if h[y]==x:
f.append(y)
else:
g=1
break
j+=1
if g==1:
print(-1)
else:
print(*f)
``` | output | 1 | 70,887 | 14 | 141,775 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | instruction | 0 | 70,888 | 14 | 141,776 |
Tags: constructive algorithms, graphs, greedy, sortings
Correct Solution:
```
import sys
readline = sys.stdin.buffer.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
def solve():
n, m = nm()
G = [list() for _ in range(n)]
for _ in range(m):
u, v = nm()
u -= 1; v -= 1
G[u].append(v)
G[v].append(u)
t = nl()
c = [1]*n
g = sorted(list(range(n)), key = lambda x: t[x])
for x in g:
if c[x] != t[x]:
print(-1)
return
c[x] = t[x]
for v in G[x]:
if c[v] == t[x]:
c[v] += 1
g = [x+1 for x in g]
print(*g)
return
solve()
#
# T = ni()
# for _ in range(T):
# solve()
``` | output | 1 | 70,888 | 14 | 141,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2. | instruction | 0 | 70,889 | 14 | 141,778 |
Tags: constructive algorithms, graphs, greedy, sortings
Correct Solution:
```
import io
import os
def main():
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, m = map(int, input().split())
dct = {x: [] for x in range(1, n + 1)}
for _ in range(m):
a, b = map(int, input().split())
dct[a].append(b)
dct[b].append(a)
mini = [-1 for _ in range(n)]
dct1 = {x: [] for x in range(1, n + 1)}
arr = list(map(int, input().split()))
for i in range(n):
dct1[arr[i]].append(i + 1)
ans = []
for x in range(1, max(arr) + 1):
fl = 1
for y in dct1[x]:
fl = 0
se = set()
for ne in dct[y]:
if mini[ne - 1] != -1:
se.add(mini[ne - 1])
if mini[ne - 1] == x:
fl = 1
break
if len(se) != x - 1 or fl:
fl = 1
break
else:
ans.append(y)
mini[y - 1] = x
if fl:
print(-1)
break
if not fl:
for kk in ans:
print(kk, end=' ')
if __name__ == '__main__':
main()
``` | output | 1 | 70,889 | 14 | 141,779 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2.
Submitted Solution:
```
"""
*Satwik_Tiwari*
-----------
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
import heapq
from math import *
from collections import deque
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned
#==============================================================================================
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
#some shortcuts
mod = 1000000007
# def inp(): return sys.stdin.readline().strip() #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
ans = 1
while(b>0):
if(b%2==1):
ans*=a
a*=a
b//=2
return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) : # Check Prime Number or not
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
def solve():
n,m = sep()
g = graph(n)
for i in range(0,m):
u,v = sep()
g[u].append(v)
g[v].append(u)
topic = lis()
new = []
for i in range(1,n+1):
new.append([topic[i-1],i])
new.sort(key= lambda x:x[0])
# print(new)
# print(new)
temp = []
pos = [0]*(n+1)
for i in range(0,len(new)):
temp.append(new[i][1])
pos[temp[i]] = i+1
# print(temp,'temp')
# print(pos,'pos')
# print(temp)
flag = True
chck = [0]*(n+1)
l=0
for i in temp:
f = False
cnt = 0
for j in g[i]:
# print(i,j)
if(pos[j] > pos[i]):
continue
# print(i,j)
# print(topic)
if(topic[j-1] < topic[i-1]):
if(chck[topic[j-1]] <= l):
cnt+=1
chck[topic[j-1]] = l+1
else:
f = True
break
if(f):
# print(i,'i')
out(-1)
nextline()
flag = False
break
elif(cnt !=topic[i-1]-1):
# print(i)
out(-1)
nextline()
flag = False
break
l+=1
if(flag):
printlist(temp)
testcase(1)
# testcase(int(inp()))
``` | instruction | 0 | 70,890 | 14 | 141,780 |
Yes | output | 1 | 70,890 | 14 | 141,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2.
Submitted Solution:
```
import sys
import os,io
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m = map(int, input().split())
graph = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
t = list(map(int, input().split()))
for node in range(n):
topic = t[node]
if topic > len(graph[node])+1:
print(-1)
exit(0)
seen = [False]*topic
seen[0] = True
for i in graph[node]:
if t[i]==topic:
print(-1)
exit(0)
if t[i]<topic:
seen[t[i]] = True
if all(seen):
continue
print(-1)
exit(0)
t = [(i+1, j) for i, j in enumerate(t)]
t.sort(key=lambda x:x[1])
sys.stdout.write(' '.join(str(i) for i, j in t))
print()
``` | instruction | 0 | 70,891 | 14 | 141,782 |
Yes | output | 1 | 70,891 | 14 | 141,783 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2.
Submitted Solution:
```
# p
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")
n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
g[a - 1].append(b - 1)
g[b - 1].append(a - 1)
t = list(map(int, input().split()))
from collections import defaultdict
d = defaultdict(set)
for i in range(n):
for j in g[i]:
d[i].add(t[j])
flag = 1
import bisect
for i in range(n):
if t[i] in d[i]:
print(-1)
sys.exit()
temp = sorted(list(d[i]))
if bisect.bisect_right(temp, t[i]) == t[i] - 1:
pass
else:
flag = 0
break
# print(d)
if not flag:
print(-1)
sys.exit()
t = [(t[i], i) for i in range(n)]
t.sort()
ans = []
for i in t:
ans.append(i[1] + 1)
print(*ans)
``` | instruction | 0 | 70,892 | 14 | 141,784 |
Yes | output | 1 | 70,892 | 14 | 141,785 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2.
Submitted Solution:
```
import sys
import math
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
input = sys.stdin.readline
N, M = map(int, input().split(' '))
A = [[] for i in range(N)]
for i in range(M):
x, y = map(int, input().split(' '))
x -= 1
y -= 1
A[x].append(y)
A[y].append(x)
topics = list(map(int, input().split(' ')))
blogs_by_topic = {}
for i in range(N):
topic = topics[i] - 1
if topic not in blogs_by_topic:
blogs_by_topic[topic] = [i]
else:
blogs_by_topic[topic].append(i)
T = [None for i in range(N)]
ans = []
for t in range(N):
blogs = blogs_by_topic.get(t, None)
if not blogs:
continue
for blog in blogs:
T[blog] = t
other_topics = set()
for adj in A[blog]:
if T[adj] is not None:
other_topics.add(T[adj])
if (other_topics and max(other_topics) >= t) or len(other_topics) != t:
print(-1)
exit(0)
ans.append(blog + 1)
print(' '.join(map(str, ans)))
``` | instruction | 0 | 70,893 | 14 | 141,786 |
Yes | output | 1 | 70,893 | 14 | 141,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2.
Submitted Solution:
```
def get(x):
return int(x) - 1
def giv(x):
return str(x + 1)
n, m = map(int, input().split())
arr = list([] for i in range(n))
for i in range(m):
a, b = map(int, input().split())
arr[a - 1].append(b - 1)
arr[b - 1].append(a - 1)
t = list(map(get, input().split()))
ans = []
mis = False
for i in range(max(t)+1):
#print('тема:', i)
jran = t.count(i)
prev = 0
for j in range(jran):
ind = t.index(i, prev)
#print('блог:', ind)
nei = []
for k in range(len(arr[ind])):
if arr[ind][k] in ans:
#print('нашел соседа:', 'блог:', arr[ind][k], 'с темой:', t[arr[ind][k]])
nei.append(t[arr[ind][k]])
#print('соседи:', nei)
bef = list(z for z in range(i))
#print('до этой темы:', bef)
if (set(bef).issubset(set(nei))) and (i not in nei):
ans.append(ind)
#print('выбираем:', ind)
else:
mis = True
#print('ошибка')
break
if mis:
print(-1)
else:
print (" ".join(map(giv, ans)))
``` | instruction | 0 | 70,894 | 14 | 141,788 |
No | output | 1 | 70,894 | 14 | 141,789 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2.
Submitted Solution:
```
from collections import defaultdict
n,m = map(int,input().split())
adj_list = defaultdict(list)
for i in range(m):
u,v = map(int,input().split())
adj_list[u].append(v)
adj_list[v].append(u)
color = list(map(int,input().split()))
blog_no = list(range(1,n+1))
color = list(zip(blog_no,color)) ## [ blog_no , topic_assigned/color ]
violate = False
for i in range(1,n+1):
color_i = color[i-1][1]
small_color = set()
for v in adj_list[i]:
if color[v-1][1]==color_i:
#print(f'same color {i,v}')
violate = True
print(-1)
exit(0)
if color[v-1][1]<color_i:
small_color.add(v)
if len(small_color)==(color_i-1):
violate = False
else:
violate = True
#print("small")
print(-1)
exit(0)
small_color.clear()
color.sort(key=lambda x: x[1])
#print(color)
print(" ".join([str(color[i][0]) for i in range(n)]))
``` | instruction | 0 | 70,895 | 14 | 141,790 |
No | output | 1 | 70,895 | 14 | 141,791 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2.
Submitted Solution:
```
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
def bfs(nodes, src):
from collections import deque
N = len(nodes)
que = deque()
dist = [INF] * N
mn = [0] * N
se = [set([0]) for i in range(N)]
for u in src:
dist[u] = A[u]
que.append(u)
for v in nodes[u]:
if mn[v] == A[u]:
a = A[u]
while a in se[v]:
a += 1
mn[v] = a
res = []
while que:
u = que.popleft()
res.append(u+1)
for v in nodes[u]:
if dist[v] != INF:
continue
if mn[v] == A[u]+1:
dist[v] = dist[u] + 1
que.append(v)
for vv in nodes[v]:
if mn[vv] == A[v]:
a = A[v]
while a in se[vv]:
a += 1
mn[vv] = a
return res
N, M = MAP()
edges = []
for i in range(M):
a, b = MAP()
a -= 1; b -= 1
edges.append((a, b))
A = [a-1 for a in LIST()]
nodes = [[] for i in range(N)]
for a, b in edges:
if A[a] == A[b]:
print(-1)
exit()
nodes[a].append(b)
nodes[b].append(a)
src = []
for u in range(N):
if A[u] == 0:
src.append(u)
res = bfs(nodes, src)
if len(res) < N:
print(-1)
else:
print(*res)
``` | instruction | 0 | 70,896 | 14 | 141,792 |
No | output | 1 | 70,896 | 14 | 141,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers can notice that they are split just for more contribution. Set of blogs and bidirectional references between some pairs of them is called blogs network.
There are n different topics, numbered from 1 to n sorted by Johnny's knowledge. The structure of the blogs network is already prepared. Now Johnny has to write the blogs in some order. He is lazy, so each time before writing a blog, he looks at it's already written neighbors (the blogs referenced to current one) and chooses the topic with the smallest number which is not covered by neighbors. It's easy to see that this strategy will always allow him to choose a topic because there are at most n - 1 neighbors.
For example, if already written neighbors of the current blog have topics number 1, 3, 1, 5, and 2, Johnny will choose the topic number 4 for the current blog, because topics number 1, 2 and 3 are already covered by neighbors and topic number 4 isn't covered.
As a good friend, you have done some research and predicted the best topic for each blog. Can you tell Johnny, in which order he has to write the blogs, so that his strategy produces the topic assignment chosen by you?
Input
The first line contains two integers n (1 ≤ n ≤ 5 ⋅ 10^5) and m (0 ≤ m ≤ 5 ⋅ 10^5) — the number of blogs and references, respectively.
Each of the following m lines contains two integers a and b (a ≠ b; 1 ≤ a, b ≤ n), which mean that there is a reference between blogs a and b. It's guaranteed that the graph doesn't contain multiple edges.
The last line contains n integers t_1, t_2, …, t_n, i-th of them denotes desired topic number of the i-th blog (1 ≤ t_i ≤ n).
Output
If the solution does not exist, then write -1. Otherwise, output n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), which describe the numbers of blogs in order which Johnny should write them. If there are multiple answers, print any.
Examples
Input
3 3
1 2
2 3
3 1
2 1 3
Output
2 1 3
Input
3 3
1 2
2 3
3 1
1 1 1
Output
-1
Input
5 3
1 2
2 3
4 5
2 1 2 2 1
Output
2 5 1 3 4
Note
In the first example, Johnny starts with writing blog number 2, there are no already written neighbors yet, so it receives the first topic. Later he writes blog number 1, it has reference to the already written second blog, so it receives the second topic. In the end, he writes blog number 3, it has references to blogs number 1 and 2 so it receives the third topic.
Second example: There does not exist any permutation fulfilling given conditions.
Third example: First Johnny writes blog 2, it receives the topic 1. Then he writes blog 5, it receives the topic 1 too because it doesn't have reference to single already written blog 2. Then he writes blog number 1, it has reference to blog number 2 with topic 1, so it receives the topic 2. Then he writes blog number 3 which has reference to blog 2, so it receives the topic 2. Then he ends with writing blog number 4 which has reference to blog 5 and receives the topic 2.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
class Graph(object):
"""docstring for Graph"""
def __init__(self,n,d): # Number of nodes and d is True if directed
self.n = n
self.graph = [[] for i in range(n)]
self.parent = [-1 for i in range(n)]
self.directed = d
def addEdge(self,x,y):
self.graph[x].append(y)
if not self.directed:
self.graph[y].append(x)
def bfs(self, root): # NORMAL BFS
self.parent = [-1 for i in range(self.n)]
queue = [root]
queue = deque(queue)
vis = [0]*self.n
while len(queue)!=0:
element = queue.popleft()
vis[element] = 1
for i in self.graph[element]:
if vis[i]==0:
queue.append(i)
self.parent[i] = element
def dfs(self, root, ans): # Iterative DFS
stack=[root]
vis=[0]*self.n
stack2=[]
while len(stack)!=0: # INITIAL TRAVERSAL
element = stack.pop()
if vis[element]:
continue
vis[element] = 1
stack2.append(element)
for i in self.graph[element]:
if vis[i]==0:
self.parent[i] = element
stack.append(i)
while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question
element = stack2.pop()
m = 0
for i in self.graph[element]:
if i!=self.parent[element]:
m += ans[i]
ans[element] = m
return ans
def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes
self.bfs(source)
path = [dest]
while self.parent[path[-1]]!=-1:
path.append(parent[path[-1]])
return path[::-1]
def ifcycle(self):
self.bfs(0)
queue = [0]
vis = [0]*n
queue = deque(queue)
while len(queue)!=0:
element = queue.popleft()
vis[element] = 1
for i in graph[element]:
if vis[i]==1 and i!=parent[element]:
return True
if vis[i]==0:
queue.append(i)
vis[i] = 1
return False
def reroot(self, root, ans):
stack = [root]
vis = [0]*n
while len(stack)!=0:
e = stack[-1]
if vis[e]:
stack.pop()
# Reverse_The_Change()
continue
vis[e] = 1
for i in graph[e]:
if not vis[e]:
stack.append(i)
if self.parent[e]==-1:
continue
# Change_The_Answers()
def check(self, node, blog):
done = {}
for i in self.graph[node]:
if i in b and b[i]<blog:
done[i] = 1
if i in b and b[i]==blog:
return False
if len(done)==blog-1:
return True
return False
n,m = map(int,input().split())
g = Graph(n+1,False)
for i in range(m):
a,b = map(int,input().split())
g.addEdge(a,b)
t = list(map(int,input().split()))
l = {}
for i in range(1,n+1):
if t[i-1] not in l:
l[t[i-1]] = [i]
else:
l[t[i-1]].append(i)
if n==100 and m==400:
print (t)
exit()
d = {}
b = {}
ans = []
i = 1
flag = 0
# print (g.graph)
# print (l)
while len(d)!=n:
for j in l[i]:
if not g.check(j,i):
flag = 1
break
else:
d[j] = 1
b[j] = i
ans.append(j)
if flag:
break
i += 1
if flag:
print (-1)
exit()
print (*ans)
``` | instruction | 0 | 70,897 | 14 | 141,794 |
No | output | 1 | 70,897 | 14 | 141,795 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.
There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero).
These atoms also form a peculiar one-way bond. For each i, (1 ≤ i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom.
Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 ≤ i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!
note: You must first change exactly K bonds before you can start exciting atoms.
Input
The first line contains two integers N K (4 ≤ N ≤ 10^5, 0 ≤ K < N), the number of atoms, and the number of bonds that must be changed.
The second line contains N integers A_i (1 ≤ A_i ≤ 10^6), which denotes the energy given by atom i when on excited state.
The third line contains N integers D_i (1 ≤ D_i ≤ 10^6), which denotes the energy needed to excite atom i.
Output
A line with an integer that denotes the maximum number of energy that Mr. Chanek can get.
Example
Input
6 1
5 6 7 8 10 2
3 5 6 7 1 10
Output
35
Note
An optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35.
Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal. | instruction | 0 | 70,913 | 14 | 141,826 |
Tags: greedy, implementation
Correct Solution:
```
import heapq
n,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
s=sum(a)
pre=[0]
j=0
while(j<n):
pre.append(a[j]+pre[-1])
j+=1
ab=[]
af=[]
af1=[]
j=n-1
while(j>=0):
heapq.heappush(af,-(s-pre[j]-b[j]))
af1.append(-af[0])
j+=-1
af1.reverse()
if k==0:
j=0
ans=0
while(j<n):
ans=max(ans,s-pre[j]-b[j])
j+=1
print(ans)
elif k==1:
j=0
m=float("inf")
ans=0
while (j < (n - 1)):
m=min(m,b[j])
if j<(n-2):
ans = max(ans, max(0,pre[j + 1] - m) + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1],s-b[0]-a[j+1])
else:
ans = max(ans, pre[j + 1] - m + max(0, af1[j + 1]), s - pre[j] - b[j] - a[j + 1])
j += 1
j=0
while(j<(n-1)):
ans=max(ans,s-a[-1]-b[j]+max(0,a[-1]-b[-1]))
j+=1
print(ans)
else:
j=0
ans=0
while(j<(n-1)):
ans=max(ans,s-b[j])
j+=1
ans=max(ans,a[-1]-b[-1])
print(ans)
``` | output | 1 | 70,913 | 14 | 141,827 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.
There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero).
These atoms also form a peculiar one-way bond. For each i, (1 ≤ i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom.
Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 ≤ i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!
note: You must first change exactly K bonds before you can start exciting atoms.
Input
The first line contains two integers N K (4 ≤ N ≤ 10^5, 0 ≤ K < N), the number of atoms, and the number of bonds that must be changed.
The second line contains N integers A_i (1 ≤ A_i ≤ 10^6), which denotes the energy given by atom i when on excited state.
The third line contains N integers D_i (1 ≤ D_i ≤ 10^6), which denotes the energy needed to excite atom i.
Output
A line with an integer that denotes the maximum number of energy that Mr. Chanek can get.
Example
Input
6 1
5 6 7 8 10 2
3 5 6 7 1 10
Output
35
Note
An optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35.
Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal. | instruction | 0 | 70,914 | 14 | 141,828 |
Tags: greedy, implementation
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# 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)
input = lambda: sys.stdin.readline()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# sys.setrecursionlimit(100000)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow,gcd,log
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
# from functools import reduce
# from functools import lru_cache
##################
## Ugly Problem ##
##################
n, k = map(int, input().split())
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k == 0:
best = 0
curr = sum(a)
for i in range(n):
best = max(best, curr - d[i])
curr -= a[i]
print(best)
elif k == 1:
best = sum(a[:-1]) - min(d[:-1])
other = sum(a)
other -= sorted(d)[0]
other -= sorted(d)[1]
curr = sum(a)
for i in range(n):
if i:
best = max(best, curr - d[i])
curr -= a[i]
o2 = sum(a) - min(a[1:]) - d[0]
print(max((best,other,0, o2)))
else:
print(max((sum(a) - min(d[:-1]),0,a[-1] - d[-1])))
``` | output | 1 | 70,914 | 14 | 141,829 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.
There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero).
These atoms also form a peculiar one-way bond. For each i, (1 ≤ i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom.
Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 ≤ i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!
note: You must first change exactly K bonds before you can start exciting atoms.
Input
The first line contains two integers N K (4 ≤ N ≤ 10^5, 0 ≤ K < N), the number of atoms, and the number of bonds that must be changed.
The second line contains N integers A_i (1 ≤ A_i ≤ 10^6), which denotes the energy given by atom i when on excited state.
The third line contains N integers D_i (1 ≤ D_i ≤ 10^6), which denotes the energy needed to excite atom i.
Output
A line with an integer that denotes the maximum number of energy that Mr. Chanek can get.
Example
Input
6 1
5 6 7 8 10 2
3 5 6 7 1 10
Output
35
Note
An optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35.
Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal. | instruction | 0 | 70,915 | 14 | 141,830 |
Tags: greedy, implementation
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
d = list(map(int, input().split()))
if k >= 2:
m = min(d[: -1])
print(max(sum(a) - m, a[-1] - d[-1], 0))
elif k == 0:
rightans = [0] * n
cursum = 0
ans = 0
for i in range(n - 1, -1, -1):
cursum += a[i]
rightans[i] = max(cursum - d[i], 0)
print(max(rightans))
else:
leftd = int(1e9)
leftsum = 0
rightans = [0] * n
cursum = 0
ans = 0
for i in range(n - 1, -1, -1):
cursum += a[i]
rightans[i] = max(cursum - d[i], 0)
for i in range(n - 1, 0, -1):
rightans[i - 1] = max(rightans[i - 1], rightans[i])
for i in range(n - 1):
leftd = min(leftd, d[i])
leftsum += a[i]
curans = max(leftsum - leftd, 0) + rightans[i + 1]
ans = max(ans, curans)
cursum = 0
rightmin = int(1e9)
for i in range(n - 1, -1, -1):
cursum += a[i]
ans = max(ans, cursum - rightmin - d[i])
rightmin = min(rightmin, a[i])
print(ans)
``` | output | 1 | 70,915 | 14 | 141,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it.
There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_i energy. When atom i is excited, it will give A_i energy. You can excite any number of atoms (including zero).
These atoms also form a peculiar one-way bond. For each i, (1 ≤ i < N), if atom i is excited, atom E_i will also be excited at no cost. Initially, E_i = i+1. Note that atom N cannot form a bond to any atom.
Mr. Chanek must change exactly K bonds. Exactly K times, Mr. Chanek chooses an atom i, (1 ≤ i < N) and changes E_i to a different value other than i and the current E_i. Note that an atom's bond can remain unchanged or changed more than once. Help Mr. Chanek determine the maximum energy that he can achieve!
note: You must first change exactly K bonds before you can start exciting atoms.
Input
The first line contains two integers N K (4 ≤ N ≤ 10^5, 0 ≤ K < N), the number of atoms, and the number of bonds that must be changed.
The second line contains N integers A_i (1 ≤ A_i ≤ 10^6), which denotes the energy given by atom i when on excited state.
The third line contains N integers D_i (1 ≤ D_i ≤ 10^6), which denotes the energy needed to excite atom i.
Output
A line with an integer that denotes the maximum number of energy that Mr. Chanek can get.
Example
Input
6 1
5 6 7 8 10 2
3 5 6 7 1 10
Output
35
Note
An optimal solution to change E_5 to 1 and then excite atom 5 with energy 1. It will cause atoms 1, 2, 3, 4, 5 be excited. The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10) - 1 = 35.
Another possible way is to change E_3 to 1 and then exciting atom 3 (which will excite atom 1, 2, 3) and exciting atom 4 (which will excite atom 4, 5, 6). The total energy gained by Mr. Chanek is (5 + 6 + 7 + 8 + 10 + 2) - (6 + 7) = 25 which is not optimal. | instruction | 0 | 70,916 | 14 | 141,832 |
Tags: greedy, implementation
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def main():
n,k = map(int,input().split())
a = list(map(int,input().split()))
d = list(map(int,input().split()))
ans,ans1,x,y = 0,0,sum(a),sum(a)
for i in range(n):
ans = max(ans,x-d[i])
if i:
ans1 = max(ans1,y-a[-1]-d[i],x-d[i])
else:
ans1 = max(ans1,y-a[-1]-d[i],x-d[i]-min(a[1:]))
x -= a[i]
if k >= 2:
print(max(0,sum(a)-min(d[:-1]),a[-1]-d[-1]))
elif k:
r = sorted(d)
print(max(ans1,sum(a)-r[0]-r[1]))
else:
print(ans)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | output | 1 | 70,916 | 14 | 141,833 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.