message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices. The vertices are numbered 0 through N-1, and the edges are numbered 1 through N-1. Edge i connects Vertex x_i and y_i, and has a value a_i. You can perform the following operation any number of times:
* Choose a simple path and a non-negative integer x, then for each edge e that belongs to the path, change a_e by executing a_e β a_e β x (β denotes XOR).
Your objective is to have a_e = 0 for all edges e. Find the minimum number of operations required to achieve it.
Constraints
* 2 β€ N β€ 10^5
* 0 β€ x_i,y_i β€ N-1
* 0 β€ a_i β€ 15
* The given graph is a tree.
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_{N-1} y_{N-1} a_{N-1}
Output
Find the minimum number of operations required to achieve the objective.
Examples
Input
5
0 1 1
0 2 3
0 3 6
3 4 4
Output
3
Input
2
1 0 0
Output
0
Submitted Solution:
```
from collections import Counter
from functools import reduce
from itertools import combinations
from operator import xor
n = int(input())
nodes = [0] * n
for _ in range(n - 1):
x, y, a = map(int, input().split())
nodes[x] ^= a
nodes[y] ^= a
c = Counter(nodes)
del c[0]
ans = 0
remains = set()
for i, v in c.items():
ans += v // 2
if v % 2:
remains.add(i)
for r in (3, 4, 5):
while len(remains) < r * 2:
for ns in combinations(remains, r):
if reduce(xor, ns) == 0:
remains.difference_update(ns)
ans += r - 1
break
else:
break
print(ans)
``` | instruction | 0 | 22,702 | 13 | 45,404 |
No | output | 1 | 22,702 | 13 | 45,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets. | instruction | 0 | 22,944 | 13 | 45,888 |
Tags: brute force, constructive algorithms, graphs, hashing, implementation
Correct Solution:
```
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
class OrderedList(SortedList): #Codeforces, Ordered Multiset
def __init__(self, arg):
super().__init__(arg)
def rangeCountByValue(self, leftVal, rightVal): #returns number of items in range [leftVal,rightVal] inclusive
leftCummulative = self.bisect_left(leftVal)
rightCummulative = self.bisect_left(rightVal + 1)
return rightCummulative - leftCummulative
def main():
n,m=readIntArr()
adj=[set() for _ in range(n+1)]
for _ in range(m):
u,v=readIntArr()
adj[u].add(v)
adj[v].add(u)
# For every node i, any node j NOT connected to i must be in the same vertex set
v1=OrderedList(range(1,n+1))
others=set()
i=0
while i<len(v1):
u=v1[i]
for v in adj[u]:
v1.discard(v)
others.add(v)
i+=1
v1set=set(v1)
v2=OrderedList(others)
others=set()
i=0
while i<len(v2):
u=v2[i]
for v in adj[u]:
v2.discard(v)
if v not in v1set:
others.add(v)
i+=1
v3=others
ok=True
for u in v3:
for v in adj[u]:
if v in v3: # 2 elements in v3 connected to each other
ok=False
break
l1,l2,l3=len(v1),len(v2),len(v3)
expectedM=l1*(l2+l3)+(l2*l3)
# print(expectedM)
if m!=expectedM:
ok=False
if len(v3)==0 or ok==False:
print(-1)
else:
v1=list(v1set)
v2=list(v2)
v3=list(v3)
ans=[-1]*(n+1)
for x in v1:
ans[x]=1
for x in v2:
ans[x]=2
for x in v3:
ans[x]=3
ans.pop(0)
oneLineArrayPrint(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 | 22,944 | 13 | 45,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets. | instruction | 0 | 22,945 | 13 | 45,890 |
Tags: brute force, constructive algorithms, graphs, hashing, implementation
Correct Solution:
```
from collections import defaultdict, deque
def threeSets(vs, es, d):
sets = [3] * vs
s1 = 0
dist = [float('inf')] * vs
sets[s1] = 1
dist[s1] = 0
queue = deque([s1])
while queue:
v1 = queue.pop()
for v2 in d[v1]:
if dist[v2] > dist[v1] + 1:
dist[v2] = dist[v1] + 1
queue.appendleft(v2)
for i in range(vs):
if dist[i] > 2:
return [-1]
elif dist[i] == 2:
sets[i] = 1
try:
s2 = sets.index(3)
except:
return [-1]
dist = [float('inf')] * vs
sets[s2] = 2
dist[s2] = 0
queue = deque([s2])
while queue:
v1 = queue.pop()
for v2 in d[v1]:
if dist[v2] > dist[v1] + 1:
dist[v2] = dist[v1] + 1
queue.appendleft(v2)
for i in range(vs):
if dist[i] > 2:
return [-1]
elif dist[i] == 2:
if sets[i] == 1:
return [-1]
else:
sets[i] = 2
VS = [set() for i in range(3)]
for i in range(vs):
g = sets[i] - 1
VS[g].add(i)
for V in VS:
if not len(V):
return [-1]
for v1 in VS[0]:
for v2 in VS[1]:
if v2 not in d[v1]:
return [-1]
for v2 in VS[2]:
if v2 not in d[v1]:
return [-1]
for v1 in VS[1]:
for v2 in VS[2]:
if v2 not in d[v1]:
return [-1]
valid_es = len(VS[0]) * len(VS[1]) + len(VS[0]) * len(VS[2]) + len(VS[1]) * len(VS[2])
return sets if es == valid_es else [-1]
d = defaultdict(set)
vs, es = map(int, input().split())
for _ in range(es):
v1, v2 = map(int, input().split())
v1 -= 1
v2 -= 1
d[v1].add(v2)
d[v2].add(v1)
print(*threeSets(vs, es, d))
``` | output | 1 | 22,945 | 13 | 45,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets. | instruction | 0 | 22,946 | 13 | 45,892 |
Tags: brute force, constructive algorithms, graphs, hashing, implementation
Correct Solution:
```
n, m = map(int, input().split())
G = [[] for _ in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
G[a].append(b)
G[b].append(a)
if len(G[0]) < 2:
print(-1)
exit(0)
res = [1]*n
for a in G[0]:
res[a] = 2
a2 = G[0][0]
for b in G[a2]:
if res[b] == 2: res[b] = 3
sizes = [n-len(G[0]), n-len(G[a2]), len(G[0])+len(G[a2])-n]
if 0 in sizes:
print(-1)
exit(0)
for i in range(n):
g = res[i]
s = sizes[g-1]
if len(G[i]) != n-s:
print(-1)
exit(0)
for j in G[i]:
if res[j] == g:
print(-1)
exit(0)
print(*res)
``` | output | 1 | 22,946 | 13 | 45,893 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets. | instruction | 0 | 22,947 | 13 | 45,894 |
Tags: brute force, constructive algorithms, graphs, hashing, implementation
Correct Solution:
```
a=list(map(int,input().split()))
n=a[0]
e=a[1]
g={}
for itr in range(1,n+1):
g[itr]=[]
for i in range(e):
a=list(map(int,input().split()))
g[a[0]].append(a[1])
g[a[1]].append(a[0])
for itr in range(1,n+1):
g[itr]=frozenset(g[itr])
a={}
k=1
res=[]
for i in range(1,n+1):
if len(g[i])==0:
k=100
break
if g[i] in a:
res.append(a[g[i]])
else:
a[g[i]]=k
k+=1
res.append(a[g[i]])
if len(a)>3:break
if k!=4 : print(-1)
else: print(*res)
``` | output | 1 | 22,947 | 13 | 45,895 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets. | instruction | 0 | 22,948 | 13 | 45,896 |
Tags: brute force, constructive algorithms, graphs, hashing, implementation
Correct Solution:
```
import sys
def fill(graph,n):
dp=[[True,True,True] for _ in range(n+1)]
l=[-1 for i in range(n+1)]
from collections import defaultdict
vis=defaultdict(int)
count1,count2,count3=0,0,0
for i in graph:
if dp[i][0]:
#fill
l[i],count1=1,count1+1
vis[i]=1
for j in graph[i]:
dp[j][0]=False
elif dp[i][1]:
#fill
l[i]=2
count2+=1
vis[i]=2
for j in graph[i]:
dp[j][1]=False
elif dp[i][2]:
#fill
l[i]=3
count3+=1
vis[i]=3
for j in graph[i]:
dp[j][2]=False
else:
return [-1]
if count1==0 or count2==0 or count3==0:
return [-1]
if count1+count2+count3!=n:
return [-1]
if count1*count2+count2*count3+count1*count3!=m:
return [-1]
l.pop(0)
for i in l:
if i==-1:
return [-1]
return l
n,m=map(int,sys.stdin.readline().split())
from collections import defaultdict
graph=defaultdict(list)
for i in range(m):
a,b=map(int,sys.stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
k=fill(graph,n)
print(*k)
``` | output | 1 | 22,948 | 13 | 45,897 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets. | instruction | 0 | 22,949 | 13 | 45,898 |
Tags: brute force, constructive algorithms, graphs, hashing, implementation
Correct Solution:
```
#!/usr/bin/python3
import math
import os
import sys
DEBUG = 'DEBUG' in os.environ
def inp():
return sys.stdin.readline().rstrip()
def dprint(*value, sep=' ', end='\n'):
if DEBUG:
print(*value, sep=sep, end=end)
def solve(N, M, G):
A = {}
for i in range(N):
t = frozenset(G[i])
if t not in A:
A[t] = set([i])
else:
A[t].add(i)
if len(A) != 3:
return None
(a1, v1), (a2, v2), (a3, v3) = A.items()
v1 = frozenset(v1)
v2 = frozenset(v2)
v3 = frozenset(v3)
if a1 != v2 | v3 or a2 != v3 | v1 or a3 != v1 | v2:
return None
ans = [0] * N
for v in v1:
ans[v] = 1
for v in v2:
ans[v] = 2
for v in v3:
ans[v] = 3
return ans
def main():
N, M = [int(e) for e in inp().split()]
G = [[] for _ in range(N)]
for _ in range(M):
a, b = [int(e) - 1 for e in inp().split()]
G[a].append(b)
G[b].append(a)
ans = solve(N, M, G)
if not ans:
print('-1')
else:
print(*ans)
if __name__ == '__main__':
main()
``` | output | 1 | 22,949 | 13 | 45,899 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets. | instruction | 0 | 22,950 | 13 | 45,900 |
Tags: brute force, constructive algorithms, graphs, hashing, implementation
Correct Solution:
```
import collections
from collections import defaultdict
graph1=defaultdict(list)
n,m=map(int,input().split())
groups=[0]*(n)
for i in range(m):
u,v=map(int, input().split())
graph1[u].append(v)
graph1[v].append(u)
index=[0,0,0,0]
for i in graph1:
for j in (graph1[i]):
if groups[j-1]==groups[i-1]:
groups[j-1]=(groups[i-1]+1)
if len(set(groups))!=3:
'''
if m==208227:
print(len(set(groups)))
else:'''
print(-1)
exit()
for i in groups:
try:
index[i]+=1
except:
pass
if (index[0]*index[1]+index[1]*index[2]+index[2]*index[0])!=m:
'''
if m==208227 :
print(index)'''
print(-1)
exit()
groups=[x+1 for x in groups]
print(*groups)
``` | output | 1 | 22,950 | 13 | 45,901 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets. | instruction | 0 | 22,951 | 13 | 45,902 |
Tags: brute force, constructive algorithms, graphs, hashing, implementation
Correct Solution:
```
"""
Satwik_Tiwari ;) .
25th AUGUST , 2020 - TUESDAY
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for pp in range(t):
solve(pp)
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
def solve(case):
n,m = sep()
g= [[] for i in range(n)]
for i in range(m):
a,b = sep()
a-=1
b-=1
g[a].append(b)
g[b].append(a)
hash = {}
for i in range(n):
neigh = []
for j in g[i]:
neigh.append(j)
neigh = sorted(neigh)
curr = ' '.join(str(neigh[i]) for i in range(len(neigh)))
if(curr in hash):
hash[curr].append(i)
else:
hash[curr] = [i]
if(len(hash)>3):
print(-1)
return
col = [-1]*n
# print(hash)
ll = []
if(len(hash) == 3):
curr = 1
for i in hash:
ll.append(len(hash[i]))
for j in (hash[i]):
col[j] = curr
curr+=1
else:
print(-1)
return
# print(ll)
if(m!= ll[0]*ll[1]+ll[0]*ll[2]+ll[1]*ll[2]):
print(-1)
return
print(' '.join(str(col[i]) for i in range(len(col))))
testcase(1)
# testcase(int(inp()))
``` | output | 1 | 22,951 | 13 | 45,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets.
Submitted Solution:
```
# https://codeforces.com/contest/1228/problem/D
# all neightbor in group --> pass 1
# all neighbor not in group --> merge 0
# invalid 2
# WA
def type_(list_v, group):
cnt_0 = 0
cnt_1 = 0
for v in list_v:
if v in group:
cnt_1 += 1
else:
cnt_0 += 1
if cnt_1 == len(group):
return 1
if cnt_0 == len(list_v):
return 0
return 2
def is_all_type_1(ex_index, list_group, v):
for i, group in list_group.items():
if i == ex_index:
continue
if type_(g[v], group) != 1:
return False
return True
def check(v, list_group):
t = None
for i, group in list_group.items():
t = type_(g[v], group)
if t == 0 or t == 2:
if t == 0:
if is_all_type_1(i, list_group, v) == True:
group[v] = 1
else:
return 2
return t
return t
group = {}
def process(g):
for v in g:
if len(group) == 0:
group[0] = {}
group[0][v] = 1
continue
t = check(v, group)
if t == 2:
return -1
if t == 1:
if len(group) == 3:
return -1
group[len(group)] = {}
group[len(group)-1][v] = 1
return group
g = {}
n, m = map(int, input().split())
for _ in range(m):
u, v = map(int, input().split())
if u not in g:
g[u] = []
if v not in g:
g[v] = []
g[u].append(v)
g[v].append(u)
ans = process(g)
if ans == -1 or len(ans) < 3:
print(-1)
else:
pr = [0] * n
cnt = 0
for k, gr in group.items():
for v in gr:
cnt += 1
pr[v-1] = str(k+1)
if cnt == n:
print(' '.join(pr))
else:
print(-1)
# 1,2 3,4 5,6
#6 12
#1 3
#1 4
#2 3
#2 4
#1 5
#1 6
#2 5
#2 6
#3 5
#3 6
#4 5
#4 6
``` | instruction | 0 | 22,952 | 13 | 45,904 |
Yes | output | 1 | 22,952 | 13 | 45,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N, M = map(int, input().split())
E = [[] for _ in range(N)]
for _ in range(M):
a, b = map(int, input().split())
E[a-1].append(b-1)
E[b-1].append(a-1)
inf = 1 << 20
A, B, C = [], [], []
X = [0] * N
for a in E[0]:
X[a] = 1
A = [i for i in range(N) if X[i]==0]
b = min([i for i in range(N) if X[i] == 1] + [inf])
if b < inf:
for a in E[b]:
if X[a] == 1: X[a] = 2
B = [i for i in range(N) if X[i]==1]
c = min([i for i in range(N) if X[i] == 2] + [inf])
if c < inf:
for a in E[c]:
if X[a] == 2: X[a] = 3
C = [i for i in range(N) if X[i]==2]
if max(X) == 2 and len(A) * len(B) * len(C) and (len(A) + len(B) + len(C) == N) and (len(A) * len(B) + len(B) * len(C) + len(A) * len(C) == M):
f = 0
for i in range(N):
for j in E[i]:
if X[i] == X[j]:
f = 1
break
if f: break
if f:
print(-1)
else:
print(*[x+1 for x in X])
else:
print(-1)
``` | instruction | 0 | 22,953 | 13 | 45,906 |
Yes | output | 1 | 22,953 | 13 | 45,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
n, m = [int(item) for item in input().split()]
ab = []
edges = [[] for _ in range(n)]
for i in range(m):
a, b = [int(item) for item in input().split()]
a -= 1; b -= 1
edges[a].append(b)
edges[b].append(a)
ab.append((a, b))
groupA = [1] * n
for a, b in ab:
if a == 0:
groupA[b] = 0
elif b == 0:
groupA[a] = 0
par = None
for i, item in enumerate(groupA):
if item == 0:
par = i
break
if par == None:
print(-1)
exit()
groupB = [1] * n
for a, b in ab:
if a == par:
groupB[b] = 0
elif b == par:
groupB[a] = 0
par = None
for i, (p, q) in enumerate(zip(groupA, groupB)):
if p == 0 and q == 0:
par = i
break
if par == None:
print(-1)
exit()
groupC = [1] * n
for a, b in ab:
if a == par:
groupC[b] = 0
elif b == par:
groupC[a] = 0
# Check edge num
sumA = sum(groupA)
sumB = sum(groupB)
sumC = sum(groupC)
e_abc = [0, n - sumA, n - sumB, n - sumC]
edge_num = sumA * sumB + sumB * sumC + sumC * sumA
if edge_num != m:
print(-1)
exit()
# Answer
setA = set()
setB = set()
setC = set()
group = [groupA, groupB, groupC]
ret = []
for i, (ga, gb, gc) in enumerate(zip(groupA, groupB, groupC)):
total = ga + gb + gc
if total != 1:
print(-1)
exit()
if ga:
ret.append(1)
setA.add(i)
elif gb:
ret.append(2)
setB.add(i)
else:
ret.append(3)
setC.add(i)
s_ABC = [set(), setA, setB, setC]
for i, item in enumerate(ret):
if e_abc[item] != len(edges[i]):
print(-1)
exit()
for node in edges[i]:
if node in s_ABC[item]:
print(-1)
exit()
print(" ".join([str(item) for item in ret]))
``` | instruction | 0 | 22,954 | 13 | 45,908 |
Yes | output | 1 | 22,954 | 13 | 45,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets.
Submitted Solution:
```
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
class UnionFind:
def __init__(self, N):
self.parent = [i for i in range(N)]
self.size = [1 for _ in range(N)]
def find(self, x):
if self.parent[x] == x:
return x
else:
return self.find(self.parent[x])
def union(self, x, y):
px = self.find(x)
py = self.find(y)
if px == py:
return
if self.size[px] < self.size[py]:
self.parent[px] = py
self.size[py] += self.size[px]
else:
self.parent[py] = px
self.size[px] += self.size[py]
def same(self, x, y):
return self.find(x) == self.find(y)
def connectedNum(self, x):
return self.size[self.find(x)]
def component_NUM(self):
par = set()
for i in self.parent:
par.add(self.find(i))
return len(par)
N, M = map(int, input().split())
adj = [set() for _ in range(N)]
Un = UnionFind(N)
for _ in range(M):
a, b = map(lambda x: int(x)-1, input().split())
adj[a].add(b)
adj[b].add(a)
added = set()
representative = set()
for i in range(N):
if i in added:
continue
added.add(i)
representative.add(i)
for j in range(i+1, N):
if j in added:
continue
if adj[i] == adj[j]:
added.add(j)
Un.union(i, j)
if len(representative) > 3:
print(-1)
exit()
if Un.component_NUM() == 3:
group = {}
ans = []
for p in range(N):
par = Un.find(p)
if par not in group.keys():
group[par] = len(group)+1
ans.append(group[par])
print(" ".join(map(str, ans)))
else:
print(-1)
``` | instruction | 0 | 22,955 | 13 | 45,910 |
Yes | output | 1 | 22,955 | 13 | 45,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets.
Submitted Solution:
```
from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list)
self.v = vertices
def addEdge(self,x,y):
self.graph[x].append(y)
self.graph[y].append(x)
def FindTripartite(self):
# st1,st2,st3 = "","",""
set1 = set({})
set2 = set({})
set3 = set({})
set4 = set({})
for i in self.graph:
flag = 0
if i in set4:
continue
else:
set1.add(i)
set4.add(i)
for j in self.graph[i]:
if j in set4:
continue
# tempset2.add(j)
set2.add(j)
set4.add(j)
for k in self.graph[j]:
if k in set4:
continue
elif k in self.graph[i]:
set3.add(k)
set4.add(k)
for i in set1:
for j in set1:
# print(set1,set2,set3,"1")
if i in self.graph[j]:
print(-1)
exit()
for i in set2:
for j in set2:
# print(set1,set2,set3)
if i in self.graph[j]:
# print(set1,set2,set3,"2")
print(-1)
exit()
for i in set3:
for j in set3:
# print(set1,set2,set3)
if i in self.graph[j]:
# print(i,j)
# print(set1,set2,set3,"3")
print(-1)
exit()
if len(set4) == g.v:
# print(set1,set2,set3,set4)
# print(set4)
print("1 "*len(set1)+"2 "*len(set2)+"3 "*len(set3))
exit()
print(-1)
n,m = map(int,input().split())
g = Graph(6)
for i in range(m):
x,y = map(int,input().split())
g.addEdge(x,y)
g.FindTripartite()
``` | instruction | 0 | 22,956 | 13 | 45,912 |
No | output | 1 | 22,956 | 13 | 45,913 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets.
Submitted Solution:
```
from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list)
self.v = vertices
def addEdge(self,u,v):
self.graph[u].append(v)
self.graph[v].append(u)
def FindTripartite(self):
set1 = set({})
adjset1 = set({})
set2 = set({})
adjset2 = set({})
set3 = set({})
adjset3 = set({})
set4 = set({})
for i in self.graph:
flag = 0
if i in set4:
continue
if i in adjset1 and i in adjset2 and i in adjset3:
return -1
if i in adjset1 and i in adjset2:
set3.add(i)
set4.add(i)
for j in self.graph[i]:
adjset3.add(j)
flag = 1
elif i in adjset2 and i in adjset3:
set1.add(i)
set4.add(i)
for j in self.graph[i]:
adjset1.add(j)
flag = 1
elif i in adjset1 and i in adjset3:
set2.add(i)
set4.add(i)
for j in self.graph[i]:
adjset2.add(j)
flag = 1
if i in adjset1:
pass
else:
set1.add(i)
set4.add(i)
for j in self.graph[i]:
adjset1.add(j)
flag = 1
continue
if i in adjset2:
pass
else:
set2.add(i)
set4.add(i)
for j in self.graph[i]:
adjset2.add(j)
flag = 1
continue
if i in adjset3:
pass
else:
set3.add(i)
set4.add(i)
for j in self.graph[i]:
adjset3.add(j)
flag = 1
continue
if flag == 0:
return -1
if set1 and set2 and set3:
return "1 "*len(set1)+"2 "*len(set2)+"3 "*len(set3)
else:
return -1
v,n = map(int,input().split())
g = Graph(v)
for i in range(n):
u,v = map(int,input().split())
g.addEdge(u,v)
ans = g.FindTripartite()
print(ans)
``` | instruction | 0 | 22,957 | 13 | 45,914 |
No | output | 1 | 22,957 | 13 | 45,915 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets.
Submitted Solution:
```
from sys import *
n, m = map(int, stdin.readline().split())
edges = [set() for i in range(n)]
for i in range(m):
u, v = map(int, stdin.readline().split())
edges[u-1].add(v-1)
edges[v-1].add(u-1)
f = 1
e1, e2, e3 = -1, -1, -1
e1 = 0
for e in edges[e1]:
e2 = e
for e in edges[e2]:
if e != e1:
e3 = e
if e2 == -1 or e3 == -1:
print(-1)
else:
ans = ""
for x in range(n):
if x == e1:
ans += "1 "
continue
if x == e2:
ans += "2 "
continue
if x == e3:
ans += "3 "
continue
isE1, isE2, isE3 = 0, 0, 0
if x in edges[e1]:
isE1 = 1
if x in edges[e2]:
isE2 = 1
if x in edges[e3]:
isE3 = 1
if isE1 +isE2 + isE3 != 2:
f = 0
break
else:
if not isE1:
ans += "1 "
if not isE2:
ans += "2 "
if not isE3:
ans += "3 "
if f ==1:
print(ans)
else:
print(-1)
``` | instruction | 0 | 22,958 | 13 | 45,916 |
No | output | 1 | 22,958 | 13 | 45,917 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:
1. There are no edges with both endpoints in vertex set v_1.
2. There are no edges with both endpoints in vertex set v_2.
3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.
Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;
1. All vertex sets should not be empty.
2. Each vertex should be assigned to only one vertex set.
3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
Input
The first line contains two integers n and m (3 β€ n β€ 10^{5}, 0 β€ m β€ min(3 β
10^{5}, (n(n-1))/(2))) β the number of vertices and edges in the graph.
The i-th of the next m lines contains two integers a_{i} and b_{i} (1 β€ a_{i} < b_{i} β€ n) β it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Output
If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.
If there are multiple answers, print any.
Examples
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Note
In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.
<image>
In the second example, it's impossible to make such vertex sets.
Submitted Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n,m = inpl()
e = [[] for _ in range(n)]
for _ in range(m):
a,b = inpl()
a,b = a-1,b-1
e[a].append(b)
e[b].append(a)
se = set()
for i in range(n):
e[i].sort()
se.add(tuple(e[i]))
if len(se) != 3:
print(-1)
else:
d = {}
for i,x in enumerate(list(se)):
d[x] = i+1
res = [-1] * n
for i in range(n):
tmp = d[tuple(e[i])]
res[i] = tmp
print(*res)
``` | instruction | 0 | 22,959 | 13 | 45,918 |
No | output | 1 | 22,959 | 13 | 45,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed. | instruction | 0 | 23,041 | 13 | 46,082 |
Tags: brute force, constructive algorithms, dfs and similar, graph matchings, graphs, trees
Correct Solution:
```
import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
e = [[] for i in range(n)]
for _ in range(n-1):
u, v = mints()
e[u-1].append(v-1)
e[v-1].append(u-1)
q = [None]*n
d = [None]*n
c = [0,0]
q[0] = 0
d[0] = 0
ql = 0
qr = 1
while ql < qr:
x = q[ql]
ql += 1
dd = d[x]
c[dd] += 1
dd ^= 1
for v in e[x]:
if d[v] is None:
d[v] = dd
q[qr] = v
qr += 1
print(min(c)-1)
solve()
``` | output | 1 | 23,041 | 13 | 46,083 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed. | instruction | 0 | 23,042 | 13 | 46,084 |
Tags: brute force, constructive algorithms, dfs and similar, graph matchings, graphs, trees
Correct Solution:
```
n = int(input())
allNodes = []
for i in range(n):
allNodes.append([i])
for i in range(n-1):
u, v = map(int, input().split())
allNodes[u-1].append(v-1)
allNodes[v-1].append(u-1)
black = 0
white = 0
from collections import deque
q = deque([])
q.append(0)
visited = [-1]*n
visited[0] = 1
while (len(q)!=0):
e = q.pop()
for i in allNodes[e][1:]:
if visited[i]==-1:
q.append(i)
visited[i] = 1-visited[e]
m = min(visited.count(1), visited.count(0))
print(m-1)
``` | output | 1 | 23,042 | 13 | 46,085 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed. | instruction | 0 | 23,043 | 13 | 46,086 |
Tags: brute force, constructive algorithms, dfs and similar, graph matchings, graphs, trees
Correct Solution:
```
import sys
import collections
inpy = [int(x) for x in sys.stdin.read().split()]
n = inpy[0]
memo = [set() for _ in range(n + 1)]
for i in range(1, len(inpy), 2):
memo[inpy[i]].add(inpy[i+1])
memo[inpy[i+1]].add(inpy[i])
# print(memo)
que = collections.deque([(1, 0, 1)])
x = 0
while que:
index, pre, color = que.pop()
x += color
for i in memo[index]:
if i != pre:
que.append((i, index, color ^ 1))
print (min(x, n - x) - 1)
``` | output | 1 | 23,043 | 13 | 46,087 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed. | instruction | 0 | 23,044 | 13 | 46,088 |
Tags: brute force, constructive algorithms, dfs and similar, graph matchings, graphs, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
graph=[[] for _ in range(n)]
for j in range(n-1):
x,y=map(int,input().split())
x-=1
y-=1
graph[x].append(y)
graph[y].append(x)
color=[-1]*n
tem=[0]
visit=[0]*n
color[0]=0
while(tem!=[]):
x=tem.pop()
for i in graph[x]:
if(color[i]==-1):
visit[i]=1
color[i]=1-color[x]
tem.append(i)
k=color.count(1)
print(min(k,n-k)-1)
``` | output | 1 | 23,044 | 13 | 46,089 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed. | instruction | 0 | 23,045 | 13 | 46,090 |
Tags: brute force, constructive algorithms, dfs and similar, graph matchings, graphs, trees
Correct Solution:
```
import sys
import collections
def input():
return sys.stdin.readline().rstrip()
def split_input():
return [int(i) for i in input().split()]
n = int(input())
color = {}
edges = [[] for _ in range(n)]
for i in range(n-1):
u,v = split_input()
edges[u-1].append(v-1)
edges[v-1].append(u-1)
color[0] = 0
de = collections.deque([])
de.append(0)
while len(de) > 0:
u = de.popleft()
for v in edges[u]:
if v not in color:
color[v] = 1 - color[u]
de.append(v)
l = list(color.values())
z = l.count(0)
o = l.count(1)
print (min(z,o) - 1)
``` | output | 1 | 23,045 | 13 | 46,091 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed. | instruction | 0 | 23,046 | 13 | 46,092 |
Tags: brute force, constructive algorithms, dfs and similar, graph matchings, graphs, trees
Correct Solution:
```
# Fast IO (only use in integer input) or take care about string
import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
connectionList = []
for _ in range(n):
connectionList.append([])
for _ in range(n-1):
a,b = map(int,input().split())
connectionList[a-1].append(b-1)
connectionList[b-1].append(a-1)
colorVertex = [-1] * n
isAdded = [False] * n
redSum = 0
blackSum = 0
colorVertex[0] = 0
queue = [(0,0)] #(Vertex, color pair)
isAdded[0] = True
queueIndex = 0
while queueIndex < len(queue):
curElem = queue[queueIndex]
queueIndex += 1
colorVertex[curElem[0]] = curElem[1]
if curElem[1] == 0:
redSum += 1
else:
blackSum += 1
for elem in connectionList[curElem[0]]:
if not isAdded[elem]:
isAdded[elem] = True
queue.append((elem,1 - curElem[1]))
print(min(redSum,blackSum) - 1)
``` | output | 1 | 23,046 | 13 | 46,093 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed. | instruction | 0 | 23,047 | 13 | 46,094 |
Tags: brute force, constructive algorithms, dfs and similar, graph matchings, graphs, trees
Correct Solution:
```
n = int(input())
adj = [[] for i in range(n)]
for _ in range(n - 1):
u, v = map(int, input().split())
adj[u-1].append(v-1)
adj[v-1].append(u-1)
depth = [-1] * n
depth[0] = 0
odd = 0
even = 1
q = [0]
while q:
nex = q.pop()
for v in adj[nex]:
if depth[v] == -1:
depth[v] = depth[nex] + 1
if depth[v] & 1:
odd += 1
else:
even += 1
q.append(v)
print(min(odd,even) - 1)
``` | output | 1 | 23,047 | 13 | 46,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed. | instruction | 0 | 23,048 | 13 | 46,096 |
Tags: brute force, constructive algorithms, dfs and similar, graph matchings, graphs, trees
Correct Solution:
```
from collections import defaultdict, deque
NONE = -1
WHITE = 0
BLACK = 1
nw = 0
def colorize(G, color, v, c):
global nw
nw += (c == WHITE)
color[v] = c
for u in G[v]:
if color[u] == NONE: # not assigned a color yet
colorize(G, color, u, 1-c)
def colorize_v2(G, stack, color):
nw = 0
while stack:
v, c = stack.pop()
color[v] = c
nw += (c == WHITE)
for u in G[v]:
if color[u] == NONE:
stack.append((u, 1-c))
return nw
n = int(input())
# Adjacency list presentation of the graph, in which G[u] is a list of u's adjacent vertices.
G = defaultdict(list)
for _ in range(n-1):
u, v = (int(x) for x in input().strip().split())
G[u].append(v)
G[v].append(u)
color = [NONE] * (n+1)
stack = deque()
stack.append((1, WHITE))
nw = colorize_v2(G, stack, color)
print(min(nw, n-nw)-1)
``` | output | 1 | 23,048 | 13 | 46,097 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
adj = [[] for i in range(n)]
for _ in range(n - 1):
u, v = map(int, input().split())
adj[u-1].append(v-1)
adj[v-1].append(u-1)
depth = [-1] * n
depth[0] = 0
odd = 0
even = 1
q = [0]
while q:
nex = q.pop()
for v in adj[nex]:
if depth[v] == -1:
depth[v] = depth[nex] + 1
if depth[v] & 1:
odd += 1
else:
even += 1
q.append(v)
print(min(odd,even) - 1)
``` | instruction | 0 | 23,049 | 13 | 46,098 |
Yes | output | 1 | 23,049 | 13 | 46,099 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed.
Submitted Solution:
```
import collections as cc
import sys
I=lambda:list(map(int,input().split()))
n,=I()
g=cc.defaultdict(list)
for i in range(n-1):
x,y=I()
g[x].append(y)
g[y].append(x)
col=[-1]*(n+1)
b=0
w=0
visi=[0]*(n+1)
st=cc.deque()
st.append(1)
col[1]=1
w+=1
while st:
x=st.pop()
visi[x]=1
for y in g[x]:
if not visi[y]:
col[y]=col[x]^1
st.append(y)
b=col.count(1)
w=col.count(0)
print(min(b,w)-1)
``` | instruction | 0 | 23,050 | 13 | 46,100 |
Yes | output | 1 | 23,050 | 13 | 46,101 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed.
Submitted Solution:
```
import sys
input=sys.stdin.readline
import collections
from collections import defaultdict
n=int(input())
def bfs(root):
visited=[0]*(n+1)
queue=collections.deque([root])
visited[root]=1
while queue:
vertex=queue.popleft()
for i in graph[vertex]:
if visited[i]==0:
depth[i]=depth[vertex]+1
queue.append(i)
visited[i]=1
graph=defaultdict(list)
for i in range(n-1):
u,v=map(int,input().split())
graph[u-1].append(v-1)
graph[v-1].append(u-1)
depth=[0]*(n)
depth[0]=0
bfs(0)
odd,even=0,0
for i in depth:
if i&1:
odd+=1
else:
even+=1
print(min(odd,even)-1)
``` | instruction | 0 | 23,051 | 13 | 46,102 |
Yes | output | 1 | 23,051 | 13 | 46,103 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed.
Submitted Solution:
```
import sys
from collections import defaultdict
def rl(): return sys.stdin.readline().strip()
def BFS(s,nbrs):
level = defaultdict(int)
ind = 0
level[ind] += 1
frontier = [s]
visited = {s}
while frontier:
next = []
ind += 1
for u in frontier:
for v in nbrs[u]:
if v not in visited:
next.append(v)
visited.add(v)
level[ind] += 1
frontier = next
return level
n = int(rl())
vert = []
nbrs = defaultdict(list)
for i in range(n-1):
vert.append(list(map(int,rl().split())))
j = vert[-1][0]
k = vert[-1][1]
nbrs[j].append(k)
nbrs[k].append(j)
new = 0
counter = BFS(1,nbrs)
for i in range(2,n-1,2):
new += counter[i]
ans = min(n-2-new,new)
print(ans)
``` | instruction | 0 | 23,052 | 13 | 46,104 |
Yes | output | 1 | 23,052 | 13 | 46,105 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed.
Submitted Solution:
```
import sys
def input():
return sys.stdin.readline().rstrip()
def split_input():
return [int(i) for i in input().split()]
def allpos(a):
n = len(a)
m = len(a[0])
def onBoard(i,j):
return i>=0 and j>=0 and i < n and j < m
dirs = [(1,0),(0,1),(-1,0),(0,-1)]
for i in range(n):
for j in range(m):
for d in dirs:
newi = i + d[0]
newj = j + d[1]
if onBoard(newi, newj):
pass
tests = 1
# tests = int(input())
ind = 0
try:
n = int(input())
color = {}
edges = [[] for _ in range(n)]
ind += 1
for i in range(n-1):
u,v = split_input()
edges[u-1].append(v-1)
edges[v-1].append(u-1)
ind += 1
color[0] = 0
# print(edges)
def dfs(u,p):
# print("color",u,p)
try:
for v in edges[u]:
if v != p:
color[v] = 1 - color[u]
dfs(v,u)
except:
print("Why", edges[u], v)
dfs(0,-1)
ind += 1
l = list(color.values())
# print(l,color)
z = l.count(0)
o = l.count(1)
ind += 1
print (min(z,o) - 1)
except:
print(ind)
``` | instruction | 0 | 23,053 | 13 | 46,106 |
No | output | 1 | 23,053 | 13 | 46,107 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed.
Submitted Solution:
```
from collections import deque
def NC_Dij(lis,start):
ret = [float("inf")] * len(lis)
ret[start] = 0
q = deque([start])
plis = [i for i in range(len(lis))]
while len(q) > 0:
now = q.popleft()
for nex in lis[now]:
if ret[nex] > ret[now] + 1:
ret[nex] = ret[now] + 1
plis[nex] = now
q.append(nex)
return ret,plis
n = int(input())
lis = [ [] for i in range(n) ]
for i in range(n-1):
a,b = map(int,input().split())
a -= 1
b -= 1
lis[a].append(b)
lis[b].append(a)
dlis,plis = NC_Dij(lis,0)
maxind = 0
for i in range(n):
if dlis[i] > dlis[maxind]:
maxind = i
dlis,plis = NC_Dij(lis,maxind)
x = max(dlis) + 1
print (max(0 , x // 2 - 1))
``` | instruction | 0 | 23,054 | 13 | 46,108 |
No | output | 1 | 23,054 | 13 | 46,109 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed.
Submitted Solution:
```
import sys
def input():
return sys.stdin.readline().rstrip()
def split_input():
return [int(i) for i in input().split()]
def allpos(a):
n = len(a)
m = len(a[0])
def onBoard(i,j):
return i>=0 and j>=0 and i < n and j < m
dirs = [(1,0),(0,1),(-1,0),(0,-1)]
for i in range(n):
for j in range(m):
for d in dirs:
newi = i + d[0]
newj = j + d[1]
if onBoard(newi, newj):
pass
tests = 1
# tests = int(input())
ind = 0
try:
n = int(input())
color = {}
edges = [[] for _ in range(n)]
ind += 1
for i in range(n-1):
u,v = split_input()
edges[u-1].append(v-1)
edges[v-1].append(u-1)
ind += 1
color[0] = 0
visited = {i:False for i in range(n)}
# print(edges)
def dfs(u,p):
# print("color",u,p)
visited[u] = True
try:
for v in edges[u]:
if not visited[v]:
color[v] = 1 - color[u]
dfs(v,u)
except Exception as e: print(e)
# print("Why", edges[u], v, color[u])
dfs(0,-1)
ind += 1
l = list(color.values())
# print(l,color)
z = l.count(0)
o = l.count(1)
ind += 1
print (min(z,o) - 1)
except:
print(ind)
``` | instruction | 0 | 23,055 | 13 | 46,110 |
No | output | 1 | 23,055 | 13 | 46,111 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n vertices. You are allowed to modify the structure of the tree through the following multi-step operation:
1. Choose three vertices a, b, and c such that b is adjacent to both a and c.
2. For every vertex d other than b that is adjacent to a, remove the edge connecting d and a and add the edge connecting d and c.
3. Delete the edge connecting a and b and add the edge connecting a and c.
As an example, consider the following tree:
<image>
The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices 2, 4, and 5:
<image>
It can be proven that after each operation, the resulting graph is still a tree.
Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree n - 1, called its center, and n - 1 vertices of degree 1.
Input
The first line contains an integer n (3 β€ n β€ 2 β
10^5) β the number of vertices in the tree.
The i-th of the following n - 1 lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i) denoting that there exists an edge connecting vertices u_i and v_i. It is guaranteed that the given edges form a tree.
Output
Print a single integer β the minimum number of operations needed to transform the tree into a star.
It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most 10^{18} operations.
Examples
Input
6
4 5
2 6
3 2
1 2
2 4
Output
1
Input
4
2 4
4 1
3 4
Output
0
Note
The first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex 5 by applying a single operation to vertices 2, 4, and 5.
In the second test case, the given tree is already a star with the center at vertex 4, so no operations have to be performed.
Submitted Solution:
```
n=int(input())
graph=[]
for i in range(n+1):
graph.append([])
for i in range(n-1):
u,v=map(int,input().split())
graph[u].append(v)
graph[v].append(u)
count=0
for i in range(1,n+1):
if len(graph[i])>1:
count+=1
if count<=1:
print(0)
elif count==2:
print(1)
else:
print(n-2)
``` | instruction | 0 | 23,056 | 13 | 46,112 |
No | output | 1 | 23,056 | 13 | 46,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph with n vertices and m edges. Also, you are given an integer k.
Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
Input
The first line contains a single integer t (1 β€ t β€ 10^5) β the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains three integers n, m, k (1 β€ n, m, k β€ 10^5, k β€ n).
Each of the next m lines contains two integers u, v (1 β€ u, v β€ n, u β v), denoting an edge between vertices u and v.
It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 β
10^5.
Output
For each test case:
If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order.
If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order.
If there are no required subsets and cliques print -1.
If there exists multiple possible answers you can print any of them.
Example
Input
3
5 9 4
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
10 15 3
1 2
2 3
3 4
4 5
5 1
1 7
2 8
3 9
4 10
5 6
7 10
10 8
8 6
6 9
9 7
4 5 4
1 2
2 3
3 4
4 1
1 3
Output
2
4 1 2 3
1 10
1 2 3 4 5 6 7 8 9 10
-1
Note
In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4.
In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer.
In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1. | instruction | 0 | 23,077 | 13 | 46,154 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
from __future__ import division,print_function
from heapq import*
import sys
le = sys.__stdin__.read().split("\n")[::-1]
af = []
for ezo in range(int(le.pop())):
n,m,k = list(map(int, le.pop().split()))
ar = [set() for _ in range(n)]
for i in range(m):
a,b = list(map(int, le.pop().split()))
ar[a - 1].add(b - 1)
ar[b - 1].add(a - 1)
if k * (k - 1) > 2 * m:
af.append(-1)
else:
pi = [i for i in range(n) if len(ar[i]) < k]
re = set(i for i in range(n) if len(ar[i]) >= k)
# print(re,pi,n,m)
while pi:
a = pi.pop()
if len(ar[a]) == k - 1:
clique = True
for j in ar[a]:
if clique:
for h in ar[a]:
if not (h in ar[j]) and h != j:
# print(a,j,h)
clique = False
break
if clique:
af.append(2)
af.append(" ".join(map(str, [i + 1 for i in ar[a]] + [a + 1])))
pi = []
re = {-1}
for j in ar[a]:
ar[j].remove(a)
if len(ar[j]) < k:
if j in re:
pi.append(j)
re.discard(j)
if re and re != {-1}:
af.append("1" + " " + str(len(re)))
af.append(" ".join(map(str, [i + 1 for i in re])))
elif re != {-1}:
af.append(-1)
print("\n".join(map(str, af)))
``` | output | 1 | 23,077 | 13 | 46,155 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph with n vertices and m edges. Also, you are given an integer k.
Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
Input
The first line contains a single integer t (1 β€ t β€ 10^5) β the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains three integers n, m, k (1 β€ n, m, k β€ 10^5, k β€ n).
Each of the next m lines contains two integers u, v (1 β€ u, v β€ n, u β v), denoting an edge between vertices u and v.
It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 β
10^5.
Output
For each test case:
If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order.
If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order.
If there are no required subsets and cliques print -1.
If there exists multiple possible answers you can print any of them.
Example
Input
3
5 9 4
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
10 15 3
1 2
2 3
3 4
4 5
5 1
1 7
2 8
3 9
4 10
5 6
7 10
10 8
8 6
6 9
9 7
4 5 4
1 2
2 3
3 4
4 1
1 3
Output
2
4 1 2 3
1 10
1 2 3 4 5 6 7 8 9 10
-1
Note
In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4.
In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer.
In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1. | instruction | 0 | 23,078 | 13 | 46,156 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
from __future__ import division,print_function
from heapq import*
import sys
t = list(map(int, sys.stdin.readline().strip().split()))[0]
af = []
for _ in range(t):
n,m,k = list(map(int, sys.stdin.readline().strip().split()))
ar = [set() for _ in range(n)]
for i in range(m):
a,b = list(map(int, sys.stdin.readline().strip().split()))
ar[a - 1].add(b - 1)
ar[b - 1].add(a - 1)
if k * (k - 1) > 2 * m:
af.append(-1)
else:
pi = [i for i in range(n) if len(ar[i]) < k]
re = set(i for i in range(n) if len(ar[i]) >= k)
# print(re,pi,n,m)
while pi:
a = pi.pop()
if len(ar[a]) == k - 1:
clique = True
for j in ar[a]:
if clique:
for h in ar[a]:
if not (h in ar[j]) and h != j:
# print(a,j,h)
clique = False
break
if clique:
af.append(2)
af.append(" ".join(map(str, [i + 1 for i in ar[a]] + [a + 1])))
pi = []
re = {-1}
for j in ar[a]:
ar[j].remove(a)
if len(ar[j]) < k:
if j in re:
pi.append(j)
re.discard(j)
if re and re != {-1}:
af.append("1" + " " + str(len(re)))
af.append(" ".join(map(str, [i + 1 for i in re])))
elif re != {-1}:
af.append(-1)
print("\n".join(map(str, af)))
``` | output | 1 | 23,078 | 13 | 46,157 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected graph with n vertices and m edges. Also, you are given an integer k.
Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
Input
The first line contains a single integer t (1 β€ t β€ 10^5) β the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains three integers n, m, k (1 β€ n, m, k β€ 10^5, k β€ n).
Each of the next m lines contains two integers u, v (1 β€ u, v β€ n, u β v), denoting an edge between vertices u and v.
It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 β
10^5.
Output
For each test case:
If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order.
If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order.
If there are no required subsets and cliques print -1.
If there exists multiple possible answers you can print any of them.
Example
Input
3
5 9 4
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
10 15 3
1 2
2 3
3 4
4 5
5 1
1 7
2 8
3 9
4 10
5 6
7 10
10 8
8 6
6 9
9 7
4 5 4
1 2
2 3
3 4
4 1
1 3
Output
2
4 1 2 3
1 10
1 2 3 4 5 6 7 8 9 10
-1
Note
In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4.
In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer.
In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1. | instruction | 0 | 23,079 | 13 | 46,158 |
Tags: constructive algorithms, data structures, graphs
Correct Solution:
```
from __future__ import division, print_function
from heapq import *
import sys
le = sys.__stdin__.read().split("\n")[::-1]
af = []
for ezo in range(int(le.pop())):
n, m, k = list(map(int, le.pop().split()))
ar = [set() for i in range(n)]
for i in range(m):
a, b = map(int, le.pop().split())
ar[a - 1].add(b - 1)
ar[b - 1].add(a - 1)
if k * (k - 1) > 2 * m:
af.append(-1)
else:
pi = [i for i in range(n) if len(ar[i]) < k]
re = set(i for i in range(n) if len(ar[i]) >= k)
while pi:
a = pi.pop()
if len(ar[a]) == k - 1:
clique = True
for j in ar[a]:
if clique:
for h in ar[a]:
if not (h in ar[j]) and h != j:
clique = False
break
if clique:
af.append(2)
af.append(" ".join(map(str, [i + 1 for i in ar[a]] + [a + 1])))
pi = []
re = {-1}
for j in ar[a]:
ar[j].remove(a)
if len(ar[j]) < k:
if j in re:
pi.append(j)
re.discard(j)
if re and re != {-1}:
af.append("1" + " " + str(len(re)))
af.append(" ".join(map(str, [i + 1 for i in re])))
elif re != {-1}:
af.append(-1)
print("\n".join(map(str, af)))
``` | output | 1 | 23,079 | 13 | 46,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph with n vertices and m edges. Also, you are given an integer k.
Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
Input
The first line contains a single integer t (1 β€ t β€ 10^5) β the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains three integers n, m, k (1 β€ n, m, k β€ 10^5, k β€ n).
Each of the next m lines contains two integers u, v (1 β€ u, v β€ n, u β v), denoting an edge between vertices u and v.
It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 β
10^5.
Output
For each test case:
If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order.
If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order.
If there are no required subsets and cliques print -1.
If there exists multiple possible answers you can print any of them.
Example
Input
3
5 9 4
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
10 15 3
1 2
2 3
3 4
4 5
5 1
1 7
2 8
3 9
4 10
5 6
7 10
10 8
8 6
6 9
9 7
4 5 4
1 2
2 3
3 4
4 1
1 3
Output
2
4 1 2 3
1 10
1 2 3 4 5 6 7 8 9 10
-1
Note
In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4.
In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer.
In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1.
Submitted Solution:
```
import io, os
from math import *
def main():
t = int(input())
for _ in range(t):
n, m, k = list(map(int, input().split()))
g = [set() for _ in range(n)]
for _ in range(m):
u, v = list(map(int, input().split()))
g[u-1].add(v-1)
g[v-1].add(u-1)
if k * (k - 1) > 2 * m:
print(-1)
continue
else:
q = [i for i in range(n) if len(g[i]) < k]
r = set(i for i in range(n) if len(g[i]) >= k)
printed = False
while len(q) > 0:
c = q.pop()
if len(g[c]) == k - 1:
# might be a clique
clique = True
for j in g[c]:
if clique:
for u in g[c]:
if u != j and u not in g[c]:
clique = False
break
if clique:
print(2)
print(" ".join(map(str, [i + 1 for i in g[c]] + [c + 1])))
printed = True
q = []
if not printed:
for j in g[c]:
g[j].remove(c)
if len(g[j]) < k:
if j in r:
r.discard(j)
q.append(j)
if len(r) > 0 and not printed:
print("1 " + str(len(r)))
print(" ".join(map(str, [i + 1 for i in r])))
main()
``` | instruction | 0 | 23,080 | 13 | 46,160 |
No | output | 1 | 23,080 | 13 | 46,161 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph with n vertices and m edges. Also, you are given an integer k.
Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
Input
The first line contains a single integer t (1 β€ t β€ 10^5) β the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains three integers n, m, k (1 β€ n, m, k β€ 10^5, k β€ n).
Each of the next m lines contains two integers u, v (1 β€ u, v β€ n, u β v), denoting an edge between vertices u and v.
It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 β
10^5.
Output
For each test case:
If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order.
If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order.
If there are no required subsets and cliques print -1.
If there exists multiple possible answers you can print any of them.
Example
Input
3
5 9 4
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
10 15 3
1 2
2 3
3 4
4 5
5 1
1 7
2 8
3 9
4 10
5 6
7 10
10 8
8 6
6 9
9 7
4 5 4
1 2
2 3
3 4
4 1
1 3
Output
2
4 1 2 3
1 10
1 2 3 4 5 6 7 8 9 10
-1
Note
In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4.
In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer.
In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1.
Submitted Solution:
```
import io, os
from math import *
def main():
t = int(input())
for _ in range(t):
n, m, k = list(map(int, input().split()))
g = [set() for _ in range(n)]
for _ in range(m):
u, v = list(map(int, input().split()))
g[u - 1].add(v - 1)
g[v - 1].add(u - 1)
if k * (k - 1) > 2 * m:
print(-1)
continue
else:
q = [i for i in range(n) if len(g[i]) < k]
r = set(i for i in range(n) if len(g[i]) >= k)
printed = False
while len(q) > 0:
c = q.pop()
if len(g[c]) == k - 1:
# might be a clique
clique = True
for j in g[c]:
if clique:
for u in g[c]:
if u != j and u not in g[c]:
clique = False
break
if clique:
print(2)
print(" ".join(map(str, [i + 1 for i in g[c]] + [c + 1])))
printed = True
q = []
if not printed:
for j in g[c]:
g[j].remove(c)
if len(g[j]) < k:
if j in r:
r.discard(j)
q.append(j)
if not printed:
if len(r) > 0:
print("1 " + str(len(r)))
print(" ".join(map(str, [i + 1 for i in r])))
else:
print(-1)
main()
``` | instruction | 0 | 23,081 | 13 | 46,162 |
No | output | 1 | 23,081 | 13 | 46,163 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph with n vertices and m edges. Also, you are given an integer k.
Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.
A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.
Input
The first line contains a single integer t (1 β€ t β€ 10^5) β the number of test cases. The next lines contain descriptions of test cases.
The first line of the description of each test case contains three integers n, m, k (1 β€ n, m, k β€ 10^5, k β€ n).
Each of the next m lines contains two integers u, v (1 β€ u, v β€ n, u β v), denoting an edge between vertices u and v.
It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 β
10^5.
Output
For each test case:
If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order.
If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order.
If there are no required subsets and cliques print -1.
If there exists multiple possible answers you can print any of them.
Example
Input
3
5 9 4
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
10 15 3
1 2
2 3
3 4
4 5
5 1
1 7
2 8
3 9
4 10
5 6
7 10
10 8
8 6
6 9
9 7
4 5 4
1 2
2 3
3 4
4 1
1 3
Output
2
4 1 2 3
1 10
1 2 3 4 5 6 7 8 9 10
-1
Note
In the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4.
In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer.
In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1.
Submitted Solution:
```
import io, os
from math import *
def main():
t = int(input())
for _ in range(t):
n, m, k = list(map(int, input().split()))
g = [set() for _ in range(n)]
for _ in range(m):
u, v = list(map(int, input().split()))
g[u-1].add(v-1)
g[v-1].add(u-1)
if k * (k - 1) > 2 * m:
print(-1)
continue
else:
q = [i for i in range(n) if len(g[i]) < k]
r = set(i for i in range(n) if len(g[i]) >= k)
printed = False
while len(q) > 0:
c = q.pop()
if len(g[c]) == k - 1:
# might be a clique
clique = True
for j in g[c]:
if clique:
for u in g[c]:
if u != j and u not in g[c]:
clique = False
break
if clique:
print(2)
print(" ".join(map(str, [i + 1 for i in g[c]] + [c + 1])))
printed = True
q = []
if not printed:
for j in g[c]:
g[j].remove(c)
if len(g[j]) < k:
if j in r:
r.discard(j)
q.append(j)
if len(r) > 0 and not printed:
print("1 " + str(len(r)))
print(" ".join(map(str, [i + 1 for i in r])))
else:
print(-1)
main()
``` | instruction | 0 | 23,082 | 13 | 46,164 |
No | output | 1 | 23,082 | 13 | 46,165 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges> | instruction | 0 | 23,494 | 13 | 46,988 |
Tags: constructive algorithms, graphs, shortest paths
Correct Solution:
```
def doit(n, m):
if (n == 2):
print(2, 2)
print(1, 2, 2)
return
sp = 2
mstw = 100003
print(sp, mstw)
print(1, n, sp)
print(2, n, mstw - n + 3 - sp)
for i in range(3, n):
print(i, n, 1)
for i in range(2, n):
for j in range(1, i):
if (m == n - 1):
return
print(i, j, mstw)
m -= 1
n, m = input().split()
doit(int(n), int(m))
``` | output | 1 | 23,494 | 13 | 46,989 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges> | instruction | 0 | 23,495 | 13 | 46,990 |
Tags: constructive algorithms, graphs, shortest paths
Correct Solution:
```
(n, m) = (int(i) for i in input().split())
if n == 2:
print(2, 2)
print(1, 2, 2)
else:
u, v, w = [], [], []
l = list(range(1, 1000000 + 1))
l[0] = 0
for i in range(2, 5 * n + 1):
if l[i - 1] != 0 :
for j in range(i * 2, 5 * n + 1, i):
l[j - 1] = 0
prime = [x for x in l if x != 0] # max(prime) < 5n
#print(prime)
for i in range(2, n - 1):
u.append(1)
v.append(i)
w.append(2)
def lower_bound(prime, value):
left, right = 0, len(prime) - 1
while left != right:
mid = (left + right) // 2
if value > prime[mid]:
left = mid + 1
else:
right = mid
return left
mstw = prime[lower_bound(prime, 2 * (n - 1))]
print(2, mstw)
for i in range(n - 3):
print(u[i], v[i], w[i])
print(1, n - 1, mstw - 2 * (n - 2))
print(1, n, 2)
i, j, count = 2, 3, n - 1
for i in range(2, n):
if count == m:
break
for j in range(i + 1, n + 1):
if count == m:
break
count += 1
print(i, j, 1000000000)
``` | output | 1 | 23,495 | 13 | 46,991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges> | instruction | 0 | 23,496 | 13 | 46,992 |
Tags: constructive algorithms, graphs, shortest paths
Correct Solution:
```
INF = 1000000
erast = [1] * INF
erast[1] = 0
primes = []
for i in range(2, INF):
if erast[i] == 1:
for j in range(i * 2, INF, i):
erast[j] = 0
primes.append(i)
# print(primes)
lastp = primes[-1]
n, m = map(int, input().split())
edges = set()
print(lastp, lastp)
for i in range(n - 2):
print(i + 1, i + 2, 1)
edges.add((i, i + 1))
edges.add((i + 1, i))
print(n - 1, n, lastp - n + 2)
edges.add((n - 1, n))
edges.add((n, n - 1))
m -= n - 1
for i in range(0, n):
for j in range(0, n):
if i == j: continue
if m == 0: break
if not (i, j) in edges:
m -= 1
print(i + 1, j + 1, INF)
edges.add((i, j))
edges.add((j, i))
``` | output | 1 | 23,496 | 13 | 46,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges> | instruction | 0 | 23,497 | 13 | 46,994 |
Tags: constructive algorithms, graphs, shortest paths
Correct Solution:
```
# n_, k_ = [int(i) for i in input().split()]
# for i in range(k_):
# L = -10 ** 18
# R = 10 ** 18
# n = n_
# k = k_
# for kkk in range(70):
# m = (L + R) // 2
# n -= 2 ** m
# k -= m
# if n <
n, m = [int(i) for i in input().split()]
p = 106033
print(p, p)
for i in range(n - 2):
print(i + 1, i + 2, 1)
print(n - 1, n, p - n + 2)
t = n - 1
for i in range(n):
for j in range(i + 2, n):
if t == m:
exit()
print(i + 1, j + 1, 2 * p)
t += 1
``` | output | 1 | 23,497 | 13 | 46,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges> | instruction | 0 | 23,498 | 13 | 46,996 |
Tags: constructive algorithms, graphs, shortest paths
Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
read = lambda: map(int, input().split())
def generate_first_prime(lower, upper):
if upper < lower:
return -1
if lower is 2:
return 2
lower = lower + 1 if lower & 1 is 0 else lower
for num in range(lower, upper + 1, 2):
for i in range(2, num):
if (num % i) is 0:
break
else:
return num
return -1
def main():
n, m = read()
p = generate_first_prime(n, 2 * n - 2)
print(2, p)
n1 = 2 * (n - 1) - p
n2 = p - (n - 1)
index = 2
for _ in range(n1):
print(1, index, 1)
index += 1
for _ in range(n2):
print(1, index, 2)
index += 1
remain = m - (n - 1)
i = 2
j = 3
while remain:
print(i, j, 999)
j += 1
if j > n:
i += 1
j = i + 1
remain -= 1
main()
``` | output | 1 | 23,498 | 13 | 46,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges> | instruction | 0 | 23,499 | 13 | 46,998 |
Tags: constructive algorithms, graphs, shortest paths
Correct Solution:
```
n,m=map(int,input().split())
if(n==2):
print(3,3)
print(1,2,3)
else:
ini=1
print(3,100003)
print(1,n,3)
for i in range(2,n-1):
print(1,i,1)
print(1,n-1,10**5-(n-3))
count=n-1
ini=2
while(count<m):
for i in range(ini+1,n+1):
count+=1
print(ini,i,10000000)
if(count>=m):
break
ini+=1
``` | output | 1 | 23,499 | 13 | 46,999 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges> | instruction | 0 | 23,500 | 13 | 47,000 |
Tags: constructive algorithms, graphs, shortest paths
Correct Solution:
```
n, m = map(int, input().split())
if n == 2:
print(2, 2)
print(1, 2, 2)
exit(0)
SMALL_PRIME = 2
BIG_PRIME = 86028121
print(SMALL_PRIME, BIG_PRIME)
print(1, n, SMALL_PRIME)
# print('----')
some_value = BIG_PRIME // (n-2)
for i in range(2, n-1):
print(1, i, some_value)
# print('----')
to_be_prime = BIG_PRIME - (some_value * (n-3) + SMALL_PRIME)
print(1, n-1, to_be_prime)
# print('----')
total = n - 1 # already printed
for i in range(2, n+1):
for j in range(i, n+1):
if total == m:
exit(0)
if i == j:
continue
print(i, j, BIG_PRIME+7)
total += 1
``` | output | 1 | 23,500 | 13 | 47,001 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges> | instruction | 0 | 23,501 | 13 | 47,002 |
Tags: constructive algorithms, graphs, shortest paths
Correct Solution:
```
n,m=map(int,input().split())
x=0
for i in range(n,2*n):
r=0
for j in range(2,int(i**0.5+1)):
if (i%j==0):
r=1
break
if (r==0):
x=i
break
a=[[] for i in range(n+1)]
for i in range(1,n-1):
a[i].append((i+1,1))
a[n-1].append((n,x-(n-2)))
j=1
l=3
for i in range(n,m+1):
a[j].append((l,10**9))
l+=1
if (l==n+1):
j+=1
l=j+2
print(x,x)
for i in range(1,n+1):
for j in range(len(a[i])):
print(i,a[i][j][0],a[i][j][1])
``` | output | 1 | 23,501 | 13 | 47,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges>
Submitted Solution:
```
n, m = map(int, input().split())
p = 999983
print(p, p)
ans = list()
def to_ans(*arr):
return ' '.join(map(str, arr))
if n == 2:
print(1, 2, p)
exit()
ans.append(to_ans(1, 2, 2))
for i in range(2, n - 1):
ans.append(to_ans(i, i + 1, 1))
ans.append(to_ans(n - 1, n, p - (n - 1)))
x = n - 1
if x == m:
print('\n'.join(ans))
exit()
for i in range(1, n - 1):
for j in range(i + 2, n + 1):
ans.append(to_ans(i, j, 10 ** 8))
x += 1
if x == m:
print('\n'.join(ans))
exit()
``` | instruction | 0 | 23,502 | 13 | 47,004 |
Yes | output | 1 | 23,502 | 13 | 47,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges>
Submitted Solution:
```
from sys import stdin, stdout
M = 200000
isprime = [True] * M
isprime[0] = isprime[1] = False
for i in range(2, M):
if isprime[i]:
for j in range(i * i, M, i):
isprime[j] = False
n, m = map(int, input().split())
sp = 2
mstw = 0
ans = []
ans.append((1, n, 2))
mstw += 2
for v in range(2, n-1):
ans.append((1, v, 1))
mstw += 1
if n-1 > 1:
for w in range(1, M):
if isprime[mstw + w]:
ans.append((1, n-1, w))
mstw += w
break
u, v = 2, 3
while len(ans) < m:
ans.append((u, v, int(1e9)))
v += 1
if v > n:
u += 1
v = u + 1
print(sp, mstw)
for tp in ans:
print(*tp)
``` | instruction | 0 | 23,503 | 13 | 47,006 |
Yes | output | 1 | 23,503 | 13 | 47,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jamie has recently found undirected weighted graphs with the following properties very interesting:
* The graph is connected and contains exactly n vertices and m edges.
* All edge weights are integers and are in range [1, 109] inclusive.
* The length of shortest path from 1 to n is a prime number.
* The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number.
* The graph contains no loops or multi-edges.
If you are not familiar with some terms from the statement you can find definitions of them in notes section.
Help Jamie construct any graph with given number of vertices and edges that is interesting!
Input
First line of input contains 2 integers n, m <image> β the required number of vertices and edges.
Output
In the first line output 2 integers sp, mstw (1 β€ sp, mstw β€ 1014) β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.
In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1 β€ u, v β€ n, 1 β€ w β€ 109) describing the edge connecting u and v and having weight w.
Examples
Input
4 4
Output
7 7
1 2 3
2 3 2
3 4 2
2 4 4
Input
5 4
Output
7 13
1 2 2
1 3 4
1 4 3
4 5 4
Note
The graph of sample 1: <image> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*).
Definition of terms used in the problem statement:
A shortest path in an undirected graph is a sequence of vertices (v1, v2, ... , vk) such that vi is adjacent to vi + 1 1 β€ i < k and the sum of weight <image> is minimized where w(i, j) is the edge weight between i and j. (<https://en.wikipedia.org/wiki/Shortest_path_problem>)
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (<https://en.wikipedia.org/wiki/Prime_number>)
A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (<https://en.wikipedia.org/wiki/Minimum_spanning_tree>)
<https://en.wikipedia.org/wiki/Multiple_edges>
Submitted Solution:
```
n,m = map(int, input().split())
import math
def is_prime(n):
if n == 1:
return False
for i in range(2, int(math.sqrt(n))+1):
if n%i == 0:
return False
return True
for i in range(10**5, 2*10**5):
if is_prime(i):
p = i
break
if n == 2:
print(2, 2)
print(1, 2, 2)
exit()
#print(p)
x = p
ans = {(1, n):2}
x -= 2
for i in range(2, n-1):
ans[(1, i)] = 1
x -= 1
ans[(1, n-1)] = x
edge = []
import itertools
for c in itertools.combinations(range(2, n+1), 2):
if len(edge) == m-(n-1):
break
edge.append((c[0], c[1]))
for i in range(m-(n-1)):
a, b = edge[i]
ans[(a, b)] = 10**9
print(2, p)
for k, v in ans.items():
k = list(k)
temp = k+[v]
print(*temp)
``` | instruction | 0 | 23,504 | 13 | 47,008 |
Yes | output | 1 | 23,504 | 13 | 47,009 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.