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 |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it. | instruction | 0 | 16,982 | 13 | 33,964 |
Tags: data structures, dsu, graphs, greedy, sortings, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
def _find(s, u):
par = []
while s[u] != u:
par.append(u)
u = s[u]
for v in par: s[v] = u
return u
def _union(s, u1, u2):
su1, su2 = _find(s, u1), _find(s, u2)
if su1 != su2: s[su1] = su2
m, n = map(int, input().split())
a, b = list(map(int, input().split())), list(map(int, input().split()))
q = []
for i in range(m):
ls = list(map(int, input().split()))
for u in ls[1:]:
q.append((a[i] + b[u-1], i, m+u-1))
q.sort(reverse=True)
cc, dsu = 0, list(range(m+n))
for cost, u1, u2 in q:
s1, s2 = _find(dsu, u1), _find(dsu, u2)
if s1 == s2: cc += cost
else: _union(dsu, s1, s2)
print(cc)
``` | output | 1 | 16,982 | 13 | 33,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it. | instruction | 0 | 16,983 | 13 | 33,966 |
Tags: data structures, dsu, graphs, greedy, sortings, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**4)
M, N = map(int, input().split())
NN = N + M
e = [-1] * NN
def find(x):
if e[x] < 0: return x
e[x] = find(e[x])
return e[x]
def join(a, b):
a, b = find(a), find(b)
if a == b: return False
if e[a] > e[b]: a, b = b, a
e[a] += e[b]
e[b] = a
return True
A = list(map(int, input().split()))
B = list(map(int, input().split()))
E = []
cost = 0
for i in range(M):
_, *X = map(lambda s: int(s)-1, input().split())
for j in X:
cost += A[i] + B[j]
E.append((i, M + j, A[i] + B[j]))
E.sort(key=lambda v: -v[2])
i = 1
for a, b, c in E:
if join(a, b):
cost -= c
i += 1
if i == NN: break
print(cost)
``` | output | 1 | 16,983 | 13 | 33,967 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it. | instruction | 0 | 16,984 | 13 | 33,968 |
Tags: data structures, dsu, graphs, greedy, sortings, trees
Correct Solution:
```
import sys
input=sys.stdin.readline
class UnionFind():
def __init__(self,n):
self.n=n
self.root=[-1]*(n+1)
self.rank=[0]*(n+1)
def FindRoot(self,x):
if self.root[x]<0:
return x
else:
self.root[x]=self.FindRoot(self.root[x])
return self.root[x]
def Unite(self,x,y):
x=self.FindRoot(x)
y=self.FindRoot(y)
if x==y:
return
else:
if self.rank[x]>self.rank[y]:
self.root[x]+=self.root[y]
self.root[y]=x
elif self.rank[x]<=self.rank[y]:
self.root[y]+=self.root[x]
self.root[x]=y
if self.rank[x]==self.rank[y]:
self.rank[y]+=1
def isSameGroup(self,x,y):
return self.FindRoot(x)==self.FindRoot(y)
def Count(self,x):
return -self.root[self.FindRoot(x)]
m,n=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
q=[]
uf=UnionFind(m+n)
ans=0
for i in range(m):
tmp=list(map(int,input().split()))
for j in range(1,tmp[0]+1):
q.append((-(a[i]+b[tmp[j]-1]),i,m+tmp[j]-1))
ans+=(a[i]+b[tmp[j]-1])
q=sorted(q,key=lambda x:x[0])
for cost,i,j in q:
if uf.isSameGroup(i,j):
continue
else:
ans+=cost
uf.Unite(i,j)
print(ans)
``` | output | 1 | 16,984 | 13 | 33,969 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it. | instruction | 0 | 16,985 | 13 | 33,970 |
Tags: data structures, dsu, graphs, greedy, sortings, trees
Correct Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
def main():
m,n = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
setA = []
aTuple = []
for i in range(m):
setA.append(list(map(int,input().split()))[1:])
costSet = []
for i in range(m):
for elem in setA[i]:
costSet.append((a[i] + b[elem - 1],elem - 1,i))
costSet.sort(reverse = True)
finalSetA = []
for i in range(m):
finalSetA.append([])
ans = 0
color = []
colorDict = {}
for i in range(n):
color.append(i)
colorDict[i] = [i]
for elem in costSet:
if not finalSetA[elem[2]]:
finalSetA[elem[2]].append(elem[1])
continue
else:
currentElem = finalSetA[elem[2]][0]
currentElem2 = elem[1]
if color[currentElem] != color[currentElem2]:
if len(colorDict[color[currentElem]]) > len(colorDict[color[currentElem2]]):
deletableColor = color[currentElem2]
newColor = color[currentElem]
for elem2 in colorDict[deletableColor]:
colorDict[newColor].append(elem2)
color[elem2] = newColor
del colorDict[deletableColor]
else:
deletableColor = color[currentElem]
newColor = color[currentElem2]
for elem2 in colorDict[deletableColor]:
colorDict[newColor].append(elem2)
color[elem2] = newColor
del colorDict[deletableColor]
finalSetA[elem[2]].append(elem[1])
else:
ans += elem[0]
print(ans)
# 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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | output | 1 | 16,985 | 13 | 33,971 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it. | instruction | 0 | 16,986 | 13 | 33,972 |
Tags: data structures, dsu, graphs, greedy, sortings, trees
Correct Solution:
```
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.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(io.IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
def calc_group_num(self):
N = len(self._parent)
ans = 0
for i in range(N):
if self.find_root(i) == i:
ans += 1
return ans
m,n = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
edge = []
S = 0
for i in range(m):
g = list(map(int,input().split()))
for k in range(1,g[0]+1):
j = g[k] - 1
val = ((a[i]+b[j])<<40) | (i<<20) |m+j
edge.append(val)
S += a[i]+b[j]
edge.sort(reverse=True)
uf = UnionFindVerSize(n+m)
mask1 = 2**40-1
mask2 = 2**20-1
for val in edge:
cost,u,v = val>>40,(val&mask1)>>20,val&mask2
if not uf.is_same_group(u,v):
S-=cost
uf.unite(u,v)
print(S)
``` | output | 1 | 16,986 | 13 | 33,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it.
Submitted Solution:
```
# region fastio # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.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(io.IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#endregion
class UnionFind: # from https://atcoder.jp/contests/practice2/submissions/16791073
__slots__ = ["_data_size", "_roots"]
def __init__(self, data_size: int) -> None:
self._data_size = data_size
self._roots = [-1]*data_size
def __getitem__(self, x: int) -> int:
while self._roots[x] >= 0:
x = self._roots[x]
return x
def is_connected(self, x: int, y: int) -> bool:
return self[x] == self[y]
def unite(self, x: int, y: int) -> None:
x, y = self[x], self[y]
if x == y:
return
if self._roots[x] > self._roots[y]:
x, y = y, x
self._roots[x] += self._roots[y]
self._roots[y] = x
M, N = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
LA = [list(map(int, input().split()))[1:] for _ in range(M)]
ans = 0
Pool = []
for super_v, (a, la) in enumerate(zip(A, LA)):
ans += len(la) * a
for v in la:
v -= 1
b = B[v]
ans += b
Pool.append(a+b<<40 | super_v<<20 | v)
Pool.sort(reverse=True)
ans2 = 0
uf = UnionFind(M)
mask = (1<<20) - 1
G = [[] for _ in range(N)]
for p in Pool:
v = p & mask
p >>= 20
super_v = p & mask
cost = p >> 20
if not G[v]:
ans2 += cost
G[v].append(super_v)
else:
super_u = G[v][0]
if uf.is_connected(super_v, super_u):
pass
else:
ans2 += cost
G[v].append(super_v)
uf.unite(super_v, super_u)
print(ans - ans2)
``` | instruction | 0 | 16,987 | 13 | 33,974 |
Yes | output | 1 | 16,987 | 13 | 33,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it.
Submitted Solution:
```
import sys; input = sys.stdin.buffer.readline
# sys.setrecursionlimit(10**7)
def getlist():
return list(map(int, input().split()))
class UnionFind:
def __init__(self, N):
self.par = [i for i in range(N)]
self.rank = [0] * N
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def same_check(self, x, y):
return self.find(x) == self.find(y)
def union(self, x, y):
x = self.find(x); y = self.find(y)
if self.rank[x] < self.rank[y]:
self.par[x] = y
else:
self.par[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
class Kruskal:
def __init__(self, E, N):
self.uf = UnionFind(N)
self.cost = 0
for w, u, v in E:
if self.uf.same_check(u, v) != True:
self.uf.union(u, v)
self.cost += w
def mincost(self):
return self.cost
def main():
M, N = getlist()
A = getlist()
B = getlist()
E = []
MAX = 0
for i in range(M):
num = getlist()
s = num[0]
for j in range(1, s + 1):
bj = num[j] - 1
w = A[i] + B[bj]
E.append((w, i, M + bj))
MAX += w
E.sort(key=lambda x: x[0], reverse=True)
K = Kruskal(E, N + M)
res = K.mincost()
# print(res)
# print(E)
ans = MAX - res
print(ans)
if __name__ == '__main__':
main()
``` | instruction | 0 | 16,988 | 13 | 33,976 |
Yes | output | 1 | 16,988 | 13 | 33,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it.
Submitted Solution:
```
import sys;input=sys.stdin.readline
def root(x):
if x == p[x]:
return x
p[x] = y = root(p[x])
return y
def unite(x, y):
px = root(x); py = root(y)
if px == py:
return 0
rx = rank[px]; ry = rank[py]
if ry < rx:
p[py] = px
elif rx < ry:
p[px] = py
else:
p[py] = px
rank[px] += 1
return
if __name__ == "__main__":
M, N = map(int, input().split());A = list(map(int, input().split()));B = list(map(int, input().split()));E = [];R = 0
for i in range(M):
X = list(map(int, input().split()))
for j in X[1:]:E.append((N+i, j-1, -A[i]-B[j-1]));R += A[i]+B[j-1]
E.sort(key=lambda x:x[2]);*p, = range(N+M);rank = [1]*(N+M)
for v, u, c in E:
if root(v) != root(u):unite(v, u);R += c
print(R)
``` | instruction | 0 | 16,989 | 13 | 33,978 |
Yes | output | 1 | 16,989 | 13 | 33,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it.
Submitted Solution:
```
import sys;input=sys.stdin.readline
def root(x):
if x == p[x]:return x
p[x] = y = root(p[x]);return y
def unite(x, y):
px = root(x); py = root(y)
if px == py:return 0
rx = rank[px]; ry = rank[py]
if ry < rx:p[py] = px
elif rx < ry:p[px] = py
else:p[py] = px;rank[px] += 1
return
M, N = map(int, input().split());A = list(map(int, input().split()));B = list(map(int, input().split()));E = [];R = 0
for i in range(M):
X = list(map(int, input().split()))
for j in X[1:]:E.append((N+i, j-1, -A[i]-B[j-1]));R += A[i]+B[j-1]
E.sort(key=lambda x:x[2]);*p, = range(N+M);rank = [1]*(N+M)
for v, u, c in E:
if root(v) != root(u):unite(v, u);R += c
print(R)
``` | instruction | 0 | 16,990 | 13 | 33,980 |
Yes | output | 1 | 16,990 | 13 | 33,981 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it.
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
def _find(s, u):
par = []
while s[u] != u:
par.append(u)
u = s[u]
for v in par: s[v] = u
return u
def _union(s, u1, u2):
su1, su2 = _find(s, u1), _find(s, u2)
if su1 != su2: s[su1] = su2
m, n = map(int, input().split())
a, b = list(map(int, input().split())), list(map(int, input().split()))
A = []
for _ in range(m):
ls = list(map(int, input().split()))
A.append(list(sorted([u-1 for u in ls[1:]], key=lambda u: -b[u])))
cc, dsu = 0, list(range(n))
for acost, p in sorted([(a[p], p) for p in range(m)], reverse=True):
d = dict()
for u in A[p]:
su = _find(dsu, u)
if su in d: cc += acost + b[u]
else: d[su] = u
d = list(d.values())
for i in range(1, len(d)):
_union(dsu, d[i-1], d[i])
print(cc)
``` | instruction | 0 | 16,991 | 13 | 33,982 |
No | output | 1 | 16,991 | 13 | 33,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it.
Submitted Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
def main():
m,n = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
setA = []
aTuple = []
for i in range(m):
setA.append(list(map(int,input().split()))[1:])
aTuple.append((a[i],i))
aTuple.sort(reverse = True)
ans = 0
color = []
colorDict = {}
for i in range(n):
color.append(i)
colorDict[i] = [i]
for i in range(m):
currentSet = []
for elem in setA[aTuple[i][1]]:
currentSet.append((b[elem - 1],elem))
if not currentSet:
continue
currentSet.sort(reverse = True)
currentElem = currentSet[0][1] - 1
for j in range(1,len(currentSet)):
currentElem2 = currentSet[j][1] - 1
if color[currentElem] != color[currentElem2]:
if len(colorDict[color[currentElem]]) > len(colorDict[color[currentElem2]]):
deletableColor = color[currentElem2]
newColor = color[currentElem]
for elem in colorDict[deletableColor]:
colorDict[newColor].append(elem)
color[elem] = newColor
del colorDict[deletableColor]
else:
deletableColor = color[currentElem]
newColor = color[currentElem2]
for elem in colorDict[deletableColor]:
colorDict[newColor].append(elem)
color[elem] = newColor
del colorDict[deletableColor]
else:
ans += aTuple[i][0]
ans += currentSet[j][0]
print(ans)
# 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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | instruction | 0 | 16,992 | 13 | 33,984 |
No | output | 1 | 16,992 | 13 | 33,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given m sets of integers A_1, A_2, β¦, A_m; elements of these sets are integers between 1 and n, inclusive.
There are two arrays of positive integers a_1, a_2, β¦, a_m and b_1, b_2, β¦, b_n.
In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that.
You can make several (maybe none) operations (some sets can become empty).
After that, you will make an edge-colored undirected graph consisting of n vertices. For each set A_i you will add an edge (x, y) with color i for all x, y β A_i and x < y. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.
You call a cycle i_1 β e_1 β i_2 β e_2 β β¦ β i_k β e_k β i_1 (e_j is some edge connecting vertices i_j and i_{j+1} in this graph) rainbow if all edges on it have different colors.
Find the minimum number of coins you should pay to get a graph without rainbow cycles.
Input
The first line contains two integers m and n (1 β€ m, n β€ 10^5), the number of sets and the number of vertices in the graph.
The second line contains m integers a_1, a_2, β¦, a_m (1 β€ a_i β€ 10^9).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ 10^9).
In the each of the next of m lines there are descriptions of sets. In the i-th line the first integer s_i (1 β€ s_i β€ n) is equal to the size of A_i. Then s_i integers follow: the elements of the set A_i. These integers are from 1 to n and distinct.
It is guaranteed that the sum of s_i for all 1 β€ i β€ m does not exceed 2 β
10^5.
Output
Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.
Examples
Input
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
Output
11
Input
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
Output
66
Note
In the first test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 5 coins for that.
* Delete element 1 from set 2. You should pay a_2 + b_1 = 6 coins for that.
You pay 11 coins in total. After these operations, the first and the second sets will be equal to \{2\} and the third set will be equal to \{1, 2\}.
So, the graph will consist of one edge (1, 2) of color 3.
In the second test, you can make such operations:
* Delete element 1 from set 1. You should pay a_1 + b_1 = 11 coins for that.
* Delete element 4 from set 2. You should pay a_2 + b_4 = 13 coins for that.
* Delete element 7 from set 3. You should pay a_3 + b_7 = 13 coins for that.
* Delete element 4 from set 4. You should pay a_4 + b_4 = 16 coins for that.
* Delete element 7 from set 6. You should pay a_6 + b_7 = 13 coins for that.
You pay 66 coins in total.
After these operations, the sets will be:
* \{2, 3\};
* \{1\};
* \{1, 3\};
* \{3\};
* \{3, 4, 5, 6, 7\};
* \{5\};
* \{8\}.
We will get the graph:
<image>
There are no rainbow cycles in it.
Submitted Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
def main():
m,n = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
setA = []
aTuple = []
for i in range(m):
setA.append(list(map(int,input().split()))[1:])
aTuple.append((a[i],i))
aTuple.sort(reverse = True)
ans = 0
color = []
colorDict = {}
for i in range(n):
color.append(i)
colorDict[i] = [i]
for i in range(m):
currentSet = []
for elem in setA[aTuple[i][1]]:
currentSet.append((b[elem - 1],elem))
if not currentSet:
continue
currentSet.sort(reverse = True)
currentElem = currentSet[0][1] - 1
for j in range(1,len(currentSet)):
currentElem2 = currentSet[j][1] - 1
if color[currentElem] != color[currentElem2]:
if len(colorDict[color[currentElem]]) > len(colorDict[color[currentElem2]]):
deletableColor = color[currentElem2]
newColor = color[currentElem]
for elem in colorDict[deletableColor]:
colorDict[newColor].append(elem)
color[elem] = newColor
del colorDict[deletableColor]
else:
deletableColor = color[currentElem]
newColor = color[currentElem2]
for elem in colorDict[deletableColor]:
colorDict[newColor].append(elem)
color[elem] = newColor
del colorDict[deletableColor]
else:
ans += aTuple[i][0]
ans += b[currentElem2]
print(ans)
# 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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | instruction | 0 | 16,993 | 13 | 33,986 |
No | output | 1 | 16,993 | 13 | 33,987 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | instruction | 0 | 17,424 | 13 | 34,848 |
Tags: implementation, trees
Correct Solution:
```
count = int(input())
tree = {}
for _ in range(count - 1):
edge = input().split()
if edge[0] in tree:
tree[edge[0]].append(edge[1])
else:
tree[edge[0]] = [edge[1]]
if edge[1] in tree:
tree[edge[1]].append(edge[0])
else:
tree[edge[1]] = [edge[0]]
centroid = []
leaves = []
for key, adj in tree.items():
if len(adj) == 1:
leaves.append(key)
elif len(adj) >= 3 and len(centroid) == 0:
centroid.append(key)
elif len(adj) >= 3 and len(centroid) > 0:
print("No")
break
else:
print("Yes")
if len(centroid) == 0:
print(1)
print(leaves[0] + " " + leaves[1])
else:
print(len(leaves))
for leaf in leaves:
print(leaf + " " + centroid[0])
``` | output | 1 | 17,424 | 13 | 34,849 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | instruction | 0 | 17,425 | 13 | 34,850 |
Tags: implementation, trees
Correct Solution:
```
n = int(input())
deg = [0 for i in range(1,n+1)]
odeg = []
for i in range(n-1):
[a, b] = [int(i) for i in input().split()]
deg[a-1] += 1
deg[b-1] += 1
mxdv = 0
mxd = 0
for i in range(n):
if deg[i]>mxd:
mxd=deg[i]
mxdv=i
if deg[i]==1:
odeg.append(i+1)
mxdv += 1
deg = sorted(deg)
if deg[n-2] > 2:
print("No")
else:
print("Yes")
c = len(odeg)
if mxdv in odeg:
c -= 1
print(c)
for v in odeg:
if v != mxdv:
print(str(mxdv) + ' ' + str(v))
``` | output | 1 | 17,425 | 13 | 34,851 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | instruction | 0 | 17,426 | 13 | 34,852 |
Tags: implementation, trees
Correct Solution:
```
n = int(input())
dic = {}
for i in range(n):
dic.update({i+1:0})
for i in range(n-1):
s = input().split()
dic[int(s[0])]+=1
dic[int(s[1])]+=1
cl = []
count1=0
count2=0
count3=0
for x in dic.keys():
if dic[x]==1:
count1+=1
cl.append(x)
elif dic[x]==2:
count2+=1
else:
count3+=1
p = x
if count3==0:
print('Yes')
print(1)
print('{} {}'.format(cl[0], cl[1]))
elif count3==1:
print('Yes')
print(count1)
for i in range(1, n+1):
if i!=p and dic[i]==1:
print('{} {}'.format(p, i))
else:
print('No')
``` | output | 1 | 17,426 | 13 | 34,853 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | instruction | 0 | 17,427 | 13 | 34,854 |
Tags: implementation, trees
Correct Solution:
```
import sys
import filecmp
import math
FILE_IO = False
CURR_PATH = []
list_of_connections = [[] for _ in range(100001)]
def dfs(vertex):
visited, stack = set(), [vertex]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(set(list_of_connections[vertex]) - visited)
if (len(set(list_of_connections[vertex]) - visited) == 0):
CURR_PATH.append(vertex)
if FILE_IO:
input_stream = open('input_test.txt')
sys.stdout = open('current_output2.txt', 'w')
else:
input_stream = sys.stdin
n = int(input_stream.readline())
for _ in range(n-1):
input_list = input_stream.readline().split()
start , end = int(input_list[0]),int(input_list[1])
list_of_connections[start].append(end)
list_of_connections[end].append(start)
max_edges = None
max_less_then_3 = None
no = False
for ind, edges in enumerate(list_of_connections):
current_len = len(edges)
if current_len > 2:
if max_less_then_3 is not None:
print('No')
exit()
else:
max_less_then_3 = ind
if max_less_then_3 is None:
max_less_then_3 = 1
print('Yes')
root = max_less_then_3
paths = []
visited = [False] * 100001
dfs(root)
print(len(CURR_PATH))
for node in CURR_PATH:
print(str(root) + " "+ str(node))
# if FILE_IO:
# assert filecmp.cmp('current_output.txt','expected_output.txt',shallow=False) == True
``` | output | 1 | 17,427 | 13 | 34,855 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | instruction | 0 | 17,428 | 13 | 34,856 |
Tags: implementation, trees
Correct Solution:
```
#!/usr/bin/env python3
n = int(input().strip())
degs = [0 for _ in range(n)]
for _ in range(n - 1):
[u, v] = map(int, input().strip().split())
degs[u - 1] += 1
degs[v - 1] += 1
ni = [None, [], [], []]
for v, d in enumerate(degs):
dd = min(d, 3)
ni[dd].append(v)
if len(ni[3]) > 1:
print ('No')
elif len(ni[3]) == 1:
print ('Yes')
print (len(ni[1]))
u = ni[3][0]
for v in ni[1]:
print (u + 1, v + 1)
else: # ni[3] == []
print ('Yes')
print (1)
print (ni[1][0] + 1, ni[1][1] + 1)
``` | output | 1 | 17,428 | 13 | 34,857 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | instruction | 0 | 17,429 | 13 | 34,858 |
Tags: implementation, trees
Correct Solution:
```
import collections;
def getIntList():
return list(map(int, input().split()));
def getTransIntList(n):
first=getIntList();
m=len(first);
result=[[0]*n for _ in range(m)];
for i in range(m):
result[i][0]=first[i];
for j in range(1, n):
curr=getIntList();
for i in range(m):
result[i][j]=curr[i];
return result;
n=int(input());
def solve():
nearVerts = [0] * (n + 1);
for i in range(n-1):
u, v=getIntList();
nearVerts[u]+=1;
nearVerts[v]+=1;
result=-1;
count3=0;
ways=[];
mainVert=-1;
v1=-1;
v2=-1;
oneVersts=collections.deque();
for i in range(n+1):
nears=nearVerts[i];
if nears==1:
result+=1;
oneVersts.append(i);
elif nears>=3:
mainVert=i;
count3+=1;
if count3>1:
result=-1;
break;
if result==-1:
print("No");
else:
print("Yes")
print(result);
v1=oneVersts.pop();
v2=oneVersts.pop();
print(v1, v2);
l=len(oneVersts);
for _ in range(l):
print(oneVersts.pop(), mainVert);
solve();
``` | output | 1 | 17,429 | 13 | 34,859 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | instruction | 0 | 17,430 | 13 | 34,860 |
Tags: implementation, trees
Correct Solution:
```
n=int(input())
d={}
for i in range(n-1):
a,b=map(int,input().split())
d[a],d[b]=d.get(a,0)+1,d.get(b,0)+1
root=[]
lev=[]
for a, b in d.items():
if b>2: root.append(a)
if b==1: lev.append(a)
if len(root)>1:
print("No")
else:
if len(root)==0:
print("Yes")
print("1")
print(*lev)
else:
print("Yes")
print(d[root[0]])
for a in lev:
print(root[0],a)
``` | output | 1 | 17,430 | 13 | 34,861 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | instruction | 0 | 17,431 | 13 | 34,862 |
Tags: implementation, trees
Correct Solution:
```
#Zad
from collections import Counter
n=int(input())
tree=[]
for i in range(n-1):
tree.extend(list(map(int,input().split())))
ans=Counter(tree)
if ans.most_common(2)[1][1]>2: print('No')
else:
print('Yes')
if n==2:
print(1)
print('1 2')
else:
if ans.most_common(1)[0][1]==2:
print(1)
print(ans.most_common()[-2][0], ans.most_common()[-1][0])
else:
center=ans.most_common(1)[0][0]
kraya=[n[0] for n in ans.most_common() if n[1]==1]
print(len(kraya))
for i in kraya:
print(center, i)
``` | output | 1 | 17,431 | 13 | 34,863 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
Submitted Solution:
```
d = {}
n = int(input())
for _ in range(n-1):
a, b = map(int, input().split())
d[a] = d.get(a, 0) + 1
d[b] = d.get(b, 0) + 1
zz = list(filter(lambda x: d[x] > 2, d))
z = len(zz)
y = list(filter(lambda x: d[x] == 1, d))
if z > 1:
print("No")
elif z == 0:
print("Yes")
print(1)
print(*y)
else:
print("Yes")
print(len(y))
for v in y:
print(zz[0], v)
``` | instruction | 0 | 17,432 | 13 | 34,864 |
Yes | output | 1 | 17,432 | 13 | 34,865 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
Submitted Solution:
```
import os, sys
from io import BytesIO, IOBase
def main():
n = rint()
deg = [0] * n
if n == 2:
exit(print(f'Yes\n1\n1 2'))
for i in range(n - 1):
u, v = rints()
deg[u - 1] += 1
deg[v - 1] += 1
ix = deg.index(max(deg))
if deg[ix] < 3 or deg.count(1) + deg.count(2) == n - 1:
print(f'Yes\n{deg.count(1)}')
for i in range(n):
if deg[i] == 1:
print(i + 1, ix + 1)
else:
print('No')
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")
BUFSIZE = 8192
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
rstr = lambda: input().strip()
rstrs = lambda: [str(x) for x in input().split()]
rstr_2d = lambda n: [rstr() for _ in range(n)]
rint = lambda: int(input())
rints = lambda: [int(x) for x in input().split()]
rint_2d = lambda n: [rint() for _ in range(n)]
rints_2d = lambda n: [rints() for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
if __name__ == '__main__':
main()
``` | instruction | 0 | 17,433 | 13 | 34,866 |
Yes | output | 1 | 17,433 | 13 | 34,867 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
Submitted Solution:
```
n = int(input())
deg = [0]*100005
leaves = []
for i in range(1,n):
a,b = map(int, input().split())
deg[a]+=1
deg[b]+=1
cnt = 0
mxdeg = 0
root = 0
for j in range(1,n+1):
if deg[j]>mxdeg:
mxdeg = deg[j]
root = j
if deg[j] == 1:
leaves.append(j)
if deg[j] > 2:
cnt+=1
if cnt>1:
print("No")
exit()
print("Yes")
m = 0
for it in leaves:
if it != root:
m+=1
print(m)
for it2 in leaves:
if it2 != root:
print(root,it2)
``` | instruction | 0 | 17,434 | 13 | 34,868 |
Yes | output | 1 | 17,434 | 13 | 34,869 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
Submitted Solution:
```
MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
if __name__=="__main__":
n=ii()
l=[[] for i in range(n)]
deg=[0]*n
for _ in range(n-1):
a,b=f()
l[a-1].append(b-1)
l[b-1].append(a-1)
deg[a-1]+=1
deg[b-1]+=1
mx=max(deg)
if mx==1:
print('Yes')
print(1)
print(mx+1,l[mx][0]+1)
exit()
if (mx>2 and deg.count(mx)>1) or any(not i in [mx,0,1,2] for i in deg):
exit(print('No'))
ind=deg.index(mx)
path=[]
for i in range(n):
if len(l[i])==1:
path.append(i)
print('Yes')
print(len(path))
for i in path:
print(ind+1,i+1)
``` | instruction | 0 | 17,435 | 13 | 34,870 |
Yes | output | 1 | 17,435 | 13 | 34,871 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
Submitted Solution:
```
from collections import deque
def bfs(start,graph):
explored = set()
queue = deque([start])
levels = {}
levels[start]= 0
visited = {start}
while queue:
node = queue.popleft()
explored.add(node)
neighbours = graph[node]
for neighbour in neighbours:
if neighbour not in visited:
queue.append(neighbour)
visited.add(neighbour)
levels[neighbour]= levels[node]+1
return levels
n = int(input())
s = set()
f = 0
d = {}
ans = []
for _ in range(n-1):
a,b = map(int,input().split())
ans.append((a,b))
if not f:
s.add(a)
s.add(b)
f = 1
else:
z = set()
z.add(a)
z.add(a)
s = s&z
if a in d:
d[a].append(b)
else:
d[a] = [b]
if b in d:
d[b].append(a)
else:
d[b] = [a]
w = bfs(1,d)
m = -1
e = -1
for i in w:
if w[i] > m:
m = w[i]
e = i
g = bfs(e,d)
m = -1
for i in g:
if g[i] > m:
m = g[i]
if len(s) == 1 or m == n-1:
print("Yes")
print(n-1)
for i in ans:
print(*i)
else:
print("No")
``` | instruction | 0 | 17,436 | 13 | 34,872 |
No | output | 1 | 17,436 | 13 | 34,873 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def local_input():
from pcm.utils import set_stdin
import sys
if len(sys.argv) == 1:
set_stdin(os.path.dirname(__file__) + '/test/' + 'sample-1.in')
import sys
import os
from sys import stdin, stdout
import time
import re
from pydoc import help
import string
import math
# import numpy as np # codeforceγ§γ―δ½Ώγγͺγ
from operator import itemgetter
from collections import Counter
from collections import deque
from collections import defaultdict as dd
import fractions
from heapq import heappop, heappush, heapify
import array
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy as dcopy
import itertools
sys.setrecursionlimit(10**7)
INF = 10**20
GOSA = 1.0 / 10**10
MOD = 10**9+7
ALPHABETS = [chr(i) for i in range(ord('a'), ord('z')+1)] # can also use string module
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def DP(N, M, first): return [[first] * M for n in range(N)]
def DP3(N, M, L, first): return [[[first] * L for n in range(M)] for _ in range(N)]
def solve():
global T, N, g
N = int(input())
T = [[] for _ in range(N)]
for n in range(N-1):
# a, b = map(lambda x:int(x)-1, input().split())
a, b = map(lambda x:int(x)-1, stdin.readline().rstrip().split())
T[a].append(b)
T[b].append(a)
# print(T)
if __name__ == "__main__":
try:
local_input()
except:
pass
solve()
``` | instruction | 0 | 17,437 | 13 | 34,874 |
No | output | 1 | 17,437 | 13 | 34,875 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
Submitted Solution:
```
MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
if __name__=="__main__":
n=ii()
l=[[] for i in range(n)]
deg=[0]*n
for _ in range(n-1):
a,b=f()
l[a-1].append(b-1)
l[b-1].append(a-1)
deg[a-1]+=1
deg[b-1]+=1
mx=max(deg)
if (mx>2 and deg.count(mx)>1) or any(not i in [mx,0,1,2] for i in deg):
exit(print('No'))
ind=deg.index(mx)
path=[]
for i in range(n):
if len(l[i])==1:
path.append(i)
print('Yes')
print(len(path))
for i in path:
print(ind+1,i+1)
``` | instruction | 0 | 17,438 | 13 | 34,876 |
No | output | 1 | 17,438 | 13 | 34,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!
He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!
The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.
Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.
Input
The first line contains a single integer n (2 β€ n β€ 10^{5}) the number of nodes in the tree.
Each of the next n - 1 lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i) β the edges of the tree. It is guaranteed that the given edges form a tree.
Output
If there are no decompositions, print the only line containing "No".
Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m.
Each of the next m lines should contain two integers u_i, v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i.
Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.
If there are multiple decompositions, print any.
Examples
Input
4
1 2
2 3
3 4
Output
Yes
1
1 4
Input
6
1 2
2 3
3 4
2 5
3 6
Output
No
Input
5
1 2
1 3
1 4
1 5
Output
Yes
4
1 2
1 3
1 4
1 5
Note
The tree from the first example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
The tree from the second example is shown on the picture below: <image> We can show that there are no valid decompositions of this tree.
The tree from the third example is shown on the picture below: <image> The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.
Submitted Solution:
```
"Codeforces Round #623 (Div. 2, based on VK Cup 2019-2020 - Elimination Round, Engine)"
"B. Homecoming"
# y=int(input())
# for i in range(y):
# a,b,p=map(int,input().split())
# s=list(input())
# l=len(s)
# #A-65
# if p<a and p<b:
# print(l)
# continue
# q=s[-1]
# if s.count(q)==l:
# if q=="A" and p>=a:
# print(1)
# elif q=="B" and p>=b:
# print(1)
# else:
# print(l)
# continue
# f=0
# for j in range(0,l):
# t=l-1-j
# qs=chr(131-ord(q))
# print("--->",t,q,s[t],p)
# if (p<a and p<b) or (p<1):
# if t==0:
# print(t+1)
# f=1
# break
# print(t+2)
# f=1
# break
# elif j==0 and q==s[-2]:
# if q=="A":
# p-=a
# else:
# p-=b
# elif j==0 and qs==s[-2]:
# if q=="A":
# p-=b
# else:
# p-=a
# q=qs
# elif j==l-1:
# pass
# elif s[t]==qs and s[t-1]==q:
# if qs=="A":
# p-=a
# else:
# p-=b
# q=qs
# if f==0:
# print(1)
"Manthan, Codefest 18 (rated, Div. 1 + Div. 2)"
"C. Equalize"
# y=int(input())
# a=input()
# b=input()
# q=[]
# for i in range(y):
# if a[i]!=b[i]:
# q.append(i)
# l=len(q)
# # print(q,l)
# i=0
# ans=0
# while i<l:
# # print(i,q[i],ans)
# if i==l-1:
# ans+=0
# break
# if abs(q[i]-q[i+1])==1 and a[q[i]]!=a[q[i+1]]:
# ans+=1
# i+=2
# else:
# i+=1
# ans=ans+(l-(2*ans))
# print(ans)
"Avito Code Challenge 2018"
"C. Useful Decomposition"
y=int(input())
t=[]
for i in range(y):
t.append([])
# print(t)
for i in range(y-1):
a,b=map(int,input().split())
t[a-1].append(b)
t[b-1].append(a)
# print(t)
b=0
indx=0
for zx in range(y):
if len(t[zx])>2:
b+=1
indx=zx
if b>1:
print("No")
else:
print("Yes")
if b==0:
print(1,len(t))
else:
for i in range(y):
if len(t[i])==1:
print(indx+1,i+1)
# for i in t[indx]:
# j=i-1
# while len(t1[j])>1:
# if len(t1[j])==2:
# j=sum(t1[j])-2-j
# r=j+1
# print(indx+1,r)
``` | instruction | 0 | 17,439 | 13 | 34,878 |
No | output | 1 | 17,439 | 13 | 34,879 |
Provide a correct Python 3 solution for this coding contest problem.
You are a judge of a programming contest. You are preparing a dataset for a graph problem to seek for the cost of the minimum cost path. You've generated some random cases, but they are not interesting. You want to produce a dataset whose answer is a desired value such as the number representing this year 2010. So you will tweak (which means 'adjust') the cost of the minimum cost path to a given value by changing the costs of some edges. The number of changes should be made as few as possible.
A non-negative integer c and a directed graph G are given. Each edge of G is associated with a cost of a non-negative integer. Given a path from one node of G to another, we can define the cost of the path as the sum of the costs of edges constituting the path. Given a pair of nodes in G, we can associate it with a non-negative cost which is the minimum of the costs of paths connecting them.
Given a graph and a pair of nodes in it, you are asked to adjust the costs of edges so that the minimum cost path from one node to the other will be the given target cost c. You can assume that c is smaller than the cost of the minimum cost path between the given nodes in the original graph.
For example, in Figure G.1, the minimum cost of the path from node 1 to node 3 in the given graph is 6. In order to adjust this minimum cost to 2, we can change the cost of the edge from node 1 to node 3 to 2. This direct edge becomes the minimum cost path after the change.
For another example, in Figure G.2, the minimum cost of the path from node 1 to node 12 in the given graph is 4022. In order to adjust this minimum cost to 2010, we can change the cost of the edge from node 6 to node 12 and one of the six edges in the right half of the graph. There are many possibilities of edge modification, but the minimum number of modified edges is 2.
Input
The input is a sequence of datasets. Each dataset is formatted as follows.
n m c
f1 t1 c1
f2 t2 c2
.
.
.
fm tm cm
<image> | <image>
---|---
Figure G.1: Example 1 of graph
|
Figure G.2: Example 2 of graph
The integers n, m and c are the number of the nodes, the number of the edges, and the target cost, respectively, each separated by a single space, where 2 β€ n β€ 100, 1 β€ m β€ 1000 and 0 β€ c β€ 100000.
Each node in the graph is represented by an integer 1 through n.
The following m lines represent edges: the integers fi, ti and ci (1 β€ i β€ m) are the originating node, the destination node and the associated cost of the i-th edge, each separated by a single space. They satisfy 1 β€ fi, ti β€ n and 0 β€ ci β€ 10000. You can assume that fi β ti and (fi, ti) β (fj, tj) when i β j.
You can assume that, for each dataset, there is at least one path from node 1 to node n, and that the cost of the minimum cost path from node 1 to node n of the given graph is greater than c.
The end of the input is indicated by a line containing three zeros separated by single spaces.
Output
For each dataset, output a line containing the minimum number of edges whose cost(s) should be changed in order to make the cost of the minimum cost path from node 1 to node n equal to the target cost c. Costs of edges cannot be made negative. The output should not contain any other extra characters.
Example
Input
3 3 3
1 2 3
2 3 3
1 3 8
12 12 2010
1 2 0
2 3 3000
3 4 0
4 5 3000
5 6 3000
6 12 2010
2 7 100
7 8 200
8 9 300
9 10 400
10 11 500
11 6 512
10 18 1
1 2 9
1 3 2
1 4 6
2 5 0
2 6 10
2 7 2
3 5 10
3 6 3
3 7 10
4 7 6
5 8 10
6 8 2
6 9 11
7 9 3
8 9 9
8 10 8
9 10 1
8 2 1
0 0 0
Output
1
2
3 | instruction | 0 | 17,642 | 13 | 35,284 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f(n,m,c):
e = collections.defaultdict(list)
for _ in range(m):
a,b,d = LI()
e[a].append((b,d))
def search(s):
d = collections.defaultdict(lambda: inf)
s = (0, s)
d[s] = 0
q = []
heapq.heappush(q, (0, s))
v = collections.defaultdict(bool)
r = inf
while len(q):
k, u = heapq.heappop(q)
if v[u]:
continue
v[u] = True
cc, uu = u
if uu == n and r > cc:
r = cc
if cc >= r:
continue
for uv, ud in e[uu]:
if k + ud <= c:
vv = (cc, uv)
vd = k + ud
if not v[vv] and d[vv] > vd:
d[vv] = vd
heapq.heappush(q, (vd, vv))
if cc < r:
vv = (cc+1, uv)
vd = k
if not v[vv] and d[vv] > vd:
d[vv] = vd
heapq.heappush(q, (vd, vv))
return r
r = search(1)
return r
while 1:
n,m,c = LI()
if n == 0:
break
rr.append(f(n,m,c))
return '\n'.join(map(str,rr))
print(main())
``` | output | 1 | 17,642 | 13 | 35,285 |
Provide a correct Python 3 solution for this coding contest problem.
You are a judge of a programming contest. You are preparing a dataset for a graph problem to seek for the cost of the minimum cost path. You've generated some random cases, but they are not interesting. You want to produce a dataset whose answer is a desired value such as the number representing this year 2010. So you will tweak (which means 'adjust') the cost of the minimum cost path to a given value by changing the costs of some edges. The number of changes should be made as few as possible.
A non-negative integer c and a directed graph G are given. Each edge of G is associated with a cost of a non-negative integer. Given a path from one node of G to another, we can define the cost of the path as the sum of the costs of edges constituting the path. Given a pair of nodes in G, we can associate it with a non-negative cost which is the minimum of the costs of paths connecting them.
Given a graph and a pair of nodes in it, you are asked to adjust the costs of edges so that the minimum cost path from one node to the other will be the given target cost c. You can assume that c is smaller than the cost of the minimum cost path between the given nodes in the original graph.
For example, in Figure G.1, the minimum cost of the path from node 1 to node 3 in the given graph is 6. In order to adjust this minimum cost to 2, we can change the cost of the edge from node 1 to node 3 to 2. This direct edge becomes the minimum cost path after the change.
For another example, in Figure G.2, the minimum cost of the path from node 1 to node 12 in the given graph is 4022. In order to adjust this minimum cost to 2010, we can change the cost of the edge from node 6 to node 12 and one of the six edges in the right half of the graph. There are many possibilities of edge modification, but the minimum number of modified edges is 2.
Input
The input is a sequence of datasets. Each dataset is formatted as follows.
n m c
f1 t1 c1
f2 t2 c2
.
.
.
fm tm cm
<image> | <image>
---|---
Figure G.1: Example 1 of graph
|
Figure G.2: Example 2 of graph
The integers n, m and c are the number of the nodes, the number of the edges, and the target cost, respectively, each separated by a single space, where 2 β€ n β€ 100, 1 β€ m β€ 1000 and 0 β€ c β€ 100000.
Each node in the graph is represented by an integer 1 through n.
The following m lines represent edges: the integers fi, ti and ci (1 β€ i β€ m) are the originating node, the destination node and the associated cost of the i-th edge, each separated by a single space. They satisfy 1 β€ fi, ti β€ n and 0 β€ ci β€ 10000. You can assume that fi β ti and (fi, ti) β (fj, tj) when i β j.
You can assume that, for each dataset, there is at least one path from node 1 to node n, and that the cost of the minimum cost path from node 1 to node n of the given graph is greater than c.
The end of the input is indicated by a line containing three zeros separated by single spaces.
Output
For each dataset, output a line containing the minimum number of edges whose cost(s) should be changed in order to make the cost of the minimum cost path from node 1 to node n equal to the target cost c. Costs of edges cannot be made negative. The output should not contain any other extra characters.
Example
Input
3 3 3
1 2 3
2 3 3
1 3 8
12 12 2010
1 2 0
2 3 3000
3 4 0
4 5 3000
5 6 3000
6 12 2010
2 7 100
7 8 200
8 9 300
9 10 400
10 11 500
11 6 512
10 18 1
1 2 9
1 3 2
1 4 6
2 5 0
2 6 10
2 7 2
3 5 10
3 6 3
3 7 10
4 7 6
5 8 10
6 8 2
6 9 11
7 9 3
8 9 9
8 10 8
9 10 1
8 2 1
0 0 0
Output
1
2
3 | instruction | 0 | 17,643 | 13 | 35,286 |
"Correct Solution:
```
import sys
from heapq import heappush, heappop
readline = sys.stdin.buffer.readline
write = sys.stdout.write
def solve():
N, M, C = map(int, readline().split())
if N == M == C == 0:
return False
G = [[] for i in range(N)]
for i in range(M):
f, t, c = map(int, readline().split()); f -= 1; t -= 1
G[f].append((t, c))
INF = 10**18
dist = [[INF]*(N+1) for i in range(N)]
que = [(0, 0, 0)]
dist[0][0] = 0
while que:
cost, v, k = heappop(que)
if dist[v][k] < cost:
continue
for w, d in G[v]:
if cost + d < dist[w][k]:
dist[w][k] = cost + d
heappush(que, (cost + d, w, k))
if k < N and cost < dist[w][k+1]:
dist[w][k+1] = cost
heappush(que, (cost, w, k+1))
for k in range(N+1):
if dist[N-1][k] <= C:
write("%d\n" % k)
break
return True
while solve():
...
``` | output | 1 | 17,643 | 13 | 35,287 |
Provide a correct Python 3 solution for this coding contest problem.
An undirected graph is given. Each edge of the graph disappears with a constant probability. Calculate the probability with which the remained graph is connected.
Input
The first line contains three integers N (1 \leq N \leq 14), M (0 \leq M \leq 100) and P (0 \leq P \leq 100), separated by a single space. N is the number of the vertices and M is the number of the edges. P is the probability represented by a percentage.
The following M lines describe the edges. Each line contains two integers v_i and u_i (1 \leq u_i, v_i \leq N). (u_i, v_i) indicates the edge that connects the two vertices u_i and v_i.
Output
Output a line containing the probability with which the remained graph is connected. Your program may output an arbitrary number of digits after the decimal point. However, the absolute error should be 10^{-9} or less.
Examples
Input
3 3 50
1 2
2 3
3 1
Output
0.500000000000
Input
3 3 10
1 2
2 3
3 1
Output
0.972000000000
Input
4 5 50
1 2
2 3
3 4
4 1
1 3
Output
0.437500000000 | instruction | 0 | 17,646 | 13 | 35,292 |
"Correct Solution:
```
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, M, P = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(M):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
N1 = 1 << N
bc = [0]*N1
for i in range(1, N1):
bc[i] = bc[i ^ (i & -i)] + 1
ec = [0]*N1
for state in range(1, N1):
c = 0
for v in range(N):
if (state & (1 << v)) == 0:
continue
for w in G[v]:
if (state & (1 << w)) == 0:
continue
c += 1
ec[state] = c >> 1
N0 = 1 << (N-1)
dp = [0]*N1
dp[1] = 1
for s0 in range(1, N0):
state0 = (s0 << 1) | 1
state1 = (state0-1) & state0
v = 0
while state1:
if state1 & 1:
k = ec[state0] - ec[state1] - ec[state0 ^ state1]
v += dp[state1] * (P/100)**k
state1 = (state1 - 1) & state0
dp[state0] = 1 - v
write("%.16f\n" % dp[N1-1])
solve()
``` | output | 1 | 17,646 | 13 | 35,293 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 17,774 | 13 | 35,548 |
Tags: math, number theory, trees
Correct Solution:
```
from collections import Counter
def gcd(x, y):
while y != 0:
(x, y) = (y, x % y)
return x
def main():
n=int(input())
arr=readIntArr()
adj=[[] for _ in range(n)]
for _ in range(n-1):
u,v=readIntArr()
u-=1;v-=1
adj[u].append(v)
adj[v].append(u)
ans=0
visited=[False]*n
visited[0]=True
stack=[[0,Counter()]] # [node,parentGCDs]
while stack:
node,parentGCDs=stack.pop()
newGCDs=Counter()
ans+=arr[node]
ans%=MOD
newGCDs[arr[node]]+=1
for k,v in parentGCDs.items():
g=gcd(arr[node],k)
ans+=(g*v)%MOD
ans%=MOD
newGCDs[g]+=v
for nex in adj[node]:
if visited[nex]==False: # not parent
visited[nex]=True
stack.append([nex,newGCDs])
print(ans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(i,j):
print('? {} {}'.format(i,j))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(' '.join([str(x) for x in ans])))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main()
``` | output | 1 | 17,774 | 13 | 35,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 17,775 | 13 | 35,550 |
Tags: math, number theory, trees
Correct Solution:
```
from math import gcd
from collections import deque
from bisect import bisect_left
from sys import setrecursionlimit
MOD = 1000000007
def modInt(mod):
class ModInt:
def __init__(self, value):
self.value = value % mod
def __int__(self):
return self.value
def __eq__(self, other):
return self.value == other.value
def __hash__(self):
return hash(self.value)
def __add__(self, other):
return ModInt(self.value + int(other))
def __sub__(self, other):
return ModInt(self.value - int(other))
def __mul__(self, other):
return ModInt(self.value * int(other))
def __floordiv__(self, other):
return ModInt(self.value // int(other))
def __truediv__(self, other):
return ModInt(self.value * pow(int(other), mod - 2, mod))
return ModInt
ModInt = modInt(MOD)
def main():
n = int(input())
setrecursionlimit(n+100)
xx = [0] + [int(x) for x in input().split()]
edges = []
neighbors = [[] for _ in range(n+1)]
for _ in range(n-1):
v1, v2 = [int(x) for x in input().split()]
neighbors[v1].append(v2)
neighbors[v2].append(v1)
visited = [False] * (n+1)
dq = deque()
dq.append((1,[]))
sum = ModInt(0)
while dq:
u,gcds = dq.popleft()
gcdns = [[xx[u], 1]]
sum = (sum + xx[u])
for g, c in gcds:
gcdn = gcd(xx[u], g)
sum = (sum + gcdn*c)
if gcdn == gcdns[-1][0]:
gcdns[-1][1] += c
else:
gcdns.append([gcdn, c])
visited[u] = True
for v in neighbors[u]:
if not visited[v]:
dq.append((v, gcdns))
print(int(sum))
if __name__ == "__main__":
main()
``` | output | 1 | 17,775 | 13 | 35,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 17,776 | 13 | 35,552 |
Tags: math, number theory, trees
Correct Solution:
```
n = int(input())
beauty = list(map(int, input().strip().split()))
tree = [[] for i in range(n)]
mod = 1000000007
used = [False for i in range(n)]
def gcd(a,b):
mn = min(a,b)
mx = max(a,b)
if mn == 0:
return mx
md = mx%mn
if md == 0:
return mn
else:
return gcd(mn, md)
for i in range(n-1):
a,b = map(int, input().strip().split())
tree[a-1].append(b-1)
tree[b-1].append(a-1)
segment_vals = [{} for i in range(n)]
ans = beauty[0]
segment_vals[0][beauty[0]] = 1
cur_nodes = [0]
used[0] = True
while 1:
new_nodes = []
for node in cur_nodes:
for potential_new in tree[node]:
if used[potential_new] == False:
used[potential_new] = True
new_nodes.append(potential_new)
new_beauty = beauty[potential_new]
segment_vals[potential_new][new_beauty] = 1
for g in segment_vals[node].keys():
segment_gcd = gcd(new_beauty,g)
segment_vals[potential_new][segment_gcd] = segment_vals[potential_new].get(segment_gcd,0) + segment_vals[node][g]
for k in segment_vals[potential_new].keys():
ans += k*segment_vals[potential_new][k]
ans = ans % mod
if len(new_nodes) == 0:
break
else:
cur_nodes = new_nodes
print(ans)
``` | output | 1 | 17,776 | 13 | 35,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 17,777 | 13 | 35,554 |
Tags: math, number theory, trees
Correct Solution:
```
from math import gcd
from collections import deque
from bisect import bisect_left
from sys import setrecursionlimit
MOD = 1000000007
def main():
n = int(input())
setrecursionlimit(n+100)
xx = [0] + [int(x) for x in input().split()]
edges = []
for _ in range(n-1):
edge = [int(x) for x in input().split()]
edges.append(edge)
edges.append(list(reversed(edge)))
edges.sort()
visited = [False] * (n+1)
dq = deque()
dq.append((1,[]))
sum = 0
while dq:
u,gcds = dq.popleft()
gcdns = [[xx[u], 1]]
sum = (sum + xx[u]) % MOD
for g, c in gcds:
gcdn = gcd(xx[u], g)
sum = (sum + gcdn*c) % MOD
if gcdn == gcdns[-1][0]:
gcdns[-1][1] += c
else:
gcdns.append([gcdn, c])
visited[u] = True
i = bisect_left(edges, [u, 0])
if i == 2*(n-1):
continue
w, v = edges[i]
while w == u and i < 2*(n-1):
if not visited[v]:
dq.append((v, gcdns))
i+=1
if i < 2*(n-1):
w, v = edges[i]
print(sum)
if __name__ == "__main__":
main()
``` | output | 1 | 17,777 | 13 | 35,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 17,778 | 13 | 35,556 |
Tags: math, number theory, trees
Correct Solution:
```
from collections import Counter
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
def gcd(x, y):
while y != 0:
(x, y) = (y, x % y)
return x
def main():
n=int(input())
arr=readIntArr()
adj=[[] for _ in range(n)]
for _ in range(n-1):
u,v=readIntArr()
u-=1;v-=1
adj[u].append(v)
adj[v].append(u)
@bootstrap
def dfs(node,p,parentGCDs):
newGCDs=Counter()
newGCDs[arr[node]]+=1
ans[0]+=arr[node]
ans[0]%=MOD
for k,v in parentGCDs.items():
newG=gcd(arr[node],k)
ans[0]+=(newG*v)%MOD
ans[0]%=MOD
newGCDs[newG]+=v
for nex in adj[node]:
if nex!=p:
yield dfs(nex,node,newGCDs)
yield None
ans=[0]
parentGCDs=Counter()
dfs(0,-1,parentGCDs)
print(ans[0])
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(i,j):
print('? {} {}'.format(i,j))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(' '.join([str(x) for x in ans])))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
# MOD=998244353
for _abc in range(1):
main()
``` | output | 1 | 17,778 | 13 | 35,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 17,779 | 13 | 35,558 |
Tags: math, number theory, trees
Correct Solution:
```
from math import gcd
from collections import deque
from bisect import bisect_left
from sys import setrecursionlimit
MOD = 1000000007
def main():
n = int(input())
setrecursionlimit(n+100)
xx = [0] + [int(x) for x in input().split()]
edges = []
neighbors = [[] for _ in range(n+1)]
for _ in range(n-1):
v1, v2 = [int(x) for x in input().split()]
neighbors[v1].append(v2)
neighbors[v2].append(v1)
visited = [False] * (n+1)
dq = deque()
dq.append((1,[]))
sum = 0
while dq:
u,gcds = dq.popleft()
gcdns = [[xx[u], 1]]
sum = (sum + xx[u]) % MOD
for g, c in gcds:
gcdn = gcd(xx[u], g)
sum = (sum + gcdn*c) % MOD
if gcdn == gcdns[-1][0]:
gcdns[-1][1] += c
else:
gcdns.append([gcdn, c])
visited[u] = True
for v in neighbors[u]:
if not visited[v]:
dq.append((v, gcdns))
print(sum)
if __name__ == "__main__":
main()
``` | output | 1 | 17,779 | 13 | 35,559 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image> | instruction | 0 | 17,780 | 13 | 35,560 |
Tags: math, number theory, trees
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
from fractions import gcd
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+
n=ni()
l=[0]+li()
d=defaultdict(list)
for i in range(n-1):
u,v=li()
d[u].append(v)
d[v].append(u)
dp=[Counter() for i in range(n+1)]
ans=0
vis=[0]*(n+1)
q=[1]
vis[1]=1
dp[1][l[1]]=1
while q:
x=q.pop()
for i in d[x]:
if not vis[i]:
vis[i]=1
q.append(i)
for j in dp[x]:
g=gcd(j,l[i])
dp[i][g]+=dp[x][j]
for j in dp[i]:
ans=(ans+(j*dp[i][j])%mod)%mod
dp[i][l[i]]+=1
pn((ans+sum(l))%mod)
``` | output | 1 | 17,780 | 13 | 35,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image>
Submitted Solution:
```
import math
mod=10**9+7
n=int(input())
A=list(int(i) for i in input().split())
sum=0
G=[[] for i in range(n+1)]
for _ in range(n-1):
s,e=list(int(i) for i in input().split())
G[s].append(e)
for ele in A:
sum+=math.gcd(ele,ele)
#print(sum)
for i in range(1,n+1):
o=A[i-1]
L=G[i]
for ele in L:
d=math.gcd(o,A[ele-1])
sum+=d
if(len(G[ele])!=0):
P=G[ele]
for x in P:
sum+=math.gcd(d,A[x-1])
print(sum%mod)
#print(G[1])
``` | instruction | 0 | 17,781 | 13 | 35,562 |
No | output | 1 | 17,781 | 13 | 35,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image>
Submitted Solution:
```
import math
mod=10**9+7
n=int(input())
A=list(int(i) for i in input().split())
sum=0
G=[[] for i in range(n+1)]
for _ in range(n-1):
s,e=list(int(i) for i in input().split())
if(s<e):
G[s].append(e)
else:
G[e].append(s)
for ele in A:
sum+=math.gcd(ele,ele)
#print(sum)
for i in range(1,n+1):
o=A[i-1]
L=G[i]
for ele in L:
d=math.gcd(o,A[ele-1])
sum+=d
if(len(G[ele])!=0):
P=G[ele]
for x in P:
sum+=math.gcd(d,A[x-1])
print(sum%mod)
#print(G[1])
``` | instruction | 0 | 17,782 | 13 | 35,564 |
No | output | 1 | 17,782 | 13 | 35,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image>
Submitted Solution:
```
from math import gcd
from collections import deque
from bisect import bisect_left
from sys import setrecursionlimit
MOD = 1000000007
def main():
n = int(input())
setrecursionlimit(n+100)
xx = [0] + [int(x) for x in input().split()]
edges = []
for _ in range(n-1):
edge = [int(x) for x in input().split()]
edges.append(edge)
edges.append(list(reversed(edge)))
edges.sort()
visited = [False] * (n+1)
children = [[] for _ in range(n+1)]
dq = deque()
dq.append(1)
while dq:
v = dq.popleft()
visited[v] = True
i = bisect_left(edges, [v, 0])
if i == 2*(n-1):
continue
w, x = edges[i]
while w == v and i < 2*(n-1):
if not visited[x]:
children[v].append(x)
dq.append(x)
i+=1
if i < 2*(n-1):
w, x = edges[i]
def gcdsum(i, gcds):
gcdns = [[xx[i], 1]]
sum = xx[i]
for g, c in gcds:
gcdn = gcd(xx[i], g) * c
sum = (sum + gcdn) % MOD
if gcdn == gcdns[-1][0]:
gcdns[-1][1] += c
else:
gcdns.append([gcdn, c])
for v in children[i]:
sum = (sum + gcdsum(v, gcdns)) % MOD
return sum
print(gcdsum(1, []))
if __name__ == "__main__":
main()
``` | instruction | 0 | 17,783 | 13 | 35,566 |
No | output | 1 | 17,783 | 13 | 35,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached 100 million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?
You're given a tree β a connected undirected graph consisting of n vertices connected by n - 1 edges. The tree is rooted at vertex 1. A vertex u is called an ancestor of v if it lies on the shortest path between the root and v. In particular, a vertex is an ancestor of itself.
Each vertex v is assigned its beauty x_v β a non-negative integer not larger than 10^{12}. This allows us to define the beauty of a path. Let u be an ancestor of v. Then we define the beauty f(u, v) as the greatest common divisor of the beauties of all vertices on the shortest path between u and v. Formally, if u=t_1, t_2, t_3, ..., t_k=v are the vertices on the shortest path between u and v, then f(u, v) = \gcd(x_{t_1}, x_{t_2}, ..., x_{t_k}). Here, \gcd denotes the greatest common divisor of a set of numbers. In particular, f(u, u) = \gcd(x_u) = x_u.
Your task is to find the sum
$$$ β_{u is an ancestor of v} f(u, v). $$$
As the result might be too large, please output it modulo 10^9 + 7.
Note that for each y, \gcd(0, y) = \gcd(y, 0) = y. In particular, \gcd(0, 0) = 0.
Input
The first line contains a single integer n (2 β€ n β€ 100 000) β the number of vertices in the tree.
The following line contains n integers x_1, x_2, ..., x_n (0 β€ x_i β€ 10^{12}). The value x_v denotes the beauty of vertex v.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers a, b (1 β€ a, b β€ n, a β b) β the vertices connected by a single edge.
Output
Output the sum of the beauties on all paths (u, v) such that u is ancestor of v. This sum should be printed modulo 10^9 + 7.
Examples
Input
5
4 5 6 0 8
1 2
1 3
1 4
4 5
Output
42
Input
7
0 2 3 0 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
30
Note
The following figure shows all 10 possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to 42:
<image>
Submitted Solution:
```
from math import gcd
n = int(input())
graph = {}
for i in range(n):
graph[i + 1] = []
x = list(map(int, input().split()))
for i in range(n - 1):
a = list(map(int, input().split()))
graph[a[0]].append(a[1])
graph[a[1]].append(a[0])
parents = [1]*(n+1)
vv = [1]
while len(parents) < n and vv:
for v in vv:
for u in graph[v]:
if not (u in parents):
parents[u] = v
vv.append(u)
result = 0;
for v in graph:
p = v
cur_gcd = 0
while p != 1:
cur_gcd = gcd(cur_gcd, x[p - 1])
result += cur_gcd
result %= 10 ** 9 + 7
p = parents[p]
result += gcd(cur_gcd, x[0])
result %= 10 ** 9 + 7
print(result)
``` | instruction | 0 | 17,784 | 13 | 35,568 |
No | output | 1 | 17,784 | 13 | 35,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6 | instruction | 0 | 18,042 | 13 | 36,084 |
Tags: brute force, constructive algorithms, graphs
Correct Solution:
```
import os,io
from sys import stdout
import collections
# import random
# import math
# from operator import itemgetter
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# from collections import Counter
# from decimal import Decimal
# import heapq
# from functools import lru_cache
# import sys
# import threading
# sys.setrecursionlimit(10**6)
# threading.stack_size(102400000)
# from functools import lru_cache
# @lru_cache(maxsize=None)
######################
# --- Maths Fns --- #
######################
def primes(n):
sieve = [True] * n
for i in range(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
return [2] + [i for i in range(3,n,2) if sieve[i]]
def binomial_coefficient(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def powerOfK(k, max):
if k == 1:
return [1]
if k == -1:
return [-1, 1]
result = []
n = 1
while n <= max:
result.append(n)
n *= k
return result
def divisors(n):
i = 1
result = []
while i*i <= n:
if n%i == 0:
if n/i == i:
result.append(i)
else:
result.append(i)
result.append(n/i)
i+=1
return result
# @lru_cache(maxsize=None)
def digitsSum(n):
if n == 0:
return 0
r = 0
while n > 0:
r += n % 10
n //= 10
return r
######################
# ---- GRID Fns ---- #
######################
def isValid(i, j, n, m):
return i >= 0 and i < n and j >= 0 and j < m
def print_grid(grid):
for line in grid:
print(" ".join(map(str,line)))
######################
# ---- MISC Fns ---- #
######################
def kadane(a,size):
max_so_far = 0
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
def prefixSum(arr):
for i in range(1, len(arr)):
arr[i] = arr[i] + arr[i-1]
return arr
def ceil(n, d):
if n % d == 0:
return n // d
else:
return (n // d) + 1
# INPUTS --------------------------
# s = input().decode('utf-8').strip()
# n = int(input())
# l = list(map(int, input().split()))
# t = int(input())
# for _ in range(t):
# for _ in range(t):
t = int(input())
for _ in range(t):
n, p = list(map(int, input().split()))
edges = []
for i in range(1, n+1):
for j in range(i+1, n+1):
edges.append((i, j))
max_edges = (n * (n-1)) // 2
permitted = 2 * n + p
to_remove = max_edges - permitted
if to_remove > 0:
edges = edges[:-to_remove]
for edge in edges:
print(edge[0], edge[1])
``` | output | 1 | 18,042 | 13 | 36,085 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6 | instruction | 0 | 18,043 | 13 | 36,086 |
Tags: brute force, constructive algorithms, graphs
Correct Solution:
```
import sys
input = sys.stdin.readline
read_tuple = lambda _type: map(_type, input().split(' '))
def solve():
t = int(input())
for _ in range(t):
n, p = read_tuple(int)
n_vertices = 2 * n + p
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
if not n_vertices:
break
print(i, j)
n_vertices -= 1
if not n_vertices:
break
if __name__ == '__main__':
solve()
``` | output | 1 | 18,043 | 13 | 36,087 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6 | instruction | 0 | 18,044 | 13 | 36,088 |
Tags: brute force, constructive algorithms, graphs
Correct Solution:
```
'''input
1
6 0
'''
# practicing a skill right after sleep improves it a lot quickly
from sys import stdin, setrecursionlimit
# main starts
t = int(stdin.readline().strip())
for _ in range(t):
n, p = list(map(int, stdin.readline().split()))
count = 0
flag = 0
for i in range(1, n + 1):
if flag == 1:
break
for j in range(i + 1, n + 1):
if count == 2 * n + p:
flag = 1
break
print(i, j)
count += 1
``` | output | 1 | 18,044 | 13 | 36,089 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6 | instruction | 0 | 18,045 | 13 | 36,090 |
Tags: brute force, constructive algorithms, graphs
Correct Solution:
```
for _ in range(int(input())):
n, p = map(int, input().split())
p += 2 * n
for i in range(n):
for j in range(i + 1, n):
if p == 0:
break
print(i + 1, j + 1)
p -= 1
``` | output | 1 | 18,045 | 13 | 36,091 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6 | instruction | 0 | 18,046 | 13 | 36,092 |
Tags: brute force, constructive algorithms, graphs
Correct Solution:
```
import re
t = int(input())
for i in range(t):
x = input()
x = re.split(r"\s" , x)
x1 = int(x[0])
x2 = int(x[1])
cnt = 0
for j in range(x1):
m = j+1
while(m < x1):
print(f"{j+1} {m+1}")
cnt += 1
m += 1
if(cnt >= 2*x1 + x2):
break
if(cnt >= 2*x1 + x2):
break
``` | output | 1 | 18,046 | 13 | 36,093 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6 | instruction | 0 | 18,047 | 13 | 36,094 |
Tags: brute force, constructive algorithms, graphs
Correct Solution:
```
for _ in range(int(input())):
n,p=map(int, input().split())
d={}
ans=0
for i in range(1,n+1):
d[i]=[]
for i in range(1,n+1):
for j in range(1,n+1):
if len(d[i])==2*n+p:
break
if j!=i and j not in d[i]:
print(i,j)
ans+=1
d[i].append(j)
d[j].append(i)
if ans==2*n+p:
break
if ans==2*n+p:
break
``` | output | 1 | 18,047 | 13 | 36,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6 | instruction | 0 | 18,048 | 13 | 36,096 |
Tags: brute force, constructive algorithms, graphs
Correct Solution:
```
for i in range(int(input())):
n, p = map(int, input().split())
all = 2 * n + p
for j in range(1, n + 1):
for k in range(j + 1, n + 1):
if all <= 0:
break
print(j, k)
all -= 1
if all <= 0:
break
``` | output | 1 | 18,048 | 13 | 36,097 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:
* the graph contains exactly 2n + p edges;
* the graph doesn't contain self-loops and multiple edges;
* for any integer k (1 β€ k β€ n), any subgraph consisting of k vertices contains at most 2k + p edges.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.
Your task is to find a p-interesting graph consisting of n vertices.
Input
The first line contains a single integer t (1 β€ t β€ 5) β the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 β€ n β€ 24; p β₯ 0; <image>) β the number of vertices in the graph and the interest value for the appropriate test.
It is guaranteed that the required graph exists.
Output
For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi) β two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.
Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.
Examples
Input
1
6 0
Output
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6 | instruction | 0 | 18,049 | 13 | 36,098 |
Tags: brute force, constructive algorithms, graphs
Correct Solution:
```
for t in range(int(input())):
n, p = map(int, input().split())
i, j = 1, 2
for k in range(2 * n + p):
print(i, j)
j += 1
if j > n:
i += 1
j = i + 1
``` | output | 1 | 18,049 | 13 | 36,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.