message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Determine whether it is possible to remove all the stones from the vertices by repeatedly performing the following operation:
* Select a pair of different leaves. Then, remove exactly one stone from every vertex on the path between those two vertices. Here, a leaf is a vertex of the tree whose degree is 1, and the selected leaves themselves are also considered as vertices on the path connecting them.
Note that the operation cannot be performed if there is a vertex with no stone on the path.
Constraints
* 2 ≦ N ≦ 10^5
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
If it is possible to remove all the stones from the vertices, print `YES`. Otherwise, print `NO`.
Examples
Input
5
1 2 1 1 2
2 4
5 2
3 2
1 3
Output
YES
Input
3
1 2 1
1 2
2 3
Output
NO
Input
6
3 2 2 2 2 2
1 2
2 3
1 4
1 5
4 6
Output
YES
Submitted Solution:
```
def examA():
N = I()
A = LI()
ans = "YES"
cur = 0
for a in A:
if a%2==1:
cur +=1
if cur%2==1:
ans = "NO"
print(ans)
return
def examB():
N = I()
A = LI()
ans = "YES"
sumA = sum(A)
oneA = (1+N)*N//2
if sumA%oneA!=0:
ans = "NO"
ope = sumA//oneA
#各Aについて何回始点としたか二分探索
cur = 0
for i in range(N):
now = ope - (A[i]-A[i-1])
if now%N!=0 or now<0:
# print(now,i)
ans = "NO"
break
cur += now//N
if cur!=ope:
ans = "NO"
print(ans)
return
def examC():
N = I()
A = LI()
V = [[]for _ in range(N)]
for i in range(N-1):
a, b = LI()
V[a-1].append(b-1)
V[b-1].append(a-1)
s = -1
for i,v in enumerate(V):
if len(v)>1:
s = i
break
def dfs(s,p):
flag = 1
rep = 0
for v in V[s]:
if v==p:
continue
cur,next = dfs(v,s)
rep += cur
flag *= next
if len(V[s])==1:
rep = A[s]
if rep==0:
return 0,flag
if (rep+1)//2>A[s] or rep<A[s]:
flag = 0
#print(s,rep)
rep -= (rep-A[s])*2
return rep,flag
rep,flag = dfs(s,-1)
if rep!=0:
flag = 0
if flag:
print("YES")
else:
print("NO")
return
from decimal import Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 1<<60
_ep = 10**(-16)
alphabet = [chr(ord('a') + i) for i in range(26)]
sys.setrecursionlimit(10**7)
if __name__ == '__main__':
examC()
``` | instruction | 0 | 95,162 | 13 | 190,324 |
No | output | 1 | 95,162 | 13 | 190,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake".
Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is a road along the coast of the lake which is a cycle of c vertices. The second part is a path from home to the lake which is a chain of t vertices, and there is an edge from the last vertex of this chain to the vertex of the road along the coast which has the most beautiful view of the lake, also known as the finish vertex. Misha decided to keep the field secret, so nobody knows neither t nor c.
<image>
Note that each vertex of the field has exactly one outgoing edge and all the vertices except the home vertex and the finish vertex have exactly one ingoing edge. The home vertex has no incoming edges, the finish vertex has two incoming edges.
At the beginning of the game pieces of all the ten players, indexed with consecutive integers from 0 to 9, are at the home vertex. After that on each turn some of the players can ask Misha to simultaneously move their pieces along the corresponding edges. Misha will not answer more than q such queries. After each move Misha will tell players whose pieces are at the same vertices and whose pieces are at different vertices.
The goal of the game is to move all the pieces to the finish vertex. Misha's friends have no idea how to win in such a game without knowledge of c, t and q, but luckily they are your friends. Help them: coordinate their actions to win the game.
Misha has drawn such a field that 1 ≤ t, c, (t+c) ≤ 1000 and q = 3 ⋅ (t+c).
Input
There is no input — go to the interaction part straight away.
Output
After all friends gather at the finish vertex, print "done" and terminate your program.
Interaction
To give a command to move the friends, print "next" and then space-separated indices of the friends you want to move. For example, to give the command to move the friends with indices 0, 2, 5 and 9 print "next 0 2 5 9". At each turn, you must move at least one of your friends.
As an answer, first read an integer k, and then 10 digits divided into k space-separated groups. The friends that correspond to the indices in the same group are in the same vertex. The friends that correspond to indices in different groups are in different vertices. The indices in each group follow in ascending order.
For example, the answer "2 05 12346789" means that the friends with indices 0 and 5 are in one vertex, and all other friends are in the same but different vertex. The answer "4 01 567 234 89" means that Misha's friends are in four different vertices: the friends with indices 0 and 1 are in the first, the friends with indices 5, 6 and 7 are in the second, the friends with indices 2, 3 and 4 are in the third, and the friends with indices 8 and 9 are in the fourth.
After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer "stop" instead of a valid one means that you made an invalid query. Exit immediately after receiving "stop" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks
In order to hack, print two integers t and c in a single line (1 ≤ t, c, (t+c) ≤ 1000).
Example
Input
2 05 12346789
3 246789 135 0
3 246789 0 135
3 246789 0 135
2 135 0246789
1 0123456789
Output
next 0 5
next 0 1 3
next 2 3 0 1 4 5 6 7 8 9
next 9 8 7 6 5 4 3 2 1 0
next 0 1 3 5
next 1 3 5
done
Note
In the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.
In the example, the friends move as follows:
<image>
Submitted Solution:
```
# Codeforces 1137D
# Credits: https://codeforces.com/contest/1137/submission/51156338
FAST = 0
SLOW = 1
def move(who):
print('next ' + ' '.join(map(str, who)), flush=True)
p = input().split()[1:]
r = [0 for _ in range(10)]
for x in range(len(p)):
for z in p[x]:
r[int(z)] = x
return r
for x in range(0, 1000000):
if x % 2 == 0:
r = move([FAST, SLOW])
else:
r = move([FAST])
if x > 0 and r[FAST] == r[SLOW]:
break
while not all(x == r[0] for x in r):
r = move(range(0, 10))
print('done')
``` | instruction | 0 | 95,314 | 13 | 190,628 |
No | output | 1 | 95,314 | 13 | 190,629 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake".
Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is a road along the coast of the lake which is a cycle of c vertices. The second part is a path from home to the lake which is a chain of t vertices, and there is an edge from the last vertex of this chain to the vertex of the road along the coast which has the most beautiful view of the lake, also known as the finish vertex. Misha decided to keep the field secret, so nobody knows neither t nor c.
<image>
Note that each vertex of the field has exactly one outgoing edge and all the vertices except the home vertex and the finish vertex have exactly one ingoing edge. The home vertex has no incoming edges, the finish vertex has two incoming edges.
At the beginning of the game pieces of all the ten players, indexed with consecutive integers from 0 to 9, are at the home vertex. After that on each turn some of the players can ask Misha to simultaneously move their pieces along the corresponding edges. Misha will not answer more than q such queries. After each move Misha will tell players whose pieces are at the same vertices and whose pieces are at different vertices.
The goal of the game is to move all the pieces to the finish vertex. Misha's friends have no idea how to win in such a game without knowledge of c, t and q, but luckily they are your friends. Help them: coordinate their actions to win the game.
Misha has drawn such a field that 1 ≤ t, c, (t+c) ≤ 1000 and q = 3 ⋅ (t+c).
Input
There is no input — go to the interaction part straight away.
Output
After all friends gather at the finish vertex, print "done" and terminate your program.
Interaction
To give a command to move the friends, print "next" and then space-separated indices of the friends you want to move. For example, to give the command to move the friends with indices 0, 2, 5 and 9 print "next 0 2 5 9". At each turn, you must move at least one of your friends.
As an answer, first read an integer k, and then 10 digits divided into k space-separated groups. The friends that correspond to the indices in the same group are in the same vertex. The friends that correspond to indices in different groups are in different vertices. The indices in each group follow in ascending order.
For example, the answer "2 05 12346789" means that the friends with indices 0 and 5 are in one vertex, and all other friends are in the same but different vertex. The answer "4 01 567 234 89" means that Misha's friends are in four different vertices: the friends with indices 0 and 1 are in the first, the friends with indices 5, 6 and 7 are in the second, the friends with indices 2, 3 and 4 are in the third, and the friends with indices 8 and 9 are in the fourth.
After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer "stop" instead of a valid one means that you made an invalid query. Exit immediately after receiving "stop" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks
In order to hack, print two integers t and c in a single line (1 ≤ t, c, (t+c) ≤ 1000).
Example
Input
2 05 12346789
3 246789 135 0
3 246789 0 135
3 246789 0 135
2 135 0246789
1 0123456789
Output
next 0 5
next 0 1 3
next 2 3 0 1 4 5 6 7 8 9
next 9 8 7 6 5 4 3 2 1 0
next 0 1 3 5
next 1 3 5
done
Note
In the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.
In the example, the friends move as follows:
<image>
Submitted Solution:
```
def move(s):
print('next', s)
return int(input().split())[0]
while 1:
move('0 1')
if move('1') == 2: break
while 1:
if move('0 1 2 3 4 5 6 7 8 9') == 1: break
print('done')
``` | instruction | 0 | 95,315 | 13 | 190,630 |
No | output | 1 | 95,315 | 13 | 190,631 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake".
Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is a road along the coast of the lake which is a cycle of c vertices. The second part is a path from home to the lake which is a chain of t vertices, and there is an edge from the last vertex of this chain to the vertex of the road along the coast which has the most beautiful view of the lake, also known as the finish vertex. Misha decided to keep the field secret, so nobody knows neither t nor c.
<image>
Note that each vertex of the field has exactly one outgoing edge and all the vertices except the home vertex and the finish vertex have exactly one ingoing edge. The home vertex has no incoming edges, the finish vertex has two incoming edges.
At the beginning of the game pieces of all the ten players, indexed with consecutive integers from 0 to 9, are at the home vertex. After that on each turn some of the players can ask Misha to simultaneously move their pieces along the corresponding edges. Misha will not answer more than q such queries. After each move Misha will tell players whose pieces are at the same vertices and whose pieces are at different vertices.
The goal of the game is to move all the pieces to the finish vertex. Misha's friends have no idea how to win in such a game without knowledge of c, t and q, but luckily they are your friends. Help them: coordinate their actions to win the game.
Misha has drawn such a field that 1 ≤ t, c, (t+c) ≤ 1000 and q = 3 ⋅ (t+c).
Input
There is no input — go to the interaction part straight away.
Output
After all friends gather at the finish vertex, print "done" and terminate your program.
Interaction
To give a command to move the friends, print "next" and then space-separated indices of the friends you want to move. For example, to give the command to move the friends with indices 0, 2, 5 and 9 print "next 0 2 5 9". At each turn, you must move at least one of your friends.
As an answer, first read an integer k, and then 10 digits divided into k space-separated groups. The friends that correspond to the indices in the same group are in the same vertex. The friends that correspond to indices in different groups are in different vertices. The indices in each group follow in ascending order.
For example, the answer "2 05 12346789" means that the friends with indices 0 and 5 are in one vertex, and all other friends are in the same but different vertex. The answer "4 01 567 234 89" means that Misha's friends are in four different vertices: the friends with indices 0 and 1 are in the first, the friends with indices 5, 6 and 7 are in the second, the friends with indices 2, 3 and 4 are in the third, and the friends with indices 8 and 9 are in the fourth.
After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer "stop" instead of a valid one means that you made an invalid query. Exit immediately after receiving "stop" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks
In order to hack, print two integers t and c in a single line (1 ≤ t, c, (t+c) ≤ 1000).
Example
Input
2 05 12346789
3 246789 135 0
3 246789 0 135
3 246789 0 135
2 135 0246789
1 0123456789
Output
next 0 5
next 0 1 3
next 2 3 0 1 4 5 6 7 8 9
next 9 8 7 6 5 4 3 2 1 0
next 0 1 3 5
next 1 3 5
done
Note
In the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.
In the example, the friends move as follows:
<image>
Submitted Solution:
```
import sys
def step(l):
print("next", end = '')
for n in l:
print(' ', n, end = '')
print('')
sys.stdout.flush()
if __name__== "__main__":
l1 = [0, 1]
l2 = [1]
l3 = [2, 3, 4, 5, 6, 7, 8, 9]
seEncontrou = False
while not seEncontrou:
step(l1)
step(l2)
ent = []
while(len(ent) == 0):
ent = input().split()
for lx in ent[1:]:
zero = False
one = False
for num in lx:
if num == '0':
zero = True
if num == '1':
one = True
if zero and one:
seEncontrou = True
seEncontrou = False
while not seEncontrou:
step(l1)
step(l3)
ent = []
while(len(ent) == 0):
ent = input().split()
for lx in ent[1:]:
zero = False
two = False
for num in lx:
if num == '0':
zero = True
if num == '2':
two = True
if zero and two:
seEncontrou = True
print("done")
sys.stdout.flush()
``` | instruction | 0 | 95,316 | 13 | 190,632 |
No | output | 1 | 95,316 | 13 | 190,633 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake".
Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is a road along the coast of the lake which is a cycle of c vertices. The second part is a path from home to the lake which is a chain of t vertices, and there is an edge from the last vertex of this chain to the vertex of the road along the coast which has the most beautiful view of the lake, also known as the finish vertex. Misha decided to keep the field secret, so nobody knows neither t nor c.
<image>
Note that each vertex of the field has exactly one outgoing edge and all the vertices except the home vertex and the finish vertex have exactly one ingoing edge. The home vertex has no incoming edges, the finish vertex has two incoming edges.
At the beginning of the game pieces of all the ten players, indexed with consecutive integers from 0 to 9, are at the home vertex. After that on each turn some of the players can ask Misha to simultaneously move their pieces along the corresponding edges. Misha will not answer more than q such queries. After each move Misha will tell players whose pieces are at the same vertices and whose pieces are at different vertices.
The goal of the game is to move all the pieces to the finish vertex. Misha's friends have no idea how to win in such a game without knowledge of c, t and q, but luckily they are your friends. Help them: coordinate their actions to win the game.
Misha has drawn such a field that 1 ≤ t, c, (t+c) ≤ 1000 and q = 3 ⋅ (t+c).
Input
There is no input — go to the interaction part straight away.
Output
After all friends gather at the finish vertex, print "done" and terminate your program.
Interaction
To give a command to move the friends, print "next" and then space-separated indices of the friends you want to move. For example, to give the command to move the friends with indices 0, 2, 5 and 9 print "next 0 2 5 9". At each turn, you must move at least one of your friends.
As an answer, first read an integer k, and then 10 digits divided into k space-separated groups. The friends that correspond to the indices in the same group are in the same vertex. The friends that correspond to indices in different groups are in different vertices. The indices in each group follow in ascending order.
For example, the answer "2 05 12346789" means that the friends with indices 0 and 5 are in one vertex, and all other friends are in the same but different vertex. The answer "4 01 567 234 89" means that Misha's friends are in four different vertices: the friends with indices 0 and 1 are in the first, the friends with indices 5, 6 and 7 are in the second, the friends with indices 2, 3 and 4 are in the third, and the friends with indices 8 and 9 are in the fourth.
After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer "stop" instead of a valid one means that you made an invalid query. Exit immediately after receiving "stop" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks
In order to hack, print two integers t and c in a single line (1 ≤ t, c, (t+c) ≤ 1000).
Example
Input
2 05 12346789
3 246789 135 0
3 246789 0 135
3 246789 0 135
2 135 0246789
1 0123456789
Output
next 0 5
next 0 1 3
next 2 3 0 1 4 5 6 7 8 9
next 9 8 7 6 5 4 3 2 1 0
next 0 1 3 5
next 1 3 5
done
Note
In the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.
In the example, the friends move as follows:
<image>
Submitted Solution:
```
import sys
def step(l):
print("next", end = '')
for n in l:
print(' ', n, end = '')
print('')
sys.stdout.flush()
def le_ent():
global ent
ent = []
while(len(ent) == 0):
ent = input().split()
if __name__== "__main__":
l1 = [0, 1]
l2 = [1]
l3 = [2, 3, 4, 5, 6, 7, 8, 9]
seEncontrou = False
ent = []
while not seEncontrou:
step(l1)
le_ent()
step(l2)
le_ent()
for lx in ent[1:]:
zero = False
one = False
for num in lx:
if num == '0':
zero = True
if num == '1':
one = True
if zero and one:
seEncontrou = True
seEncontrou = False
while not seEncontrou:
step(l1)
le_ent()
step(l3)
le_ent()
for lx in ent[1:]:
zero = False
two = False
for num in lx:
if num == '0':
zero = True
if num == '2':
two = True
if zero and two:
seEncontrou = True
print("done")
sys.stdout.flush()
``` | instruction | 0 | 95,317 | 13 | 190,634 |
No | output | 1 | 95,317 | 13 | 190,635 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Misha likes to play cooperative games with incomplete information. Today he suggested ten his friends to play a cooperative game "Lake".
Misha has already come up with a field for the upcoming game. The field for this game is a directed graph consisting of two parts. The first part is a road along the coast of the lake which is a cycle of c vertices. The second part is a path from home to the lake which is a chain of t vertices, and there is an edge from the last vertex of this chain to the vertex of the road along the coast which has the most beautiful view of the lake, also known as the finish vertex. Misha decided to keep the field secret, so nobody knows neither t nor c.
<image>
Note that each vertex of the field has exactly one outgoing edge and all the vertices except the home vertex and the finish vertex have exactly one ingoing edge. The home vertex has no incoming edges, the finish vertex has two incoming edges.
At the beginning of the game pieces of all the ten players, indexed with consecutive integers from 0 to 9, are at the home vertex. After that on each turn some of the players can ask Misha to simultaneously move their pieces along the corresponding edges. Misha will not answer more than q such queries. After each move Misha will tell players whose pieces are at the same vertices and whose pieces are at different vertices.
The goal of the game is to move all the pieces to the finish vertex. Misha's friends have no idea how to win in such a game without knowledge of c, t and q, but luckily they are your friends. Help them: coordinate their actions to win the game.
Misha has drawn such a field that 1 ≤ t, c, (t+c) ≤ 1000 and q = 3 ⋅ (t+c).
Input
There is no input — go to the interaction part straight away.
Output
After all friends gather at the finish vertex, print "done" and terminate your program.
Interaction
To give a command to move the friends, print "next" and then space-separated indices of the friends you want to move. For example, to give the command to move the friends with indices 0, 2, 5 and 9 print "next 0 2 5 9". At each turn, you must move at least one of your friends.
As an answer, first read an integer k, and then 10 digits divided into k space-separated groups. The friends that correspond to the indices in the same group are in the same vertex. The friends that correspond to indices in different groups are in different vertices. The indices in each group follow in ascending order.
For example, the answer "2 05 12346789" means that the friends with indices 0 and 5 are in one vertex, and all other friends are in the same but different vertex. The answer "4 01 567 234 89" means that Misha's friends are in four different vertices: the friends with indices 0 and 1 are in the first, the friends with indices 5, 6 and 7 are in the second, the friends with indices 2, 3 and 4 are in the third, and the friends with indices 8 and 9 are in the fourth.
After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Answer "stop" instead of a valid one means that you made an invalid query. Exit immediately after receiving "stop" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks
In order to hack, print two integers t and c in a single line (1 ≤ t, c, (t+c) ≤ 1000).
Example
Input
2 05 12346789
3 246789 135 0
3 246789 0 135
3 246789 0 135
2 135 0246789
1 0123456789
Output
next 0 5
next 0 1 3
next 2 3 0 1 4 5 6 7 8 9
next 9 8 7 6 5 4 3 2 1 0
next 0 1 3 5
next 1 3 5
done
Note
In the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.
In the example, the friends move as follows:
<image>
Submitted Solution:
```
from __future__ import division, print_function
import itertools
import os
import sys
from __builtin__ import xrange as range
from cStringIO import StringIO
from future_builtins import ascii, filter, hex, map, oct, zip
from io import IOBase
from collections import deque
import __pypy__
MOD = 10 ** 9 + 7
def main():
# 0: fast
# 1: slow
same = False
ctr = 0
while not same:
curres = ["next", "0"]
if ctr % 2:
curres.append("1")
print(" ".join(curres))
sys.stdout.flush()
imparr = sys.stdin.readline().strip()
if imparr == "stop":
return
imparr = imparr.split()
k = int(imparr[0]); arr = imparr[1:]
for str in arr:
if len(str) >= 2 and str[0] == '0' and str[1] == '1':
same = True
ctr += 1
while True:
print("next 0 1 2 3 4 5 6 7 8 9")
sys.stdout.flush()
imparr = sys.stdin.readline().strip()
if imparr == "stop":
return
if imparr[0] == "1":
break
print("done")
stdout.flush()
""" Python 3 compatibility tools. """
def compatibility():
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
""" End of Python 3 compatibility tools. """
""" Python Fast IO """
BUFSIZE = 8192
class FastI(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = StringIO()
self.newlines = 0
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("\n") + (not b)
ptr = self._buffer.tell()
self._buffer.seek(0,
2), self._buffer.write(b), self._buffer.seek(ptr)
self.newlines -= 1
return self._buffer.readline()
class FastO(IOBase):
def __init__(self, file):
self._fd = file.fileno()
self._buffer = __pypy__.builders.StringBuilder()
self.write = lambda s: self._buffer.append(s)
def flush(self):
os.write(self._fd, self._buffer.build())
self._buffer = __pypy__.builders.StringBuilder()
def print(*args, **kwargs):
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()
sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
""" End of Python Fast IO """
if __name__ == "__main__":
len = len
compatibility()
main()
``` | instruction | 0 | 95,318 | 13 | 190,636 |
No | output | 1 | 95,318 | 13 | 190,637 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer k and an undirected tree, consisting of n vertices.
The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree.
You are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to k.
Two sets of edges are different if there is an edge such that it appears in only one of the sets.
Count the number of valid sets of edges modulo 998 244 353.
Input
The first line contains two integers n and k (2 ≤ n ≤ 5000, 0 ≤ k ≤ n - 1) — the number of vertices of the tree and the maximum allowed diameter, respectively.
Each of the next n-1 lines contains a description of an edge: two integers v and u (1 ≤ v, u ≤ n, v ≠ u).
The given edges form a tree.
Output
Print a single integer — the number of valid sets of edges modulo 998 244 353.
Examples
Input
4 3
1 2
1 3
1 4
Output
8
Input
2 0
1 2
Output
1
Input
6 2
1 6
2 4
2 6
3 6
5 6
Output
25
Input
6 3
1 2
1 5
2 3
3 4
5 6
Output
29
Note
In the first example the diameter of the given tree is already less than or equal to k. Thus, you can choose any set of edges to remove and the resulting trees will have diameter less than or equal to k. There are 2^3 sets, including the empty one.
In the second example you have to remove the only edge. Otherwise, the diameter will be 1, which is greater than 0.
Here are the trees for the third and the fourth examples:
<image> | instruction | 0 | 95,502 | 13 | 191,004 |
Tags: combinatorics, dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import deque
input = lambda :sys.stdin.buffer.readline()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
mod = 998244353
N,K = mi()
edge = [[] for i in range(N)]
for _ in range(N-1):
a,b = mi()
edge[a-1].append(b-1)
edge[b-1].append(a-1)
parent = [-1 for i in range(N)]
deq = deque([0])
res = []
while deq:
v = deq.popleft()
res.append(v)
for nv in edge[v]:
if nv!=parent[v]:
parent[nv] = v
deq.append(nv)
dp = [[1] for i in range(N)]
def merge(v,nv):
res_dp = [0 for i in range(max(len(dp[v]),len(dp[nv])+1))]
for i in range(len(dp[v])):
for j in range(len(dp[nv])):
if j+1+i <= K:
res_dp[max(j+1,i)] += dp[v][i] * dp[nv][j]
res_dp[max(j+1,i)] %= mod
res_dp[i] += dp[v][i] * dp[nv][j]
res_dp[i] %= mod
dp[v] = res_dp
for v in res[::-1]:
for nv in edge[v]:
if nv==parent[v]:
continue
merge(v,nv)
print(sum(dp[0][i] for i in range(min(K+1,len(dp[0])))) % mod)
``` | output | 1 | 95,502 | 13 | 191,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer k and an undirected tree, consisting of n vertices.
The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of this tree.
You are about to remove a set of edges from the tree. The tree splits into multiple smaller trees when the edges are removed. The set of edges is valid if all the resulting trees have diameter less than or equal to k.
Two sets of edges are different if there is an edge such that it appears in only one of the sets.
Count the number of valid sets of edges modulo 998 244 353.
Input
The first line contains two integers n and k (2 ≤ n ≤ 5000, 0 ≤ k ≤ n - 1) — the number of vertices of the tree and the maximum allowed diameter, respectively.
Each of the next n-1 lines contains a description of an edge: two integers v and u (1 ≤ v, u ≤ n, v ≠ u).
The given edges form a tree.
Output
Print a single integer — the number of valid sets of edges modulo 998 244 353.
Examples
Input
4 3
1 2
1 3
1 4
Output
8
Input
2 0
1 2
Output
1
Input
6 2
1 6
2 4
2 6
3 6
5 6
Output
25
Input
6 3
1 2
1 5
2 3
3 4
5 6
Output
29
Note
In the first example the diameter of the given tree is already less than or equal to k. Thus, you can choose any set of edges to remove and the resulting trees will have diameter less than or equal to k. There are 2^3 sets, including the empty one.
In the second example you have to remove the only edge. Otherwise, the diameter will be 1, which is greater than 0.
Here are the trees for the third and the fourth examples:
<image>
Submitted Solution:
```
nk = input().split()
n, k = int(nk[0]), int(nk[1])
if n == 4 and k == 3: print(8)
if n == 2 and k == 0: print(1)
if n == 6 and k == 2: print(25)
if n == 6 and k == 3: print(29)
``` | instruction | 0 | 95,503 | 13 | 191,006 |
No | output | 1 | 95,503 | 13 | 191,007 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added. | instruction | 0 | 95,504 | 13 | 191,008 |
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
'''Author- Akshit Monga'''
# Don't know the proper proof
from sys import stdin, stdout
input = stdin.readline
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
@bootstrap
def detach(start,parent):
global removed
childs=list(graph[start])
for i in childs:
if i==parent:
continue
yield detach(i,start)
childs=graph[start].copy()
if parent:
childs.remove(parent)
childs=list(childs)
if len(childs)>=2:
if parent:
removed.append((start,parent))
graph[start].remove(parent)
graph[parent].remove(start)
for i in childs[2:]:
removed.append((start,i))
graph[start].remove(i)
graph[i].remove(start)
yield
@bootstrap
def dfs(start):
global check
vis.add(start)
count=0
for i in graph[start]:
count+=1
if i not in vis:
yield dfs(i)
if count==0:
leaves.append(start)
leaves.append(start)
elif count==1:
leaves.append(start)
yield
t = int(input())
for _ in range(t):
n=int(input())
graph=[set() for i in range(n+1)]
for i in range(n-1):
a,b=map(int,input().split())
graph[a].add(b)
graph[b].add(a)
removed=[]
added=[]
leaves=[]
detach(1,0)
vis=set()
for i in range(1,n+1):
if i not in vis:
dfs(i)
for i in range(1,len(leaves)-1,2):
added.append((leaves[i],leaves[i+1]))
x=len(removed)
print(x)
for i in range(x):
stdout.write(str(removed[i][0])+" "+str(removed[i][1])+" "+str(added[i][0])+" "+str(added[i][1])+'\n')
``` | output | 1 | 95,504 | 13 | 191,009 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added. | instruction | 0 | 95,505 | 13 | 191,010 |
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
n = int(input())
edges = [list(map(int,input().split())) for i in range(n-1)]
adj = [set() for i in range(n+1)]
for a,b in edges:
adj[a].add(b)
adj[b].add(a)
operations = []
#removed_edge = [0]*(n-1)
visited = [0] * (n + 1)
parent = [0]*(n+1)
s = [1]
while s:
c = s[-1]
if not visited[c]:
visited[c] = 1
for ne in adj[c]:
if not visited[ne]:
parent[ne] = c
s.append(ne)
else:
if len(adj[c]) > 2:
if parent[c]:
operations.append([c,parent[c]])
adj[parent[c]].remove(c)
adj[c].remove(parent[c])
while len(adj[c]) > 2:
x = adj[c].pop()
adj[x].remove(c)
operations.append([x, c])
s.pop()
'''for i in range(n-1):
a,b = edges[i]
if len(adj[a]) > 2 and len(adj[b]) > 2:
operations.append([a,b])
adj[a].remove(b)
adj[b].remove(a)
removed_edge[i] = 1
for i in range(n-1):
a,b = edges[i]
if not removed_edge[i]:
if len(adj[a]) > 2:
operations.append([a,b])
adj[a].remove(b)
adj[b].remove(a)
if len(adj[b]) > 2:
operations.append([a, b])
adj[a].remove(b)
adj[b].remove(a)
'''
endpoints = []
visited = [0]*(n+1)
for i in range(1,n+1):
if not visited[i]:
endpoints.append([])
s = [i]
while s:
c = s[-1]
if not visited[c]:
visited[c] = 1
if len(adj[c]) <= 1:
endpoints[-1].append(c)
for ne in adj[c]:
s.append(ne)
else:
s.pop()
assert(len(operations) == len(endpoints) -1)
for i in range(len(endpoints)-1):
if len(endpoints[i]) == 1:
endpoints[i].append(endpoints[i][0])
operations[i].extend([endpoints[i][1],endpoints[i+1][0]])
print(len(operations))
for operation in operations:
print(*operation)
``` | output | 1 | 95,505 | 13 | 191,011 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added. | instruction | 0 | 95,506 | 13 | 191,012 |
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import sys
sys.setrecursionlimit(250010)
def dfs(x):
tag[x] = 1
ql = -1
tgs = (-1, -1)
l = 0
for v in lian[x]:
if tag[v] == 0:
t = dfs(v)
gs[v][0] = t[0]
gs[v][1] = t[1]
if gs[v][0] == -1 and ql == -1:
ql = v
q[x].append(v)
l += 1
if l == 0:
tag[x] = 0
return (-1, x)
if ql == -1:
for i in range(l-1):
ans[0] += 1
res[ans[0]-1] = (q[x][i], x, gs[q[x][i]][0], gs[q[x][i+1]][0])
gs[q[x][i+1]][0] = gs[q[x][i]][1]
ans[0] += 1
res[ans[0]-1] = (q[x][l-1], x, gs[q[x][l-1]][0], x)
tgs = (-1, gs[q[x][l-1]][1])
else:
v2 = ql
last = -1
for i in range(l):
if gs[q[x][i]][0] != -1:
ans[0] += 1
res[ans[0]-1] = (q[x][i], x, gs[q[x][i]][0], gs[v2][1])
gs[v2][1] = gs[q[x][i]][1]
else:
last = q[x][i]
for i in range(l):
if gs[q[x][i]][0] == -1 and q[x][i] != v2 and q[x][i] != last:
ans[0] += 1
res[ans[0]-1] = (q[x][i], x, q[x][i], gs[v2][1])
gs[v2][1] = gs[q[x][i]][1]
if last == v2:
tgs = (-1, gs[v2][1])
else:
tgs = (gs[v2][1], gs[last][1])
tag[x] = 0
return tgs
for _ in range(int(input())):
n = int(input())
q = [[] for i in range(n+1)]
lian = [[] for i in range(n+1)]
tag = [0] * (n+1)
res = [0]* (n+1)
ans = [0]
gs = [[-1,-1] for i in range(n+1)]
for i in range(n-1):
a,b = map(int, input().split())
lian[a].append(b)
lian[b].append(a)
dfs(1)
print(ans[0])
for t in range(ans[0]):
i = res[t]
print(i[0],i[1],i[2],i[3])
``` | output | 1 | 95,506 | 13 | 191,013 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added. | instruction | 0 | 95,507 | 13 | 191,014 |
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import io
import os
from collections import defaultdict
from types import GeneratorType
from heapq import heappush, heappop
# From https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py
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
def solve(N, edges):
graph = [[] for i in range(N)]
for (u, v) in edges:
graph[u].append(v)
graph[v].append(u)
dp1 = [0] * N
dp2 = [0] * N
bp1 = [()] * N # back pointers
bp2 = [()] * N
@bootstrap
def dfs(node, p):
for child in graph[node]:
if child != p:
yield dfs(child, node)
total = 0 # total if connected with no children
heap = [] # sorted connectable children
for child in graph[node]:
if child != p:
total += dp2[child]
heappush(heap, (dp2[child] - dp1[child], child))
if heap:
# Connect with 1 child
gain1, child1 = heappop(heap)
gain1 *= -1
score1 = 1 + total + gain1
if dp1[node] < score1:
dp1[node] = score1
bp1[node] = (child1,)
if dp2[node] < score1:
dp2[node] = score1
bp2[node] = (child1,)
if heap:
# Connect with 2 children
gain2, child2 = heappop(heap)
gain2 *= -1
assert gain2 <= gain1
score2 = 2 + total + gain1 + gain2
if dp2[node] < score2:
dp2[node] = score2
bp2[node] = (child1, child2)
assert dp1[node] <= dp2[node]
yield
dfs(0, -1)
disconnect = []
@bootstrap
def dfs2(node, p, isConnected):
if not isConnected and dp1[node] < dp2[node]:
connectedChild = bp2[node]
else:
connectedChild = bp1[node]
for child in graph[node]:
if child != p:
childConnected = child in connectedChild
if not childConnected:
disconnect.append((node, child))
yield dfs2(child, node, childConnected)
yield
dfs2(0, -1, False)
# Construct the paths
disconnect = set(disconnect)
uf = UnionFind(N)
degree = [0] * N
for u, v in edges:
if (u, v) in disconnect or (v, u) in disconnect:
continue
degree[u] += 1
degree[v] += 1
uf.union(u, v)
paths = defaultdict(list)
for u in range(N):
if degree[u] <= 1:
paths[uf.find(u)].append(u)
endpoints = list(paths.values())
# Join the endpoints
ops = []
for i in range(len(endpoints) - 1):
x = endpoints[i][-1]
y = endpoints[i + 1][0]
u, v = disconnect.pop()
ops.append(" ".join(str(i + 1) for i in [u, v, x, y]))
assert not disconnect
assert len(ops) == N - 1 - max(dp1[0], dp2[0])
return str(len(ops)) + "\n" + "\n".join(ops)
class UnionFind:
def __init__(self, N):
# Union find with component size
# Negative means is a root where value is component size
# Otherwise is index to parent
self.p = [-1 for i in range(N)]
def find(self, i):
# Find root with path compression
if self.p[i] >= 0:
self.p[i] = self.find(self.p[i])
return self.p[i]
else:
return i
def union(self, i, j):
# Union by size
root1 = self.find(j)
root2 = self.find(i)
if root1 == root2:
return
size1 = -self.p[root1]
size2 = -self.p[root2]
if size1 < size2:
self.p[root1] = root2
self.p[root2] = -(size1 + size2)
else:
self.p[root2] = root1
self.p[root1] = -(size1 + size2)
def getComponentSize(self, i):
return -self.p[self.find(i)]
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
(N,) = [int(x) for x in input().split()]
edges = [[int(x) - 1 for x in input().split()] for i in range(N - 1)]
ans = solve(N, edges)
print(ans)
``` | output | 1 | 95,507 | 13 | 191,015 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added. | instruction | 0 | 95,508 | 13 | 191,016 |
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
def leaf(f,u):
if len(m[u])==1:
return u
else:
for v in m[u]:
if v!=f:
ans=leaf(u,v)
if ans:return ans
def cut():
stack=[]
stack.append([0,-1,leaf(-1,0)])
while len(stack):
a,*b=stack.pop()
f,u=b
if a==0:
stack.append([1,f,u])
for v in m[u]-{f}:
stack.append([0,u,v])
elif a==1:
du=len(m[u])
it=iter(m[u]-{f})
if du>=3:
while du>=4:
v=next(it)
ct.append((u+1,v+1))
m[v].remove(u)
m[u].remove(v)
du-=1
if f!=-1:
ct.append((f+1,u+1))
m[u].remove(f)
m[f].remove(u)
def link():
l=set()
node=-1
for i in range(n):
if len(m[i])<=1:
l.add(i)
v=next(iter(l))
l.discard(v)
u=end(v)
l.discard(u)
while len(l)!=0:
v=next(iter(l))
l.discard(v)
lk.append((u+1,v+1))
u=end(v)
l.discard(u)
def end(s):
if len(m[s])==0:return s
f=s
s=next(iter(m[s]))
while len(m[s])!=1:
f,s=s,next(iter(m[s]-{f}))
return s
for test in range(int(input())):
n=int(input())
m=[set() for i in range(n)]
ct=[]
lk=[]
for i in range(n-1):
a,b=(int(i)-1 for i in input().split())
m[a].add(b);m[b].add(a)
cut()
link()
op=zip(ct,lk)
print(len(ct))
for c,l in op:
print(*c,*l)
``` | output | 1 | 95,508 | 13 | 191,017 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added. | instruction | 0 | 95,509 | 13 | 191,018 |
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import sys
sys.setrecursionlimit(111111)
def dfs(x):
tag[x] = 1
q = []
ql = -1
tgs = [-1, -1]
for v in lian[x]:
if tag[v] == 0:
gs[v] = dfs(v)
if gs[v][0] == -1 and ql == -1:
ql = v
q.append(v)
if len(q) == 0:
return [-1, x]
if ql == -1:
for i in range(len(q)-1):
v1 = q[i]
v2 = q[i+1]
ans[0] += 1
res.append((v1, x, gs[v1][0], gs[v2][0]))
gs[v2][0] = gs[v1][1]
v = q[len(q)-1]
ans[0] += 1
res.append((v, x, gs[v][0], x))
tgs = [-1, gs[v][1]]
else:
v2 = ql
last = -1
for i in range(len(q)):
v1 = q[i]
if gs[v1][0] != -1:
ans[0] += 1
res.append((v1, x, gs[v1][0], gs[v2][1]))
gs[v2][1] = gs[v1][1]
else:
last = v1
for i in range(len(q)):
v1 = q[i]
if gs[v1][0] == -1 and v1 != v2 and v1 != last:
ans[0] += 1
res.append((v1, x, v1, gs[v2][1]))
gs[v2][1] = gs[v1][1]
if last == v2:
tgs = [-1, gs[v2][1]]
else:
tgs = [gs[v2][1], gs[last][1]]
return tgs
for i in range(len(q)-1):
v = q[i][1]
dus = q[i][0]
if dus == 3:
ans[0] += 1
for _ in range(int(input())):
n = int(input())
du = [0]*(n+1)
lian = [[] for i in range(n+1)]
tag = [0] * (n+1)
res = []
ans = [0]
gs = [[-1,-1] for i in range(n+1)]
for i in range(n-1):
a,b = map(int, input().split())
du[a] += 1
du[b] += 1
lian[a].append(b)
lian[b].append(a)
dfs(1)
print(ans[0])
for i in res:
print(i[0],i[1],i[2],i[3])
``` | output | 1 | 95,509 | 13 | 191,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added. | instruction | 0 | 95,510 | 13 | 191,020 |
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
import time
#start_time = time.time()
#def TIME_(): print(time.time()-start_time)
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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 getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def getBin(): return list(map(int,list(input())))
def isInt(s): return '0' <= s[0] <= '9'
def ceil_(a,b): return a//b + (a%b > 0)
MOD = 10**9 + 7
"""
"""
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
def solve():
N = getInt()
G = [[] for _ in range(N)]
deg = [0]*N
par = [-1]*N
for i in range(N-1):
a, b = getInts()
G[a-1].append(b-1)
G[b-1].append(a-1)
#to_remove = []
to_add = []
leaves = []
removed = set()
global count
count = 0
@bootstrap
def dfs(node):
global count
children = 0
for neigh in G[node]:
if neigh != par[node]:
par[neigh] = node
yield dfs(neigh)
if (node, neigh) not in removed: children += 1
if children == 2:
if par[node] != -1:
#to_remove.append((par[node],node))
count += 1
removed.add((par[node],node))
if children > 2:
if par[node] != -1:
count += 1
removed.add((par[node],node))
idx = len(G[node]) - 1
while children > 2:
if G[node][idx] == par[node]: idx -= 1
#to_remove.append((node,G[node][idx]))
count += 1
while (node,G[node][idx]) in removed or G[node][idx] == par[node]:
idx -= 1
removed.add((node,G[node][idx]))
children -= 1
idx -= 1
yield
dfs(0)
ends = []
used = [0]*N
global flag
@bootstrap
def dfs2(node):
global flag
if flag: neighs = 1
else: neighs = 0
flag = True
used[node] = 1
for neigh in G[node]:
if not used[neigh] and (node,neigh) not in removed and (neigh,node) not in removed:
neighs += 1
yield dfs2(neigh)
if neighs == 1:
ends.append(node)
elif neighs == 0:
ends.append(node)
ends.append(node)
yield
for i in range(N):
flag = False
if not used[i]:
dfs2(i)
removed = list(removed)
#print(removed)
#print(ends)
#print(len(ends))
print(len(removed))
j = 0
for i in range(1,len(ends)-1,2):
print(removed[j][0]+1,removed[j][1]+1,ends[i]+1,ends[i+1]+1)
j += 1
return
for _ in range(getInt()):
#print(solve())
solve()
#TIME_()
``` | output | 1 | 95,510 | 13 | 191,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added. | instruction | 0 | 95,511 | 13 | 191,022 |
Tags: constructive algorithms, data structures, dfs and similar, dp, dsu, greedy, implementation, trees
Correct Solution:
```
def dfs(x, e, v, g):
v[x] = True
c = 0
for y in e[x]:
if not y in v:
if dfs(y, e, v, g):
c += 1
if c > 2:
g.append((x, y))
else:
g.append((x, y))
if c < 2:
return True
if x != 1:
return False
def leaf(x, e):
p = 0
while True:
u = 0
for y in e[x]:
if y != p:
u = y
break
if u == 0: break
p = x
x = u
return x
def solve(n, e):
g = []
dfs(1, e, {}, g)
for x, y in g:
e[x].remove(y)
e[y].remove(x)
z = []
l = leaf(1, e)
for p, y, in g:
r = leaf(y, e)
z.append((p, y, l, r))
l = leaf(r, e)
print(len(z))
if len(z) > 0:
print('\n'.join(map(lambda x: ' '.join(map(str, x)), z)))
def main():
t = int(input())
for i in range(t):
n = int(input())
e = {}
for i in range(n - 1):
a, b = map(int, input().split())
if not a in e: e[a] = []
if not b in e: e[b] = []
e[a].append(b)
e[b].append(a)
solve(n, e)
import threading
import sys
sys.setrecursionlimit(10 ** 5 + 1)
threading.stack_size(262000)
main = threading.Thread(target=main)
main.start()
main.join()
``` | output | 1 | 95,511 | 13 | 191,023 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
'''
from bisect import bisect,bisect_left
from collections import *
from heapq import *
from math import gcd,ceil,sqrt,floor,inf
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().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
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
mod=10**9+7
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
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
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 floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
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 ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
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
class UF:#秩+路径+容量,边数
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
self.size=AI(n,1)
self.edge=A(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:
self.edge[pu]+=1
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
self.edge[pu]+=self.edge[pv]+1
self.size[pu]+=self.size[pv]
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
self.edge[pv]+=self.edge[pu]+1
self.size[pv]+=self.size[pu]
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
return flag
def dij(s,graph):
d=AI(n,inf)
d[s]=0
heap=[(0,s)]
vis=A(n)
while heap:
dis,u=heappop(heap)
if vis[u]:
continue
vis[u]=1
for v,w in graph[u]:
if d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def bell(s,g):#bellman-Ford
dis=AI(n,inf)
dis[s]=0
for i in range(n-1):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change=A(n)
for i in range(n):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change[v]=1
return dis
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j,n,m):
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
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
#from random import randint
from heapq import *
@bootstrap
def dfs(r,p):
s=0
one=[]
for ch in g[r]:
if ch!=p:
child[r].append(ch)
yield dfs(ch,r)
ma=max(dp[ch])
s+=ma
t1=dp[ch][1]
if t1+1>ma:
heappush(one,[ma-t1-1,ch])
#print(r,one)
if not one:
dp[r]=[s,s,s]
elif len(one)==1:
v,ch=heappop(one)
ma=max(dp[ch])
for i in range(3):
if dp[ch][i]==ma:
break
g1[r].append((ch,i))
dp[r]=[s,s-v,s-v]
else:
v,ch=heappop(one)
v2,ch2=heappop(one)
ma=max(dp[ch])
for i in range(3):
if dp[ch][i]==ma:
break
g1[r].append((ch,i))
g2[r].append((ch,i))
ma2=max(dp[ch2])
for i in range(3):
if dp[ch2][i]==ma2:
break
g2[r].append((ch2,i))
dp[r]=[s,s-v,s-v-v2]
yield None
@bootstrap
def dfs2(r,t):
used=set()
#print(r,t)
if t==1:
#print(r)
ch,i=g1[r][0]
used.add(ch)
x,y=r,ch
if x>y:
x,y=y,x
nedge.add((x,y))
yield dfs2(ch,i)
elif t==2:
for ch,i in g2[r]:
used.add(ch)
x,y=r,ch
if x>y:
x,y=y,x
nedge.add((x,y))
yield dfs2(ch,i)
for ch in child[r]:
if ch not in used:
ma=max(dp[ch])
for i in range(3):
if dp[ch][i]==ma:
break
#print(r,ch,i)
yield dfs2(ch,i)
yield None
t=N()
for i in range(t):
n=N()
g=G(n)
edge=[]
for i in range(n-1):
a,b=RL()
a-=1
b-=1
g[a].append(b)
g[b].append(a)
if a>b:
a,b=b,a
edge.append((a,b))
g1=G(n)
g2=G(n)
dp=[[0]*3 for i in range(n)]
child=G(n)
dfs(0,-1)
ma=max(dp[0])
for i in range(3):
if dp[0][i]==ma:
break
nedge=set()
#print(dp,i)
#print(g1)
#print(g2)
dfs2(0,i)
delt=[]
add=[]
for x,y in edge:
if (x,y) not in nedge:
delt.append((x,y))
na=G(n)
#ind=A(n)
for x,y in nedge:
na[x].append(y)
na[y].append(x)
#print(nedge,na)
vis=A(n)
for i in range(n):
if len(na[i])==0:
add.append((i,i))
elif len(na[i])==1 and not vis[i]:
#print(i)
u=i
vis[u]=1
v=na[u][0]
while len(na[v])!=1:
#print(i,v)
for ch in na[v]:
if ch!=i:
i,v=v,ch
#print(i,v)
break
add.append((u,v))
vis[v]=1
#print(u,v,vis)
#print(add,delt)
i=0
print(len(delt))
for i in range(len(delt)):
x2,y2=add[i][1],add[i+1][0]
x1,y1=delt[i]
print(x1+1,y1+1,x2+1,y2+1)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
``` | instruction | 0 | 95,512 | 13 | 191,024 |
Yes | output | 1 | 95,512 | 13 | 191,025 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
def order(n,G):
ans = []
parent = [-1]*n
def dfs(x,par):
parent[x] = par
for y in G[x]:
if y == par:
continue
dfs(y,x)
ans.append(x)
dfs(1,-1)
return ans,parent
def solve(n,G,topo,parent):
to_remove = []
for x in topo:
p = parent[x]
num_child = len(G[x]) - (1 if p in G[x] else 0)
if num_child <= 1:
pass
else:
if p != -1:
to_remove.append((x,p))
G[x].remove(p)
G[p].remove(x)
to_select = 0
tmp = []
for y in G[x]:
if y == p:
continue
if to_select < 2:
to_select += 1
else:
to_remove.append((y,x))
tmp.append(y)
for y in tmp:
G[x].remove(y)
G[y].remove(x)
visited = [False]*n
def find_bamboo(x):
visited[x] = True
if not G[x]:
return x,x
par = x
while len(G[x]) > 1:
for y in G[x]:
if y != par:
par = x
x = y
break
par = x
cur = list(G[x])[0]
visited[x] = True
visited[cur] = True
while len(G[cur]) > 1:
for y in G[cur]:
if y != par:
par = cur
cur = y
visited[y] = True
break
return x,cur
bamboos = []
for x in range(n):
if not visited[x]:
u,v = find_bamboo(x)
bamboos.append((u,v))
k = len(to_remove)
print(k)
for i in range(k):
a,b = bamboos[i][1], bamboos[i+1][0]
u,v = to_remove[i]
print(u+1,v+1,a+1,b+1)
return
for nt in range(int(input())):
n = int(input())
G = [set() for _ in range(n)]
for _ in range(n-1):
a,b = map(int,input().split())
G[a-1].add(b-1)
G[b-1].add(a-1)
topo,parent = order(n,G)
solve(n,G,topo,parent)
``` | instruction | 0 | 95,513 | 13 | 191,026 |
Yes | output | 1 | 95,513 | 13 | 191,027 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
import sys
def readline():
return map(int, input().split())
def solve():
n = int(input())
nbrs = [list() for __ in range(n)]
for __ in range(n - 1):
ai, bi = readline()
ai -= 1
bi -= 1
nbrs[ai].append(bi)
nbrs[bi].append(ai)
to_delete = list()
pos = 0
parent = -1
arr = list(nbrs[pos]) # copy
stack = [(pos, parent, arr)]
while stack:
pos, parent, arr = stack[-1]
if arr:
child = arr.pop()
if child != parent and len(nbrs[child]) > 1:
pos, parent = child, pos
stack.append((pos, parent, list(nbrs[pos])))
continue
else:
stack.pop()
if len(nbrs[pos]) > 2 and parent >= 0:
nbrs[pos].remove(parent)
nbrs[parent].remove(pos)
to_delete.append((pos, parent))
while len(nbrs[pos]) > 2:
child = nbrs[pos].pop()
nbrs[child].remove(pos)
to_delete.append((pos, child))
segments = list()
is_tail = [False] * n
for i in range(n):
p = len(nbrs[i])
assert p <= 2
if p == 0:
segments.append((i, i))
if is_tail[i] or p != 1:
continue
pos, = nbrs[i]
prev = i
while len(nbrs[pos]) == 2:
prev, pos = pos, sum(nbrs[pos]) - prev
assert len(nbrs[pos]) == 1
is_tail[pos] = True
segments.append((i, pos))
a, b = segments.pop()
k = len(to_delete)
assert k == len(segments)
print(k)
for ((x1, y1), (c, d)) in zip(to_delete, segments):
print(x1 + 1, y1 + 1, b + 1, d + 1)
b = c
def main():
t = int(input())
for __ in range(t):
solve()
if __name__ == '__main__':
main()
``` | instruction | 0 | 95,514 | 13 | 191,028 |
Yes | output | 1 | 95,514 | 13 | 191,029 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import log,gcd
input = lambda :sys.stdin.buffer.readline()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
INF = 10**17
def test(n):
p = [i+1 for i in range(n)]
random.shuffle(p)
Edge = []
for i in range(1,n):
pv = random.randint(0,i-1)
Edge.append((p[pv],p[i]))
return Edge
def line(N):
node = [i+2 for i in range(N-1)]
random.shuffle(node)
node = [1] + node
edge=[]
for i in range(1,N):
edge.append((node[i-1],node[i]))
return edge
def star(N):
node = [i+1 for i in range(N)]
random.shuffle(node)
edge = []
for i in range(1,N):
if random.randint(0,9999)%2:
edge.append((node[0],node[i]))
else:
edge.append((node[i],node[0]))
return edge
for _ in range(int(input())):
n = int(input())
#Edge = test(n)
edge = [[] for i in range(n)]
for i in range(n-1):
a,b = mi()
edge[a-1].append(b-1)
edge[b-1].append(a-1)
deq = deque([0])
parent = [-1]*n
topo = []
while deq:
v = deq.popleft()
topo.append(v)
for nv in edge[v]:
if nv!=parent[v]:
parent[nv] = v
deq.append(nv)
topo = topo[::-1]
dp = [[0,INF,INF] for v in range(n)]
not_cut = [[None,-1,(-1,-1)] for v in range(n)]
def merge(v,nv):
a,b,c = dp[v]
dp[v][0] += min(dp[nv]) + 1
dp[v][1] += min(dp[nv]) + 1
dp[v][2] += min(dp[nv]) + 1
if b + min(dp[nv][0],dp[nv][1]) < dp[v][2]:
not_cut[v][2] = (not_cut[v][1],nv)
dp[v][2] = b + min(dp[nv][0],dp[nv][1])
if a + min(dp[nv][0],dp[nv][1]) < dp[v][1]:
not_cut[v][1] = nv
dp[v][1] = a + min(dp[nv][0],dp[nv][1])
for v in topo:
for nv in edge[v]:
if nv!=parent[v]:
merge(v,nv)
topo = topo[::-1]
limit = [2 for v in range(n)]
print(min(dp[0]))
CUT = []
_ADD = []
for v in topo:
if limit[v]==1:
if dp[v][1] < dp[v][0]:
for nv in edge[v]:
if nv!=parent[v]:
if nv!=not_cut[v][1]:
CUT.append((v,nv))
else:
limit[nv] = 1
else:
for nv in edge[v]:
if nv!=parent[v]:
CUT.append((v,nv))
else:
if dp[v][2] < dp[v][1]:
a,b = -1,-1
for nv in edge[v]:
if nv!=parent[v]:
if nv not in not_cut[v][2]:
CUT.append((v,nv))
else:
limit[nv] = 1
while not_cut[nv][1]!=-1:
if dp[nv][1] < dp[nv][0]:
nv = not_cut[nv][1]
else:
break
if a==-1:
a = nv
else:
b = nv
_ADD.append((a,b))
else:
if dp[v][1] < dp[v][0]:
a,b = v,-1
for nv in edge[v]:
if nv!=parent[v]:
if nv!=not_cut[v][1]:
CUT.append((v,nv))
else:
limit[nv] = 1
while not_cut[nv][1]!=-1:
if dp[nv][1] < dp[nv][0]:
nv = not_cut[nv][1]
else:
break
b = nv
_ADD.append((a,b))
else:
_ADD.append((v,v))
for nv in edge[v]:
if nv!=parent[v]:
CUT.append((v,nv))
for i in range(len(_ADD)-1):
a,b = _ADD[i]
c,d = _ADD[i+1]
u,v = CUT[i]
print(u+1,v+1,b+1,c+1)
assert len(CUT)==min(dp[0])
assert len(CUT)==len(_ADD)-1
``` | instruction | 0 | 95,515 | 13 | 191,030 |
Yes | output | 1 | 95,515 | 13 | 191,031 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
import sys
# sys.stdin = open("actext.txt", "r")
t = int(input())
for tt in range(t):
n = int(input())
adj_list = [[] for i in range(n+1)]
for i in range(n-1):
x, y = map(int, input().split())
adj_list[x].append(y)
deg = []
for num, i in enumerate(adj_list[1:]):
if(num == 0):
deg.append(len(i))
else:
deg.append(len(i)+1)
ans = 0
toattach = -1
for num, j in enumerate(deg[1:]):
if(j == 1):
toattach = num+2
break
for i in deg:
ans += max(0, i-2)
print(ans)
# print(deg)
degg = list(zip(deg,[i for i in range(1,n+1)]))
degg.sort()
st = []
# print(degg)
# print(adj_list)
for k,kk in degg:
if(k>2):
st.append(kk)
# print(st)
for num in st:
if(num==1):
cnt = 2
else:
cnt=1
if(deg[num-1] > 2):
elem = adj_list[num][cnt:]
for j in elem:
print(num, j, toattach, j)
ff = j
while(len(adj_list[ff])!=0):
ff = adj_list[ff][0]
toattach = ff
``` | instruction | 0 | 95,516 | 13 | 191,032 |
No | output | 1 | 95,516 | 13 | 191,033 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
how_much_t = int(input())
max_of_tops = 2#int(input("Введите максимальное количество вершин\n"))
for global_cycle in range(how_much_t):
this_tops = int(input())
quan_of_ribs = []
for cycle in range(this_tops - 1):
quan_of_ribs.append(list(map(int, input().split(" "))))
if this_tops == 7:
print("2")
print("2 1 5 6")
print("3 6 4 7")
elif this_tops == 4:
print("0")
``` | instruction | 0 | 95,517 | 13 | 191,034 |
No | output | 1 | 95,517 | 13 | 191,035 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
def dfs1(n,G,x,par,B):
# return an endpoint of a bamboo
# push extra nodes to B
if len(G[x]) == 1:
return x
found = False
for y in G[x]:
if y == par:
continue
if not found:
found = True
ans = dfs1(n,G,y,x,B)
else:
B.append((y,x))
return ans
def dfs2(n,G,x,par,B):
# num_child >= 2
to_select = []
for y in G[x]:
if y == par:
continue
if len(to_select) < 2:
to_select.append(y)
else:
B.append((y,x))
a,b = to_select
u = dfs1(n,G,a,x,B)
v = dfs1(n,G,b,x,B)
return u,v
def solve(n,G):
B = [(0,-1)]
to_remove = []
bamboo = []
while B:
x,par = B.pop()
num_child = sum(1 for y in G[x] if y != par)
if par != -1:
to_remove.append((x,par))
if num_child == 1:
z = dfs1(n,G,x,par,B)
bamboo.append((z,x))
elif num_child >= 2:
u,v = dfs2(n,G,x,par,B)
bamboo.append((u,v))
else:
bamboo.append((x,x))
k = len(to_remove)
print(k)
for i in range(k):
x,y = to_remove[i]
a = bamboo[i][1]
b = bamboo[i+1][0]
print(x+1,y+1,a+1,b+1)
for nt in range(int(input())):
n = int(input())
G = [[] for _ in range(n)]
for _ in range(n-1):
a,b = map(int,input().split())
G[a-1].append(b-1)
G[b-1].append(a-1)
solve(n,G)
``` | instruction | 0 | 95,518 | 13 | 191,036 |
No | output | 1 | 95,518 | 13 | 191,037 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tree? A bamboo is a tree in which no node has a degree greater than 2.
Input
The first line contains a single integer t (1 ≤ t ≤ 10 000) — the number of test cases.
The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) — the number of vertices in the tree.
Next n - 1 lines of each test cases describe the edges of the tree in form a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i).
It's guaranteed the given graph is a tree and the sum of n in one test doesn't exceed 2 ⋅ 10^5.
Output
For each test case in the first line print a single integer k — the minimum number of operations required to obtain a bamboo from the initial tree.
In the next k lines print 4 integers x_1, y_1, x_2, y_2 (1 ≤ x_1, y_1, x_2, y_{2} ≤ n, x_1 ≠ y_1, x_2 ≠ y_2) — this way you remove the edge (x_1, y_1) and add an undirected edge (x_2, y_2).
Note that the edge (x_1, y_1) must be present in the graph at the moment of removing.
Example
Input
2
7
1 2
1 3
2 4
2 5
3 6
3 7
4
1 2
1 3
3 4
Output
2
2 5 6 7
3 6 4 5
0
Note
Note the graph can be unconnected after a certain operation.
Consider the first test case of the example:
<image> The red edges are removed, and the green ones are added.
Submitted Solution:
```
from collections import defaultdict, deque
from random import randint
def test(edges):
n = len(edges) + 1
v_by_v = defaultdict(list)
for edge in edges:
v1, v2 = edge
v_by_v[v1].append(v2)
v_by_v[v2].append(v1)
prevVert = dict()
def searchFar(i):
nonlocal prevVert
d = deque()
d.append(i)
dist = dict()
dist[i] = 0
while len(d) > 0:
currV = d.pop()
for v in v_by_v[currV]:
if v not in dist.keys():
d.append(v)
dist[v] = dist[currV] + 1
prevVert[v] = currV
vFar = max([i for i in range(1, n+1)], key = lambda x: dist[x])
return vFar
v1 = searchFar(1)
v2 =searchFar(v1)
x = v2
edgeSet = set()
vertSet = set()
while x != v1:
xPrev = prevVert[x]
edgeSet.add((xPrev, x))
edgeSet.add((x, xPrev))
vertSet.add(x)
x = xPrev
vertSet.add(v1)
vertSet = set(range(1, n + 1)) - vertSet
finish = v2
result = []
nextVerts = defaultdict(list)
for v in range(1, n + 1):
if v in prevVert.keys():
vPrev = prevVert[v]
nextVerts[vPrev].append(v)
nearVerts = [v for v in vertSet if prevVert[v] not in vertSet]
while len(nearVerts) > 0:
v = nearVerts.pop()
x1 = prevVert[v]
x2 = v
while len(nextVerts[v]) > 0:
nearVerts.extend(nextVerts[v][1:])
v = nextVerts[v][0]
result.append([x1, x2, finish, x2])
finish = v
return result
# def createTree(n):
# edges = deque()
# edges.append((1,2))
# for i in range(n-2):
# x2 = i + 3
# x1 = randint(1, i + 2)
# edges.append((x1, x2))
# return edges
# while True:
# edges = createTree(randint(2, 10))
# print('created tree',len(edges) + 1)
# for edge in edges:
# print(edge)
# result = test(edges)
# print(len(result))
# for x in result:
# x = map(str, x)
# print(' '.join(x))
# print('1 - stop, 0 - continue')
# stop = input()
# if stop == '1':
# assert False
t = int(input())
results = []
for _ in range(t):
n = int(input())
edges = [tuple(map(int, input().split(' '))) for _ in range(n-1)]
result = test(edges)
results.append(result)
for result in results:
print(len(result))
for x in result:
x = map(str, x)
print(' '.join(x))
``` | instruction | 0 | 95,519 | 13 | 191,038 |
No | output | 1 | 95,519 | 13 | 191,039 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 95,603 | 13 | 191,206 |
Tags: binary search, data structures, dp
Correct Solution:
```
import sys
input = sys.stdin.readline
I = lambda : list(map(int,input().split()))
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (A[m] >= key):
r = m
else:
l = m
return r
def lis(A, size):
tailTable = [0 for i in range(size + 1)]
len = 0 # always points empty slot
tailTable[0] = A[0]
len = 1
for i in range(1, size):
if (A[i] < tailTable[0]):
tailTable[0] = A[i]
elif (A[i] > tailTable[len-1]):
tailTable[len] = A[i]
len+= 1
else:
tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i]
return len
n,=I()
p=I()
an=1
print(lis(p,n))
``` | output | 1 | 95,603 | 13 | 191,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 95,604 | 13 | 191,208 |
Tags: binary search, data structures, dp
Correct Solution:
```
from sys import stdin
input = stdin.readline
class BIT():
def __init__(self, n):
self.n = n
self.tree = [0] * (n + 1)
def sum(self, i):
ans = 0
i += 1
while i > 0:
ans =max(ans, self.tree[i])
i -= (i & (-i))
return ans
def update(self, i, value):
i += 1
while i <= self.n:
self.tree[i] = max(value,self.tree[i])
i += (i & (-i))
def f(a):
newind=0
maxs=0
ans=0
ft=BIT(2*(10**5)+5)
for i in a:
maxs=ft.sum(i-1)
# print(maxs,i)
ft.update(i,maxs+1)
ans=max(ans,maxs+1)
# print(ft.tree)
return ans
a=input()
l=list(map(int,input().strip().split()))
print(f(l))
``` | output | 1 | 95,604 | 13 | 191,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 95,605 | 13 | 191,210 |
Tags: binary search, data structures, dp
Correct Solution:
```
import math
import sys
from bisect import bisect_right, bisect_left, insort_right
from collections import Counter, defaultdict
from heapq import heappop, heappush
from itertools import accumulate, permutations, combinations
from sys import stdout
R = lambda: map(int, input().split())
n = int(input())
arr = list(R())
tps = [(0, 0)]
for x in arr:
i = bisect_left(tps, (x, -1)) - 1
tps.insert(i + 1, (x, tps[i][1] + 1))
if i + 2 < len(tps) and tps[i + 1][1] >= tps[i + 2][1]:
del tps[i + 2]
print(max(x[1] for x in tps))
``` | output | 1 | 95,605 | 13 | 191,211 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 95,606 | 13 | 191,212 |
Tags: binary search, data structures, dp
Correct Solution:
```
from bisect import *
s, n = [0], input()
for i in map(int, input().split()):
if i > s[-1]: s.append(i)
else: s[bisect_right(s, i)] = i
print(len(s) - 1)
``` | output | 1 | 95,606 | 13 | 191,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 95,607 | 13 | 191,214 |
Tags: binary search, data structures, dp
Correct Solution:
```
from bisect import bisect_left, bisect_right, insort
R = lambda: map(int, input().split())
n, arr = int(input()), list(R())
dp = []
for i in range(n):
idx = bisect_left(dp, arr[i])
if idx >= len(dp):
dp.append(arr[i])
else:
dp[idx] = arr[i]
print(len(dp))
``` | output | 1 | 95,607 | 13 | 191,215 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 95,608 | 13 | 191,216 |
Tags: binary search, data structures, dp
Correct Solution:
```
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (A[m] >= key):
r = m
else:
l = m
return r
def LongestIncreasingSubsequenceLength(A, size):
# Add boundary case,
# when array size is one
tailTable = [0 for i in range(size + 1)]
len = 0 # always points empty slot
tailTable[0] = A[0]
len = 1
for i in range(1, size):
if (A[i] < tailTable[0]):
# new smallest value
tailTable[0] = A[i]
elif (A[i] > tailTable[len-1]):
# A[i] wants to extend
# largest subsequence
tailTable[len] = A[i]
len+= 1
else:
# A[i] wants to be current
# end candidate of an existing
# subsequence. It will replace
# ceil value in tailTable
tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i]
return len
N = int(input())
List = [int(x) for x in input().split()]
print(LongestIncreasingSubsequenceLength(List,N))
``` | output | 1 | 95,608 | 13 | 191,217 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 95,609 | 13 | 191,218 |
Tags: binary search, data structures, dp
Correct Solution:
```
n = int(input())
num_list = list(map(int, input().split()))
# def lower_bound(min_lis, x):
# #goal return the position of the first element >= x
# left = 0
# right = len(min_lis) - 1
# res = -1
# while left <= right:
# mid = (left + right) // 2
# if min_lis[mid] < x:
# left = mid + 1
# else:
# res = mid
# right = mid - 1
# return res
import bisect
def LongestIncreasingSubsequence(a, n):
min_lis = []
#lis = [0 for i in range(n)]
for i in range(n):
pos = bisect.bisect_left(min_lis, a[i])
if pos == len(min_lis):
#lis[i] = len(min_lis) + 1
min_lis.append(a[i])
else:
#lis[i] = pos + 1
min_lis[pos] = a[i]
#print(*min_lis)
return (len(min_lis))
print(LongestIncreasingSubsequence(num_list, n))
``` | output | 1 | 95,609 | 13 | 191,219 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2]. | instruction | 0 | 95,610 | 13 | 191,220 |
Tags: binary search, data structures, dp
Correct Solution:
```
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (A[m] >= key):
r = m
else:
l = m
return r
def LIS(A, size):
tailTable = [0 for i in range(size + 1)]
len = 0
tailTable[0] = A[0]
len = 1
for i in range(1, size):
if (A[i] < tailTable[0]):
tailTable[0] = A[i]
elif (A[i] > tailTable[len-1]):
tailTable[len] = A[i]
len+= 1
else:
tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i]
return len
def main():
n = int(input())
arr = list(map(int,input().split()))
print(LIS(arr,n))
main()
``` | output | 1 | 95,610 | 13 | 191,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
# Python program to find
# length of longest
# increasing subsequence
# in O(n Log n) time
# Binary search (note
# boundaries in the caller)
# A[] is ceilIndex
# in the caller
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (A[m] >= key):
r = m
else:
l = m
return r
def Lis(A, size):
# Add boundary case,
# when array size is one
tailTable = [0 for i in range(size + 1)]
len = 0 # always points empty slot
tailTable[0] = A[0]
len = 1
for i in range(1, size):
if (A[i] < tailTable[0]):
# new smallest value
tailTable[0] = A[i]
elif (A[i] > tailTable[len-1]):
# A[i] wants to extend
# largest subsequence
tailTable[len] = A[i]
len+= 1
else:
# A[i] wants to be current
# end candidate of an existing
# subsequence. It will replace
# ceil value in tailTable
tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i]
return len
# Driver program to
# test above function
a=int(input())
z=list(map(int,input().split()))
print(Lis(z,a))
``` | instruction | 0 | 95,611 | 13 | 191,222 |
Yes | output | 1 | 95,611 | 13 | 191,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
def lis(a):
b = []
for c in a:
# if len(b) == 0 or c > b[-1]
if len(b) == 0 or c > b[-1]:
b.append(c)
else:
l = 0
r = len(b)
while l < r-1:
m = l+r>>1
# if b[m] <= c: l = m
if b[m] < c: l = m
else: r = m
# if b[l] <= c: l += 1
if b[l] < c: l += 1
b[l] = c
return len(b)
n = int(input())
a = list(map(int, input().split()))
print(lis(a))
``` | instruction | 0 | 95,612 | 13 | 191,224 |
Yes | output | 1 | 95,612 | 13 | 191,225 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
import sys,math as mt
import heapq as hp
import collections as cc
import math as mt
import itertools as it
input=sys.stdin.readline
I=lambda:list(map(int,input().split()))
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (A[m] >= key):
r = m
else:
l = m
return r
def lis(A, size):
tailTable = [0 for i in range(size + 1)]
len = 0
tailTable[0] = A[0]
len = 1
for i in range(1, size):
if (A[i] < tailTable[0]):
tailTable[0] = A[i]
elif (A[i] > tailTable[len-1]):
tailTable[len] = A[i]
len+= 1
else:
tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i]
return len
n,=I()
l=I()
print(lis(l,n))
``` | instruction | 0 | 95,613 | 13 | 191,226 |
Yes | output | 1 | 95,613 | 13 | 191,227 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
n=int(input())
a=list(map(lambda x: int(x), input().split()))
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l) // 2
if (A[m] >= key):
r = m
else:
l = m
return r
def LongestIncreasingSubsequenceLength(A, size):
# Add boundary case,
# when array size is one
tailTable = [0 for i in range(size + 1)]
len = 0 # always points empty slot
tailTable[0] = A[0]
len = 1
for i in range(1, size):
if (A[i] < tailTable[0]):
# new smallest value
tailTable[0] = A[i]
elif (A[i] > tailTable[len - 1]):
# A[i] wants to extend
# largest subsequence
tailTable[len] = A[i]
len += 1
else:
# A[i] wants to be current
# end candidate of an existing
# subsequence. It will replace
# ceil value in tailTable
tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]
return len
print(LongestIncreasingSubsequenceLength(a,len(a)))
``` | instruction | 0 | 95,614 | 13 | 191,228 |
Yes | output | 1 | 95,614 | 13 | 191,229 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
s, n = [0], input()
for i in map(int, input().split()):
if i > s[-1]: s.append(i)
else: s[-1] = i
print(len(s) - 1)
``` | instruction | 0 | 95,615 | 13 | 191,230 |
No | output | 1 | 95,615 | 13 | 191,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
from collections import defaultdict
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
group_members = defaultdict(list)
for member in range(self.n):
group_members[self.find(member)].append(member)
return group_members
n=int(input())
a=list(map(int,input().split()))
uf=UnionFind(n)
for i in range(n-1):
if a[i]>a[i+1]:
uf.union(a[i]-1,a[i+1]-1)
ans=0
for p in uf.roots():
ans=max(ans,uf.size(p))
print(ans)
``` | instruction | 0 | 95,616 | 13 | 191,232 |
No | output | 1 | 95,616 | 13 | 191,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
n = int(input())
num_list = list(map(int, input().split()))
def lower_bound(min_lis, x):
#goal return the position of the first element >= x
left = 0
right = len(min_lis) - 1
res = -1
while left <= right:
mid = (left + right) // 2
if min_lis[mid] < x:
left = mid + 1
else:
res = mid
right = mid - 1
return res
def LongestIncreasingSubsequence(a, n):
min_lis = []
#lis = [0 for i in range(n)]
for i in range(n-1, -1, -1):
pos = lower_bound(min_lis, a[i])
if pos == -1:
#lis[i] = len(min_lis) + 1
min_lis.append(a[i])
else:
#lis[i] = pos + 1
min_lis[pos] = a[i]
return (len(min_lis))
print(LongestIncreasingSubsequence(num_list, n))
``` | instruction | 0 | 95,617 | 13 | 191,234 |
No | output | 1 | 95,617 | 13 | 191,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Submitted Solution:
```
N = int(input())
List = [int(x) for x in input().split()]
MinPre = [0] * N
Min = List[0]
index = 0
for i in range(1,N):
if(Min>List[i]):
index = i
Min = List[i]
MinPre[i] = index
Ans = [1] * N
for i in range(N):
if(MinPre[i] == i):
continue
else:
Ans[i] = Ans[MinPre[i]] + 1
print(max(Ans))
``` | instruction | 0 | 95,618 | 13 | 191,236 |
No | output | 1 | 95,618 | 13 | 191,237 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 95,670 | 13 | 191,340 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
#!/usr/bin/env python
# coding=utf-8
n = int(input())
l = []
for i in range(n):
x, y = map(int, input().split())
l += [(x + y, x - y)]
l.sort()
r = -2000000000
a = 0
for u in l:
if u[1] >= r:
a += 1
r = u[0]
print(a)
# Made By Mostafa_Khaled
``` | output | 1 | 95,670 | 13 | 191,341 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 95,671 | 13 | 191,342 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
def on(l1, l2):
return(abs(l1[0]-l2[0])>=l1[1]+l2[1])
n = int(input())
inf = []
for i in range(n):
a,b = map(int,input().split())
inf.append([a+b,a-b])
inf.sort()
res = 1
last = 0
for i in range(1,n):
if inf[i][1] >= inf[last][0]:
res+=1
last = i
print(res)
``` | output | 1 | 95,671 | 13 | 191,343 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 95,672 | 13 | 191,344 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
from sys import stdin,setrecursionlimit
import threading
def main():
n = int(stdin.readline())
line = []
for i in range(n):
x, w = [int(x) for x in stdin.readline().split()]
line.append((x-w,x+w))
line.sort()
def best(ind, line):
r = line[ind][1]
nxt = ind+1
while nxt < len(line):
nL, nR = line[nxt]
if nL >= r:
return best(nxt, line)+1
elif nR < r:
return best(nxt,line)
nxt += 1
return 1
print(best(0,line))
if __name__ == "__main__":
setrecursionlimit(10**6)
threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join()
``` | output | 1 | 95,672 | 13 | 191,345 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 95,673 | 13 | 191,346 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
from sys import stdin
from sys import stdout
from collections import defaultdict
n=int(stdin.readline())
a=[map(int,stdin.readline().split(),(10,10)) for i in range(n)]
v=defaultdict(list)
for i,e in enumerate(a,1):
q,f=e
v[q-f].append(i)
v[q+f-1].append(-i)
sa=set()
rez=0
for j in sorted(v.keys()):
for d in v[j]:
if d>0:
sa.add(d)
for d in v[j]:
if -d in sa:
sa.clear()
rez+=1
stdout.write(str(rez))
``` | output | 1 | 95,673 | 13 | 191,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 95,674 | 13 | 191,348 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
from operator import itemgetter
class CodeforcesTask528BSolution:
def __init__(self):
self.result = ''
self.n = 0
self.points = []
def read_input(self):
self.n = int(input())
for _ in range(self.n):
self.points.append([int(x) for x in input().split(" ")])
self.points[-1].append(sum(self.points[-1]))
def process_task(self):
self.points.sort(key=itemgetter(2))
last = 0
ans = 1
for i in range(1, self.n):
if self.points[i][0] - self.points[i][1] >= self.points[last][0] + self.points[last][1]:
last = i
ans += 1
self.result = str(ans)
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask528BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
``` | output | 1 | 95,674 | 13 | 191,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 95,675 | 13 | 191,350 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
import sys
readline = sys.stdin.readline
def main():
N = int(input())
itvs = []
for _ in range(N):
x, w = map(int, input().split())
itvs.append((x - w, x + w))
itvs.sort(key=lambda x: x[1])
ans = 0
end = -(10**9 + 1)
for l, r in itvs:
if end <= l:
ans += 1
end = r
print(ans)
if __name__ == "__main__":
main()
``` | output | 1 | 95,675 | 13 | 191,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 95,676 | 13 | 191,352 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
from bisect import bisect
import sys
readlines = sys.stdin.buffer.readlines
readline = sys.stdin.buffer.readline
def solve(X,W):
'''
(X[j]>X[i]) and (X[j]-W[j] >= X[i]+W[i]) <=> i,j are connected
'''
XW = sorted((x,w) for x,w in zip(X,W))
dp = [2*10**9+1]*len(X)
n = 0
for x,w in XW:
i = bisect(dp,x-w,hi=n)
if x+w < dp[i]:
dp[i] = x+w
n += i==n
return n
if __name__ == '__main__':
n = int(readline())
X,W = [None]*n,[None]*n
for i,s in enumerate(readlines()):
x,w = map(int,s.split())
X[i] = x
W[i] = w
print(solve(X,W))
``` | output | 1 | 95,676 | 13 | 191,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 95,677 | 13 | 191,354 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
n = int(input())
d = []
for i in range(n):
xx, ww = [int(i) for i in input().split()]
d.append([xx-ww, xx+ww])
d.sort(key=lambda x:x[0])
last = -100000000000
ans = 0
for i in range(n):
if last <= d[i][0]:
last = d[i][1]
ans += 1
elif last > d[i][1]:
last = d[i][1]
print(ans)
``` | output | 1 | 95,677 | 13 | 191,355 |
Provide tags and a correct Python 2 solution for this coding contest problem.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image> | instruction | 0 | 95,678 | 13 | 191,356 |
Tags: data structures, dp, greedy, implementation, sortings
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
from fractions import Fraction
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
# main code
n=ni()
l=[]
for i in range(n):
l.append(tuple(li()))
l.sort(key=lambda x:sum(x))
id=0
ans=1
for i in range(1,n):
if l[i][0]-l[i][1]>=sum(l[id]):
id=i
ans+=1
pn(ans)
``` | output | 1 | 95,678 | 13 | 191,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<image>
Submitted Solution:
```
def solve():
from sys import stdin
f_i = stdin
n = int(f_i.readline())
segments = []
for i in range(n):
x, w = map(int, f_i.readline().split())
segments.append((x + w, x - w)) # (end, start)
segments.sort()
ans = 0
t = segments[0][1]
for end, start in segments:
if t <= start:
ans += 1
t = end
print(ans)
solve()
``` | instruction | 0 | 95,679 | 13 | 191,358 |
Yes | output | 1 | 95,679 | 13 | 191,359 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.