message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once. | instruction | 0 | 67,500 | 13 | 135,000 |
Tags: binary search, bitmasks, data structures, divide and conquer, dp, trees
Correct Solution:
```
# coding: utf-8
from math import log2
def dfs (a):
if len(a) == 1:
return 1
mask = 1 << int(log2(a[0] ^ a[-1]))
for i, v in enumerate(a):
if v & mask:
break
return max(dfs(a[0 : i]), dfs(a[i : len(a)])) + 1
n = int(input())
a = sorted(map(int, input().split()))
print(n - dfs(a))
``` | output | 1 | 67,500 | 13 | 135,001 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once. | instruction | 0 | 67,501 | 13 | 135,002 |
Tags: binary search, bitmasks, data structures, divide and conquer, dp, trees
Correct Solution:
```
# according to editorial
import math
# def binary_search(l, target): // this has not been tested
# # returns index i such that l[j] < target iff j < i
# if l[0] >= target:
# return 0
# if l[-1] < target:
# return len(l)
# lo = 0
# hi = len(l) - 1
# while lo < hi:
# mid = (lo+hi) // 2
# if l[mid] >= target and l[mid-1] < target:
# return mid
# elif l[mid] >= target:
# hi = mid
# else:
# lo = mid
# assert binary_search([1, 1, 2, 4, 6], 3) == 3
def num_to_remove(a):
if len(a) == 0:
return 0
max_a = max(a)
if max_a == 0:
return len(a) - 1
highest_bit = int(math.log2(max_a))
cutoff = 2**highest_bit
s_0 = []
s_1 = []
for a_i in a:
if (a_i >> highest_bit) % 2:
s_1.append(a_i ^ cutoff)
else:
s_0.append(a_i)
if len(s_0) <= 1:
return num_to_remove(s_1)
elif len(s_1) == 1:
return num_to_remove(s_0)
else:
assert len(s_0) > 1 and len(s_1) > 1
return min(len(s_0)-1+num_to_remove(s_1), len(s_1)-1+num_to_remove(s_0))
n = int(input())
a = [int(i) for i in input().split()]
print(num_to_remove(a))
``` | output | 1 | 67,501 | 13 | 135,003 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once. | instruction | 0 | 67,502 | 13 | 135,004 |
Tags: binary search, bitmasks, data structures, divide and conquer, dp, trees
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
def rec(s, i):
if len(s) in (0, 1, 2):
return len(s)
mask = 1 << i
a = []
b = []
for one in s:
if one & mask:
a.append(one)
else:
b.append(one)
if not a or not b:
return rec(s, i - 1)
return 1 + max(rec(a, i-1), rec(b, i-1))
print(len(a) - rec(a, 31))
``` | output | 1 | 67,502 | 13 | 135,005 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once. | instruction | 0 | 67,503 | 13 | 135,006 |
Tags: binary search, bitmasks, data structures, divide and conquer, dp, trees
Correct Solution:
```
import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def costs(l, bit = 32):
if len(l) <= 2:
return 0
left = []
right = []
for el in l:
if el & (1<<bit):
left.append(el)
else:
right.append(el)
return min(costs(left, bit-1) + max(0, len(right)-1), costs(right, bit-1) + max(0, len(left)-1))
def solve():
n = int(input())
a = list(map(int, input().split()))
print(costs(a))
t = 1
for _ in range(t):
solve()
``` | output | 1 | 67,503 | 13 | 135,007 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once. | instruction | 0 | 67,504 | 13 | 135,008 |
Tags: binary search, bitmasks, data structures, divide and conquer, dp, trees
Correct Solution:
```
n = int(input());a = sorted([int(x) for x in input().split()])
def solve(l, bit):
if len(l) <= 1: return 0
if bit == 0: return 0
high = [x ^ (1 << bit) for x in l if x & (1 << bit)];low = [x for x in l if not x & (1 << bit)];sh = solve(high, bit-1);sl = solve(low, bit-1)
if not low: return sh
if not high: return sl
return min(len(high) - 1 + sl, len(low) - 1 + sh)
print(solve(a, 40))
``` | output | 1 | 67,504 | 13 | 135,009 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once. | instruction | 0 | 67,505 | 13 | 135,010 |
Tags: binary search, bitmasks, data structures, divide and conquer, dp, trees
Correct Solution:
```
class Trie:
class TrieNode:
def __init__(self) -> None:
self.left = None
self.right = None
self.leaves = 0
self.ends = False
def __init__(self, numbers) -> None:
self.root = self.TrieNode()
self.values = list()
self.size = 0
for n in numbers:
rep = list()
if (n == 0):
rep.append (0)
else:
while n>0:
n,digit = divmod (n, 2)
rep.append (digit)
self.size = max (self.size, len(rep))
self.values.append (rep)
for rep in self.values :
while (len(rep) < self.size):
rep.append (0)
for rep in self.values:
self.reverse (rep)
self.insert (rep)
def reverse (self, A):
i=0
j=len(A)-1
while i < j:
A[i],A[j] = A[j],A[i]
i += 1
j -= 1
def reverse (self, A) :
i,j = 0,len(A)-1
while i<j:
A[i],A[j] = A[j],A[i]
i += 1
j -= 1
def insert (self, string) :
temp = self.root
temp.leaves += 1
for char in string:
if (char == 0) :
if (temp.left is None) :
temp.left = self.TrieNode()
temp = temp.left
else:
if (temp.right is None) :
temp.right = self.TrieNode()
temp = temp.right
temp.leaves += 1
temp.ends = True
def minEliminate (self, node) :
if (node.leaves <= 2) :
return 0
if (node.left is None):
return self.minEliminate (node.right)
if (node.right is None) :
return self.minEliminate (node.left)
return min (self.minEliminate(node.left) + node.right.leaves -1, self.minEliminate(node.right) + node.left.leaves -1)
n = int(input())
A = list(map(int, input().split()))
t = Trie (A)
print (t.minEliminate(t.root))
``` | output | 1 | 67,505 | 13 | 135,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
Submitted Solution:
```
import io,os
from math import *
n = int(input())
a = sorted([int(x) for x in input().split()])
def solve(l, bit):
if len(l) <= 1:
return 0
if bit == 0:
return 0
high = [x ^ (1 << bit) for x in l if x & (1 << bit)]
low = [x for x in l if not x & (1 << bit)]
sh = solve(high, bit-1)
sl = solve(low, bit-1)
if not low:
return sh
if not high:
return sl
return min(len(high) - 1 + sl, len(low) - 1 + sh)
print(solve(a, 40))
``` | instruction | 0 | 67,506 | 13 | 135,012 |
Yes | output | 1 | 67,506 | 13 | 135,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
Submitted Solution:
```
import sys
from collections import defaultdict
import sys
import os
from io import BytesIO, IOBase
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
N = int(input())
arr = list(map(int, input().split()))
max_val = max(arr)
max_binary_len = len(bin(max_val)) - 2
class Node:
def __init__(self):
self.zero = None
self.one = None
self.end = False
root = Node()
for v in arr:
cur = root
ln = max_binary_len - 1
while ln >= 0:
msb = (v & (1<<ln)) > 0
if msb:
if cur.one is None:
cur.one = Node()
cur = cur.one
else:
if cur.zero is None:
cur.zero = Node()
cur = cur.zero
ln -= 1
cur.end = 1
def rec(cur):
if not cur:
return 0
if cur.end:
return cur.end
left = rec(cur.zero)
right = rec(cur.one)
if left > 1 and right > 1:
return 1 + max(left, right)
return left + right
valid = rec(root)
print(N - valid)
``` | instruction | 0 | 67,507 | 13 | 135,014 |
Yes | output | 1 | 67,507 | 13 | 135,015 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
Submitted Solution:
```
"""
#If FastIO not needed, use this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
#start_time = time.time()
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
def getMat(n):
return [getInts() for _ in range(n)]
MOD = 10**9+7
"""
1,1,1,10,1,1,1
"""
def solve(A,L):
if len(A) <= 1 or not L:
return 0
len_L = []
not_len_L = []
for a in A:
if a & pow(2,L):
len_L.append(a)
else:
not_len_L.append(a)
min_L = solve(len_L,L-1)
min_not_L = solve(not_len_L,L-1)
if not len_L:
return min_not_L
if not not_len_L:
return min_L
return min(len(len_L)+min_not_L-1,len(not_len_L)+min_L-1)
#for _ in range(getInt()):
N = getInt()
A = getInts()
print(solve(A,32))
#print(time.time()-start_time)
``` | instruction | 0 | 67,508 | 13 | 135,016 |
Yes | output | 1 | 67,508 | 13 | 135,017 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
Submitted Solution:
```
"""
#If FastIO not needed, use this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
#start_time = time.time()
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
def getMat(n):
return [getInts() for _ in range(n)]
MOD = 10**9+7
"""
0000111100
0000011100
0000101101
0 1 2 5 6
We are going to draw N edges, and exactly N-1 of them must be unique, with one single repeated edge
000
001
010
101
110
numbers will always go below when they can, above only when they have to. they have to go above when they are the lowest in the power of 2 block, unless they are the only one
in which case they have to go below
10
11
2 <-> 3
101
110
111
5 -> 6
6 <-> 7
1000
1001
8 <-> 9
we can have one block of more than one, everything else must be reduced to one block
within each sub-block of those blocks, we can have at most
A number goes below unless it has a longer common prefix above, or unless there is no other number below
So we need to ensure that the number for which this is true is 1
Clearly we can only have one bucket with more than 1 in
Which bucket can we get the most out of?
1000
1001
1010
1011
1100
1101
1110
1111
suppose we have a bucket of [X], the max number of distinct prefixes is len - 1, but this may not be achievable
for each bucket, how many sub-buckets does it have
The lowest number will *always* edge up
We then either edge back down, or we edge up max once more
if we edge back down, then everything else must be different length
if we edge up, we must have two in the same bucket. We can have at most one more in this bucket
"""
def solve():
N = getInt()
A = getInts()
buckets = [0]*31
for n in range(N):
S = bin(A[n])[2:]
buckets[len(S)] += 1
tmp = []
for b in buckets:
if b: tmp.append(b)
if len(tmp) == 1:
if tmp[0] > 3:
return tmp[0] - 3
return 0
ans = 0
best = 10**9
for j in range(2,len(tmp)):
if tmp[j] > 1:
ans += tmp[j] - 1
if tmp[0] >= 3:
ans += tmp[1] - 1
ans += tmp[0] - 3
best = min(best,ans)
ans = 0
if tmp[1] >= 3:
ans += tmp[0] - 1
ans += tmp[1] - 3
best = min(best,ans)
ans = 0
if tmp[0] == 2:
ans += tmp[1] - 1
best = min(best,ans)
ans = 0
if tmp[1] == 2:
ans += tmp[0] - 1
best = min(best,ans)
return best
#for _ in range(getInt()):
print(solve())
#print(time.time()-start_time)
``` | instruction | 0 | 67,509 | 13 | 135,018 |
No | output | 1 | 67,509 | 13 | 135,019 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
Submitted Solution:
```
"""
#If FastIO not needed, use this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
#start_time = time.time()
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
def getMat(n):
return [getInts() for _ in range(n)]
MOD = 10**9+7
"""
0000111100
0000011100
0000101101
0 1 2 5 6
We are going to draw N edges, and exactly N-1 of them must be unique, with one single repeated edge
000
001
010
101
110
numbers will always go below when they can, above only when they have to. they have to go above when they are the lowest in the power of 2 block, unless they are the only one
in which case they have to go below
10
11
2 <-> 3
101
110
111
5 -> 6
6 <-> 7
1000
1001
8 <-> 9
we can have one block of more than one, everything else must be reduced to one block
within each sub-block of those blocks, we can have at most
A number goes below unless it has a longer common prefix above, or unless there is no other number below
So we need to ensure that the number for which this is true is 1
Clearly we can only have one bucket with more than 1 in
Which bucket can we get the most out of?
1000
1001
1010
1011
1100
1101
1110
1111
suppose we have a bucket of [X], the max number of distinct prefixes is len - 1, but this may not be achievable
for each bucket, how many sub-buckets does it have
The lowest number will *always* edge up
We then either edge back down, or we edge up max once more
if we edge back down, then everything else must be different length
if we edge up, we must have two in the same bucket. We can have at most one more in this bucket
"""
def solve():
N = getInt()
A = getInts()
buckets = [0]*31
for n in range(N):
S = bin(A[n])[2:]
buckets[len(S)] += 1
tmp = []
for b in buckets:
if b: tmp.append(b)
if len(tmp) == 1:
if tmp[0] > 3:
return tmp[0] - 3
return 0
ans = 0
best = 10**9
min_ans = 0
for j in range(2,len(tmp)):
if tmp[j] > 1:
min_ans += tmp[j] - 1
if tmp[0] >= 3:
ans += tmp[1] - 1
ans += tmp[0] - 3
best = min(best,ans)
ans = 0
if tmp[1] >= 3:
ans += tmp[0] - 1
ans += tmp[1] - 3
best = min(best,ans)
ans = 0
if tmp[0] == 2:
ans += tmp[1] - 1
best = min(best,ans)
ans = 0
if tmp[1] == 2:
ans += tmp[0] - 1
best = min(best,ans)
return best + min_ans
#for _ in range(getInt()):
print(solve())
#print(time.time()-start_time)
``` | instruction | 0 | 67,510 | 13 | 135,020 |
No | output | 1 | 67,510 | 13 | 135,021 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
Submitted Solution:
```
import io,os
from math import *
n = int(input())
a = sorted([int(x) for x in input().split()])
def solve(l, bit):
if len(l) <= 1:
return 0
high = [x ^ (1 << bit) for x in l if x & (1 << bit)]
low = [x for x in l if not x & (1 << bit)]
sh = solve(high, bit-1)
sl = solve(low, bit-1)
if not low:
return sl
if not high:
return sl
return min(len(high) - 1 + sl, len(low) - 1 + sh)
print(solve(a, 33))
``` | instruction | 0 | 67,511 | 13 | 135,022 |
No | output | 1 | 67,511 | 13 | 135,023 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
Submitted Solution:
```
"""
#If FastIO not needed, use this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
#start_time = time.time()
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
def getMat(n):
return [getInts() for _ in range(n)]
MOD = 10**9+7
"""
0000111100
0000011100
0000101101
0 1 2 5 6
We are going to draw N edges, and exactly N-1 of them must be unique, with one single repeated edge
000
001
010
101
110
numbers will always go below when they can, above only when they have to. they have to go above when they are the lowest in the power of 2 block, unless they are the only one
in which case they have to go below
10
11
2 <-> 3
101
110
111
5 -> 6
6 <-> 7
1000
1001
8 <-> 9
we can have one block of more than one, everything else must be reduced to one block
within each sub-block of those blocks, we can have at most
A number goes below unless it has a longer common prefix above, or unless there is no other number below
So we need to ensure that the number for which this is true is 1
Clearly we can only have one bucket with more than 1 in
Which bucket can we get the most out of?
1000
1001
1010
1011
1100
1101
1110
1111
suppose we have a bucket of [X], the max number of distinct prefixes is len - 1, but this may not be achievable
for each bucket, how many sub-buckets does it have
The lowest number will *always* edge up
We then either edge back down, or we edge up max once more
if we edge back down, then everything else must be different length
if we edge up, we must have two in the same bucket. We can have at most one more in this bucket
"""
def solve():
N = getInt()
A = getInts()
buckets = [0]*31
for n in range(N):
S = bin(A[n])[2:]
buckets[len(S)] += 1
if buckets[1] == 2:
for j in range(2,31):
if buckets[j]: buckets[j] = 1
return N - sum(buckets)
tmp = []
for b in buckets:
if b: tmp.append(b)
if len(tmp) == 1:
if tmp[0] > 3:
return tmp[0] - 3
return 0
ans = 0
for j in range(2,len(tmp)):
if tmp[j] > 1:
ans += tmp[j] - 1
if tmp[0] == 3:
ans += tmp[1] - 1
elif tmp[1] == 3:
ans += tmp[0] - 1
elif tmp[0] == 2:
ans += tmp[1] - 1
elif tmp[1] == 2:
ans += tmp[0] - 1
return ans
#for _ in range(getInt()):
print(solve())
#print(time.time()-start_time)
``` | instruction | 0 | 67,512 | 13 | 135,024 |
No | output | 1 | 67,512 | 13 | 135,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has n nodes (numbered 1 to n, with some node r as its root). There are a_i presents are hanging from the i-th node.
Before beginning the game, a special integer k is chosen. The game proceeds as follows:
* Alice begins the game, with moves alternating each turn;
* in any move, the current player may choose some node (for example, i) which has depth at least k. Then, the player picks some positive number of presents hanging from that node, let's call it m (1 β€ m β€ a_i);
* the player then places these m presents on the k-th ancestor (let's call it j) of the i-th node (the k-th ancestor of vertex i is a vertex j such that i is a descendant of j, and the difference between the depth of j and the depth of i is exactly k). Now, the number of presents of the i-th node (a_i) is decreased by m, and, correspondingly, a_j is increased by m;
* Alice and Bob both play optimally. The player unable to make a move loses the game.
For each possible root of the tree, find who among Alice or Bob wins the game.
Note: The depth of a node i in a tree with root r is defined as the number of edges on the simple path from node r to node i. The depth of root r itself is zero.
Input
The first line contains two space-separated integers n and k (3 β€ n β€ 10^5, 1 β€ k β€ 20).
The next n-1 lines each contain two integers x and y (1 β€ x, y β€ n, x β y), denoting an undirected edge between the two nodes x and y. These edges form a tree of n nodes.
The next line contains n space-separated integers denoting the array a (0 β€ a_i β€ 10^9).
Output
Output n integers, where the i-th integer is 1 if Alice wins the game when the tree is rooted at node i, or 0 otherwise.
Example
Input
5 1
1 2
1 3
5 2
4 3
0 3 2 4 4
Output
1 0 0 1 1
Note
Let us calculate the answer for sample input with root node as 1 and as 2.
Root node 1
Alice always wins in this case. One possible gameplay between Alice and Bob is:
* Alice moves one present from node 4 to node 3.
* Bob moves four presents from node 5 to node 2.
* Alice moves four presents from node 2 to node 1.
* Bob moves three presents from node 2 to node 1.
* Alice moves three presents from node 3 to node 1.
* Bob moves three presents from node 4 to node 3.
* Alice moves three presents from node 3 to node 1.
Bob is now unable to make a move and hence loses.
Root node 2
Bob always wins in this case. One such gameplay is:
* Alice moves four presents from node 4 to node 3.
* Bob moves four presents from node 5 to node 2.
* Alice moves six presents from node 3 to node 1.
* Bob moves six presents from node 1 to node 2.
Alice is now unable to make a move and hence loses. | instruction | 0 | 67,529 | 13 | 135,058 |
Tags: bitmasks, data structures, dfs and similar, dp, games, math, trees
Correct Solution:
```
import sys
from sys import stdin
from collections import deque
n,k = map(int,stdin.readline().split())
N,K = n,k
lis = [ [] for i in range(N) ]
for i in range(N-1):
x,y = map(int,stdin.readline().split())
x -= 1
y -= 1
lis[x].append(y)
lis[y].append(x)
a = list(map(int,stdin.readline().split()))
#bfs
p = [i for i in range(N)]
vlis = []
q = deque([0])
while q:
v = q.popleft()
vlis.append(v)
for nex in lis[v]:
if nex != p[v]:
p[nex] = v
q.append(nex)
#dp-first
dp = [[0] * (2*k) for i in range(N)]
for ind in range(N-1,-1,-1):
v = vlis[ind]
dp[v][0] ^= a[v]
for nex in lis[v]:
if nex != p[v]:
for nk in range(2*k):
dp[v][(nk+1) % (2*k)] ^= dp[nex][nk]
#dp2
ans = [None] * N
for v in vlis:
if v == 0:
now = 0
for i in range(k,2*k):
now ^= dp[v][i]
ans[v] = min(now,1)
else:
pcopy = [dp[p[v]][i] for i in range(2*k)]
for i in range(2*k):
pcopy[(i+1) % (2*k)] ^= dp[v][i]
for i in range(2*k):
dp[v][(i+1) % (2*k)] ^= pcopy[i]
now = 0
for i in range(k,2*k):
now ^= dp[v][i]
ans[v] = min(now,1)
print (*ans)
``` | output | 1 | 67,529 | 13 | 135,059 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has n nodes (numbered 1 to n, with some node r as its root). There are a_i presents are hanging from the i-th node.
Before beginning the game, a special integer k is chosen. The game proceeds as follows:
* Alice begins the game, with moves alternating each turn;
* in any move, the current player may choose some node (for example, i) which has depth at least k. Then, the player picks some positive number of presents hanging from that node, let's call it m (1 β€ m β€ a_i);
* the player then places these m presents on the k-th ancestor (let's call it j) of the i-th node (the k-th ancestor of vertex i is a vertex j such that i is a descendant of j, and the difference between the depth of j and the depth of i is exactly k). Now, the number of presents of the i-th node (a_i) is decreased by m, and, correspondingly, a_j is increased by m;
* Alice and Bob both play optimally. The player unable to make a move loses the game.
For each possible root of the tree, find who among Alice or Bob wins the game.
Note: The depth of a node i in a tree with root r is defined as the number of edges on the simple path from node r to node i. The depth of root r itself is zero.
Input
The first line contains two space-separated integers n and k (3 β€ n β€ 10^5, 1 β€ k β€ 20).
The next n-1 lines each contain two integers x and y (1 β€ x, y β€ n, x β y), denoting an undirected edge between the two nodes x and y. These edges form a tree of n nodes.
The next line contains n space-separated integers denoting the array a (0 β€ a_i β€ 10^9).
Output
Output n integers, where the i-th integer is 1 if Alice wins the game when the tree is rooted at node i, or 0 otherwise.
Example
Input
5 1
1 2
1 3
5 2
4 3
0 3 2 4 4
Output
1 0 0 1 1
Note
Let us calculate the answer for sample input with root node as 1 and as 2.
Root node 1
Alice always wins in this case. One possible gameplay between Alice and Bob is:
* Alice moves one present from node 4 to node 3.
* Bob moves four presents from node 5 to node 2.
* Alice moves four presents from node 2 to node 1.
* Bob moves three presents from node 2 to node 1.
* Alice moves three presents from node 3 to node 1.
* Bob moves three presents from node 4 to node 3.
* Alice moves three presents from node 3 to node 1.
Bob is now unable to make a move and hence loses.
Root node 2
Bob always wins in this case. One such gameplay is:
* Alice moves four presents from node 4 to node 3.
* Bob moves four presents from node 5 to node 2.
* Alice moves six presents from node 3 to node 1.
* Bob moves six presents from node 1 to node 2.
Alice is now unable to make a move and hence loses.
Submitted Solution:
```
print('1 0 0 1 1')
``` | instruction | 0 | 67,530 | 13 | 135,060 |
No | output | 1 | 67,530 | 13 | 135,061 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | instruction | 0 | 67,642 | 13 | 135,284 |
Tags: constructive algorithms, data structures, greedy, sortings, trees
Correct Solution:
```
from collections import deque
n = int(input())
process = deque()
vs = []
for i in range(n):
d, s = map(int, input().split())
if d == 1:
process.append(i)
vs.append((d, s))
edges = []
while process:
a = process.popleft()
d, s = vs[a]
if d == 0:
continue
dd, ss = vs[s]
vs[s] = (dd - 1, ss ^ a)
if dd == 2:
process.append(s)
edges.append((a, s))
print(len(edges))
for a, b in edges:
print(a, b)
``` | output | 1 | 67,642 | 13 | 135,285 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | instruction | 0 | 67,643 | 13 | 135,286 |
Tags: constructive algorithms, data structures, greedy, sortings, trees
Correct Solution:
```
n = int(input())
ss = [0] * n
degs = [0] * n
leaves = []
for i in range(n):
degs[i], ss[i] = list(map(int, input().split()))
if degs[i] == 1:
leaves.append(i)
edges = []
while len(leaves) != 0:
leaf = leaves.pop()
if degs[leaf] == 0:
continue
v = ss[leaf]
edges.append((leaf, v))
v_deg = degs[v]
ss[v] = ss[v] ^ leaf
degs[v] -= 1
if degs[v] == 1:
leaves.append(v)
print(len(edges))
for edge in edges:
print(edge[0], edge[1])
``` | output | 1 | 67,643 | 13 | 135,287 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | instruction | 0 | 67,644 | 13 | 135,288 |
Tags: constructive algorithms, data structures, greedy, sortings, trees
Correct Solution:
```
def fastio():
import sys
from io import StringIO
from atexit import register
global input
sys.stdin = StringIO(sys.stdin.read())
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.stdout = StringIO()
register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from queue import Queue as Q
q = Q()
n, = I()
l = []
x = [0]*(n + 10)
d = [0]*(n + 10)
for i in range(n):
a, b = I()
x[i] = b
d[i] = a
if a == 1:
q.put(i)
e = []
while not q.empty():
p = q.get()
par = x[p]
if d[p] == 1:
if p != par:
e.append([p, par])
x[par] ^= p
d[par] -= 1
d[p] -= 1
if d[par] == 1:
q.put(par)
print(len(e))
for i in e:
if i[0] != i[1]:
print(*i)
``` | output | 1 | 67,644 | 13 | 135,289 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | instruction | 0 | 67,645 | 13 | 135,290 |
Tags: constructive algorithms, data structures, greedy, sortings, trees
Correct Solution:
```
from sys import stdin,stdout,setrecursionlimit
stdin.readline
def mp(): return list(map(int, stdin.readline().strip().split()))
def it():return int(stdin.readline().strip())
from collections import defaultdict as dd,Counter as C,deque
from math import ceil,gcd,sqrt,factorial,log2,floor
from bisect import bisect_right as br,bisect_left as bl
import heapq
n = it()
v=[]
for _ in range(n):
v.append(mp())
q = deque()
for i in range(n):
if v[i][0] == 1:
q.append(i)
# print(q)
ans=[]
while q:
ver = q.popleft()
if not v[ver][0]:
continue
ans.append([ver,v[ver][1]])
v[v[ver][1]][0] -= 1
v[v[ver][1]][1] ^= ver
if v[v[ver][1]][0] == 1:
q.append(v[ver][1])
print(len(ans))
for i in range(len(ans)):
print(*ans[i])
``` | output | 1 | 67,645 | 13 | 135,291 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | instruction | 0 | 67,646 | 13 | 135,292 |
Tags: constructive algorithms, data structures, greedy, sortings, trees
Correct Solution:
```
def main():
n, l, ones, j = int(input()), [], [], 0
for i in range(n):
degree, s = map(int, input().split())
l.append((degree, s))
j += degree
if degree == 1:
ones.append(i)
print(j // 2)
while ones:
i = ones.pop()
degree, j = l[i]
if degree == 1:
print(i, j)
degree, s = l[j]
s ^= i
degree -= 1
l[j] = degree, s
if degree == 1:
ones.append(j)
if __name__ == '__main__':
main()
``` | output | 1 | 67,646 | 13 | 135,293 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | instruction | 0 | 67,647 | 13 | 135,294 |
Tags: constructive algorithms, data structures, greedy, sortings, trees
Correct Solution:
```
def main():
n = int(input())
ones, l = set(), []
for i in range(n):
degree, s = map(int, input().split())
if degree == 1:
ones.add(i)
l.append((degree, s))
res = []
while ones:
i = ones.pop()
degree_i, j = l[i]
degree_j, s = l[j]
res.append(' '.join((str(i), str(j))))
if degree_j == 1:
ones.remove(j)
else:
degree_j -= 1
if degree_j == 1:
ones.add(j)
l[j] = (degree_j, s ^ i)
print(len(res))
print('\n'.join(res))
if __name__ == '__main__':
main()
``` | output | 1 | 67,647 | 13 | 135,295 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | instruction | 0 | 67,648 | 13 | 135,296 |
Tags: constructive algorithms, data structures, greedy, sortings, trees
Correct Solution:
```
n=int(input())
l=[]
stack=[]
for i in range(n):
d,s=map(int,input().split())
if d==1:
stack.append(i)
l.append([d,s])
c=0
edges=''
while stack:
i=stack.pop(0)
d,s=l[i]
if d==0:
continue
dd,ss=l[s]
if dd==2:
stack.append(s)
l[s]=[dd-1,ss^i]
edges+=str(i)+' '+str(s)+'\n'
c+=1
print(c)
print(edges)
``` | output | 1 | 67,648 | 13 | 135,297 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | instruction | 0 | 67,649 | 13 | 135,298 |
Tags: constructive algorithms, data structures, greedy, sortings, trees
Correct Solution:
```
n = int(input())
d = []
v = []
for i in range(n):
(a, b) = map(int, input().split())
v.append([a, b, i])
g = dict()
for i in range(n+20):
g[i] = set()
for i in v:
if i[0] in g:
g[i[0]].add(i[2])
else:
g[i[0]] = set()
g[i[0]].add(i[2])
ans = []
while len(g[1]) > 0:
i = 0
for x in g[1]:
i = x
break
a = v[i][2]
b = v[i][1]
g[v[a][0]].discard(v[a][2])
g[v[a][0]-1].add(v[a][2])
v[a][0] -= 1
g[v[b][0]].discard(v[b][2])
g[v[b][0]-1].add(v[b][2])
v[b][0] -= 1
v[b][1] ^= a
ans.append((a, b))
print(len(ans))
for i in ans:
print(*i)
'''
9
2 5
4 3
7 6
8 3
5 0
6 1
3 9
1 0
9 0
'''
``` | output | 1 | 67,649 | 13 | 135,299 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor".
Submitted Solution:
```
n = int(input())
stack_leaves = []
deg = [0]*n
s = [0]*n
summ = 0
for i in range(n):
deg[i], s[i] = map(int, input().split())
summ += deg[i]
if deg[i] == 1:
stack_leaves.append(i)
print(summ // 2)
while stack_leaves:
x = stack_leaves.pop()
if deg[x] != 0:
print(x, s[x])
deg[s[x]] -= 1
s[s[x]] ^= x
if deg[s[x]] == 1:
stack_leaves.append(s[x])
``` | instruction | 0 | 67,650 | 13 | 135,300 |
Yes | output | 1 | 67,650 | 13 | 135,301 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor".
Submitted Solution:
```
import math
#n,m=map(int,input().split())
from collections import Counter
#for i in range(n):
import math
#for _ in range(int(input())):
n = int(input())
deg=[0]*n
ss=[0]*n
q=[]
for i in range(n):
deg[i],ss[i]=map(int,input().split())
if deg[i]==1:
q.append(i)
edges=[]
while q:
leaf=q.pop()
if deg[leaf]==0:
continue
v=ss[leaf]
edges.append((leaf, v))
deg[v]-=1
ss[v]=ss[v]^leaf
if deg[v]==1:
q.append(v)
print(len(edges))
for i in edges:
print(*i)
``` | instruction | 0 | 67,651 | 13 | 135,302 |
Yes | output | 1 | 67,651 | 13 | 135,303 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor".
Submitted Solution:
```
n = int(input())
deg2vs = {}
ss = [0] * n
degs = [0] * n
for i in range(n):
degs[i], ss[i] = list(map(int, input().split()))
if degs[i] > 0:
if degs[i] not in deg2vs:
deg2vs[degs[i]] = set()
deg2vs[degs[i]].add(i)
edges = []
while len(deg2vs) != 0:
leaves = deg2vs.pop(1)
for leaf in leaves:
if degs[leaf] == 0:
continue
v = ss[leaf]
edges.append((leaf, v))
v_deg = degs[v]
if v_deg > 1:
deg2vs[v_deg].remove(v)
if len(deg2vs[v_deg]) == 0:
deg2vs.pop(v_deg)
ss[v] = ss[v] ^ leaf
degs[v] -= 1
if degs[v] > 0:
if degs[v] not in deg2vs:
deg2vs[degs[v]] = set()
deg2vs[degs[v]].add(v)
print(len(edges))
for edge in edges:
print(edge[0], edge[1])
``` | instruction | 0 | 67,652 | 13 | 135,304 |
Yes | output | 1 | 67,652 | 13 | 135,305 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor".
Submitted Solution:
```
#!/usr/bin/env python3
from queue import PriorityQueue
N = int(input())
v = list()
Q = list()
for i in range(N):
s, k = input().split()
v.append((int(s), int(k)))
if int(s) == 1:
Q.append(i)
edge = list()
while len(Q) > 0:
u = Q.pop()
if v[u][0] == 0:
continue
g = v[u][1]
edge.append((u, g))
v[g] = (v[g][0] - 1, v[g][1] ^ u)
if v[g][0] == 1:
Q.append(g)
print(len(edge))
for i, j in edge:
print(i, j)
``` | instruction | 0 | 67,653 | 13 | 135,306 |
Yes | output | 1 | 67,653 | 13 | 135,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor".
Submitted Solution:
```
n = int(input())
verts = []
e = []
for i in range(n):
inp = [*map(int, input().split(' '))]
verts.append([i] + inp)
# e = []
# verts = [
# [0, 1, 1],
# [1, 5, 0],
# [2, 3, 0],
# [3, 1, 1],
# [4, 1, 1],
# [5, 1, 1],
# [6, 1, 2],
# [7, 1, 2],
# ]
leavesQ = list(filter(lambda v: v[1] == 1, verts))
while len(leavesQ) > 1:
l = leavesQ.pop()
e.append([l[0], l[2]])
l[1] -= 1
verts[l[2]][1] -= 1
verts[l[2]][2] ^= l[0]
if verts[l[2]][1] == 1:
leavesQ.append(verts[l[2]])
print(len(e))
for [x, y] in e:
print(x, y)
``` | instruction | 0 | 67,654 | 13 | 135,308 |
No | output | 1 | 67,654 | 13 | 135,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor".
Submitted Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
from collections import deque
# it's a tree
def main():
n=int(input())
arr=[]
q=deque()
for _ in range(n):
a,b=map(int,input().split())
arr.append([a,b])
if a==1:
q.append(_)
while q:
x=q.popleft()
if arr[x][0]==1:
print(x,arr[x][1])
y=arr[x][1]
arr[y][0]-=1
arr[y][1]^=x
if arr[y][0]==1:
q.append(y)
#----------------------------------------------------------------------------------------
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
``` | instruction | 0 | 67,655 | 13 | 135,310 |
No | output | 1 | 67,655 | 13 | 135,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor".
Submitted Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
from collections import deque
# it's a tree
def main():
n=int(input())
arr=[]
q=deque()
for _ in range(n):
a,b=map(int,input().split())
arr.append([a,b])
if a==1:
q.append(_)
ans=[]
while q:
x=q.popleft()
if arr[x][0]==1:
ans.append((x,arr[x][1]))
y=arr[x][1]
arr[y][0]-=1
arr[y][1]^=x
if arr[y][0]==1:
q.append(y)
print(len(ans))
for _ in ans:
print(*_)
#----------------------------------------------------------------------------------------
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
``` | instruction | 0 | 67,656 | 13 | 135,312 |
No | output | 1 | 67,656 | 13 | 135,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).
Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
Input
The first line contains integer n (1 β€ n β€ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 β€ degreei β€ n - 1, 0 β€ si < 216), separated by a space.
Output
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 β€ a β€ n - 1, 0 β€ b β€ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
Examples
Input
3
2 3
1 0
1 0
Output
2
1 0
2 0
Input
2
1 1
1 0
Output
1
0 1
Note
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor".
Submitted Solution:
```
n = int(input())
verts = []
e = []
for i in range(n):
inp = [*map(int, input().split(' '))]
verts.append([i] + inp)
leavesQ = list(filter(lambda v: v[1] == 1, verts))
while len(leavesQ) > 0:
l = leavesQ.pop()
if l[1] != 1:
continue
l2 = verts[l[2]]
e.append([l[0], l2[0]])
l[1] -= 1
l2[1] -= 1
l2[2] ^= l[0]
if l2[1] == 1:
leavesQ.append(l2)
print(leavesQ)
print(len(e))
for [x, y] in e:
print(x, y)
``` | instruction | 0 | 67,657 | 13 | 135,314 |
No | output | 1 | 67,657 | 13 | 135,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | instruction | 0 | 67,752 | 13 | 135,504 |
Tags: binary search, data structures, dfs and similar, graphs, trees
Correct Solution:
```
from itertools import accumulate
from math import *
import os, sys
import threading
from io import BytesIO
from bisect import bisect_left
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
a = list(map(int, input().split()))
e = {}
g = [[] for i in range(n)]
d = [0]*(n+5)
ans = [0]*n
p = [0]*(n+5)
for i in range(n-1):
c, w = map(int, input().split())
c-= 1
g[c].append(i+1)
e[i+1] = w
def dfs(i, h):
global ans, a, e, g, d, p
p[h]=0
for j in g[i]:
d[h+1] = d[h]+e[j]
dfs(j, h+1)
x = bisect_left(d, d[h]-a[i], 0, h+1)
#print(x-1, i, h, d[h], d[h], a[i])
if x>=0:
p[x-1]-=1
p[h-1]+=p[h]+1
ans[i]=p[h]
def solve():
global ans
dfs(0, 0)
print(*ans)
sys.setrecursionlimit(10**5*2 + 1000)
threading.stack_size((10**5*2 + 1000) * 500)
thread = threading.Thread(target=solve)
thread.start()
``` | output | 1 | 67,752 | 13 | 135,505 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | instruction | 0 | 67,753 | 13 | 135,506 |
Tags: binary search, data structures, dfs and similar, graphs, trees
Correct Solution:
```
#!/usr/bin/env python3
import sys
import threading
from bisect import *
from itertools import *
#def ri():
# return map(int, input().split())
def dfs(v):
global d
d += 1
dist[d] = w[v] + dist[d-1]
add[d] = 0
for i in c[v]:
dfs(i)
x = bisect_left(dist, dist[d] - a[v], 0, d)
add[x-1] -= 1
add[d-1] += 1
add[d-1] += add[d]
ans[v] = add[d]
d -= 1
d = 0
dist = [0]
dist = [0 for i in range(2*10**5+3)]
add = [0 for i in range(2*10**5+3)]
ans = [0 for i in range(2*10**5+3)]
n = int(input())
a = [0]
c = [[] for i in range(n+1)]
w = [0 for i in range(n+1)]
for i in map(int, input().split()):
a.append(i)
for i in range(2, n+1):
t1, t2 = map(int, input().split())
c[t1].append(i)
w[i] = t2
sys.setrecursionlimit(10**6)
threading.stack_size(10**7*8)
thread = threading.Thread(target=dfs, args=(1,))
thread.start()
if thread.is_alive():
thread.join()
print(' '.join(str(ans[i]) for i in range(1, n+1)))
``` | output | 1 | 67,753 | 13 | 135,507 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | instruction | 0 | 67,754 | 13 | 135,508 |
Tags: binary search, data structures, dfs and similar, graphs, trees
Correct Solution:
```
#!/usr/bin/env python3
import sys
import threading
from bisect import *
def ri():
return map(int, input().split())
def dfs(v, d, c, w):
d += 1
dist[d] = w[v] + dist[d-1]
add[d] = 0
for i in c[v]:
dfs(i, d, c, w)
x = bisect_left(dist, dist[d] - a[v], 0, d)
add[x-1] -= 1
add[d-1] += 1 + add[d]
ans[v] = str(add[d])
d -= 1
n = int(input())
dist = [0] * (2*10**5+3)
add = [0] * (2*10**5+3)
ans = [''] * (n+1)
a = [0] * (n+1)
def solve():
c = [[] for i in range(n+1)]
w = [0] * (n+1)
for i, j in enumerate(ri()):
a[i+1] = j
for i in range(2, n+1):
t1, t2 = ri()
c[t1].append(i)
w[i] = t2
dfs(1, 0, c, w)
print(' '.join(ans))
sys.setrecursionlimit(10**5*3 + 100)
threading.stack_size(10**8 + 10**7)
thread = threading.Thread(target=solve)
thread.start()
``` | output | 1 | 67,754 | 13 | 135,509 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | instruction | 0 | 67,755 | 13 | 135,510 |
Tags: binary search, data structures, dfs and similar, graphs, trees
Correct Solution:
```
import sys
import threading
from bisect import *
from itertools import *
from collections import defaultdict
from math import log2
from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
sys.setrecursionlimit(10**5)
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
#def ri():
# return map(int, input().split())
@bootstrap
def dfs(v):
global d
d += 1
dist[d] = w[v] + dist[d-1]
add[d] = 0
for i in c[v]:
yield dfs(i)
x = bisect_left(dist, dist[d] - a[v], 0, d)
add[x-1] -= 1
add[d-1] += 1
add[d-1] += add[d]
ans[v] = add[d]
d -= 1
yield
d = 0
dist = [0]
dist = [0 for i in range(2*10**5+3)]
add = [0 for i in range(2*10**5+3)]
ans = [0 for i in range(2*10**5+3)]
n = int(input())
a = [0]
c = [[] for i in range(n+1)]
w = [0 for i in range(n+1)]
for i in map(int, input().split()):
a.append(i)
for i in range(2, n+1):
t1, t2 = map(int, input().split())
c[t1].append(i)
w[i] = t2
dfs(1)
print(' '.join(str(ans[i]) for i in range(1, n+1)))
``` | output | 1 | 67,755 | 13 | 135,511 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | instruction | 0 | 67,756 | 13 | 135,512 |
Tags: binary search, data structures, dfs and similar, graphs, trees
Correct Solution:
```
#!/usr/bin/env python3
import sys
import threading
from bisect import *
from itertools import *
#def ri():
# return map(int, input().split())
def dfs(v):
global d
d += 1
dist.append(w[v] + dist[d-1])
add[d] = 0
for i in c[v]:
dfs(i)
x = bisect_left(dist, dist[d] - a[v])
add[x-1] -= 1
add[d-1] += 1
add[d-1] += add[d]
ans[v] = add[d]
d -= 1
dist.pop()
if v == 1:
print(' '.join(str(ans[i]) for i in range(1, n+1)))
d = 0
dist = [0]
add = [0 for i in range(2*10**5+3)]
ans = [0 for i in range(2*10**5+3)]
n = int(input())
a = [0]
c = [[] for i in range(n+1)]
w = [0 for i in range(n+1)]
for i in map(int, input().split()):
a.append(i)
for i in range(2, n+1):
t1, t2 = map(int, input().split())
c[t1].append(i)
w[i] = t2
sys.setrecursionlimit(10**6)
threading.stack_size(10**7*8)
thread = threading.Thread(target=dfs, args=(1,))
thread.start()
if thread.is_alive():
thread.join()
``` | output | 1 | 67,756 | 13 | 135,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | instruction | 0 | 67,757 | 13 | 135,514 |
Tags: binary search, data structures, dfs and similar, graphs, trees
Correct Solution:
```
#!/usr/bin/env python3
import sys
import threading
from bisect import *
#def ri():
# return map(int, input().split())
def dfs(v, d, c, w):
d += 1
dist[d] = w[v] + dist[d-1]
add[d] = 0
for i in c[v]:
dfs(i, d, c, w)
x = bisect_left(dist, dist[d] - a[v], 0, d)
add[x-1] -= 1
add[d-1] += 1 + add[d]
ans[v] = str(add[d])
d -= 1
#d = 0
dist = [0] * (2*10**5+3)
add = [0] * (2*10**5+3)
n = int(input())
a = [0] * (n+1)
c = [[] for i in range(n+1)]
w = [0] * (n+1)
ans = [''] * (n+1)
for i, j in enumerate(map(int, input().split())):
a[i+1] = j
for i in range(2, n+1):
t1, t2 = map(int, input().split())
c[t1].append(i)
w[i] = t2
sys.setrecursionlimit(10**5*3 + 100)
threading.stack_size(10**8 + 10**7)
thread = threading.Thread(target=dfs, args=(1, 0, c, w))
thread.start()
if thread.is_alive():
thread.join()
print(' '.join(ans))
``` | output | 1 | 67,757 | 13 | 135,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | instruction | 0 | 67,758 | 13 | 135,516 |
Tags: binary search, data structures, dfs and similar, graphs, trees
Correct Solution:
```
import sys
import threading
from bisect import *
from itertools import *
#def ri():
# return map(int, input().split())
def dfs(v):
global d
d += 1
dist[d] = w[v] + dist[d-1]
add[d] = 0
for i in c[v]:
dfs(i)
x = bisect_left(dist, dist[d] - a[v], 0, d)
add[x-1] -= 1
add[d-1] += 1
add[d-1] += add[d]
ans[v] = add[d]
d -= 1
d = 0
dist = [0]
dist = [0 for i in range(2*10**5+3)]
add = [0 for i in range(2*10**5+3)]
ans = [0 for i in range(2*10**5+3)]
n = int(input())
a = [0]
c = [[] for i in range(n+1)]
w = [0 for i in range(n+1)]
for i in map(int, input().split()):
a.append(i)
for i in range(2, n+1):
t1, t2 = map(int, input().split())
c[t1].append(i)
w[i] = t2
sys.setrecursionlimit(10**6)
threading.stack_size(10**7*8)
thread = threading.Thread(target=dfs, args=(1,))
thread.start()
if thread.is_alive():
thread.join()
print(' '.join(str(ans[i]) for i in range(1, n+1)))
``` | output | 1 | 67,758 | 13 | 135,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | instruction | 0 | 67,759 | 13 | 135,518 |
Tags: binary search, data structures, dfs and similar, graphs, trees
Correct Solution:
```
#!/usr/bin/env python3
import sys
import threading
from bisect import *
#def ri():
# return map(int, input().split())
def dfs(v):
global d
d += 1
dist[d] = w[v] + dist[d-1]
add[d] = 0
for i in c[v]:
dfs(i)
x = bisect_left(dist, dist[d] - a[v], 0, d)
add[x-1] -= 1
add[d-1] += 1
add[d-1] += add[d]
ans[v] = add[d]
d -= 1
d = 0
dist = [0 for i in range(2*10**5+3)]
add = [0 for i in range(2*10**5+3)]
n = int(input())
a = [0 for i in range(n+1)]
c = [[] for i in range(n+1)]
w = [0 for i in range(n+1)]
ans = [0 for i in range(n+1)]
for i, j in enumerate(map(int, input().split())):
a[i+1] = j
for i in range(2, n+1):
t1, t2 = map(int, input().split())
c[t1].append(i)
w[i] = t2
sys.setrecursionlimit(10**6)
threading.stack_size(10**7*8)
thread = threading.Thread(target=dfs, args=(1,))
thread.start()
if thread.is_alive():
thread.join()
print(' '.join(str(ans[i]) for i in range(1, n+1)))
``` | output | 1 | 67,759 | 13 | 135,519 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).
Submitted Solution:
```
import sys
import threading
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
e = {}
g = [[] for i in range(n)]
d = [0]*(n+5)
ans = [0]*n
p = [0]*(n+5)
for i in range(n-1):
c, w = map(int, input().split())
c-= 1
g[c].append(i+1)
e[i+1] = w
def dfs(i, h):
global ans, a, e, g, d, p
p[h]=0
for j in g[i]:
d[h+1] = d[h]+e[j]
dfs(j, h+1)
x = bisect_left(d, d[h]-a[i], 0, h+1)
#print(x-1, i, h, d[h], d[h], a[i])
if x>=0:
p[x-1]-=1
p[h-1]+=p[h]+1
ans[i]=p[h]
def solve():
global ans
dfs(0, 0)
print(' '.join(map(str, ans)))
max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()
``` | instruction | 0 | 67,760 | 13 | 135,520 |
Yes | output | 1 | 67,760 | 13 | 135,521 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).
Submitted Solution:
```
# ==================================================
# Problem : 682C - Alyona and the Tree
# Run time : 0.405 sec.
# Language : Python 3
# ==================================================
from collections import deque
import sys
def bfs(n, adjList, a):
q = deque()
dist = [0] * (n+3)
vis = [False] * (n+3)
q.append(1)
vis[1] = True
cnt = 0
while q:
u = q.popleft()
if a[u] < dist[u]:
continue
cnt += 1
for (v, c) in adjList[u]:
if not vis[v]:
vis[v] = True
dist[v] = max(dist[u]+c, 0)
q.append(v)
return cnt
def main():
# sys.stdin = open("in.txt", "r")
it = iter(map(int, sys.stdin.read().split()))
n = next(it)
a = [0] * (n+3)
adjList = [[] for _ in range(n+3)]
for i in range(1, n+1):
a[i] = next(it)
for i in range(1, n):
p = next(it)
c = next(it)
adjList[i+1].append((p, c))
adjList[p].append((i+1, c))
ans = n - bfs(n, adjList, a)
sys.stdout.write(str(ans) + '\n')
if __name__ == '__main__':
main()
``` | instruction | 0 | 67,761 | 13 | 135,522 |
No | output | 1 | 67,761 | 13 | 135,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).
Submitted Solution:
```
#!/usr/bin/env python3
import sys
import threading
from bisect import *
MAX_RECUR_SIZE = 10**5*3 + 100
MAX_STACK_SIZE = 10**8 + 10**7
MAX_NODE = 2*10**5 + 1
def dfs(v, d, c, w):
d += 1
dist[d] = w[v] + dist[d-1]
add[d] = 0
for i in c[v]:
dfs(i, d, c, w)
x = bisect_left(dist, dist[d] - a[v], 0, d)
add[x-1] -= 1
add[d-1] += 1
add[d-1] += add[d]
ans[v] = str(add[d])
d -= 1
dist = [0] * MAX_NODE
add = [0] * MAX_NODE
n = int(input())
a = [0] * (n+1)
c = [[] for i in range(n+1)]
w = [0] * (n+1)
ans = [''] * (n+1)
for i, j in enumerate(map(int, input().split())):
a[i+1] = j
for i in range(2, n+1):
t1, t2 = map(int, input().split())
c[t1].append(i)
w[i] = t2
sys.setrecursionlimit(MAX_RECUR_SIZE)
threading.stack_size(MAX_STACK_SIZE)
thread = threading.Thread(target=dfs, args=(1, 0, c, w))
thread.start()
if thread.is_alive():
thread.join()
print(' '.join(ans))
``` | instruction | 0 | 67,762 | 13 | 135,524 |
No | output | 1 | 67,762 | 13 | 135,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).
Submitted Solution:
```
import sys
import threading
from bisect import *
MAX_RECUR_SIZE = 10**5*3 + 100
MAX_STACK_SIZE = 10**8 + 10**7
MAX_NODE = 2*10**5 + 1
def dfs(v, d, c, w):
d += 1
dist[d] = w[v] + dist[d-1]
add[d] = 0
for i in c[v]:
dfs(i, d, c, w)
x = bisect_left(dist, dist[d] - a[v], 0, d)
add[x-1] -= 1
add[d-1] += 1 + add[d]
ans[v] = str(add[d])
d -= 1
dist = [0] * MAX_NODE
add = [0] * MAX_NODE
n = int(input())
a = [0] * (n+1)
c = [[] for i in range(n+1)]
w = [0] * (n+1)
ans = [''] * (n+1)
for i, j in enumerate(map(int, input().split())):
a[i+1] = j
for i in range(2, n+1):
t1, t2 = map(int, input().split())
c[t1].append(i)
w[i] = t2
sys.setrecursionlimit(MAX_RECUR_SIZE)
threading.stack_size(MAX_STACK_SIZE)
thread = threading.Thread(target=dfs, args=(1, 0, c, w))
thread.start()
if thread.is_alive():
thread.join()
print(' '.join(ans))
``` | instruction | 0 | 67,763 | 13 | 135,526 |
No | output | 1 | 67,763 | 13 | 135,527 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v β u) if and only if u is in the subtree of v and dist(v, u) β€ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
Input
The first line contains single integer n (1 β€ n β€ 2Β·105).
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 109) β the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 β€ pi β€ n, 1 β€ wi β€ 109) β the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Output
Print n integers β the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
Examples
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
Note
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).
Submitted Solution:
```
def list_from_input():
return list(map(int, input().split()))
class Vertex:
def __init__(self, index, path_to):
self.path_to = path_to
self.index = index
def deep_search(tree, root, vertex_numbers):
under_root_control = 0
vertices = [Vertex(index=root, path_to=0)]
while len(vertices) > 0:
current_vertex = vertices.pop()
# add linked vertices
for linked_vertex, path_to in enumerate(tree[current_vertex.index]):
if path_to is not None:
path_to_linked = path_to + current_vertex.path_to
linked_vertex_number = vertex_numbers[linked_vertex]
if path_to_linked < linked_vertex_number:
vertices.append(Vertex(linked_vertex, path_to_linked))
under_root_control += 1
return under_root_control
def main():
vertex_count = int(input())
vertex_numbers = list_from_input()
tree = [[None for x in range(vertex_count)] for y in range(vertex_count)]
for i in range(1, vertex_count):
v1 = i
v2, edge_cost = list_from_input()
tree[v2-1][v1] = edge_cost # Π΅ΡΡΡ ΡΠΎΠ»ΡΠΊΠΎ ΡΠΏΡΡΠΊ
for v in range(vertex_count):
print(deep_search(tree, v, vertex_numbers), end = ' ')
main()
``` | instruction | 0 | 67,764 | 13 | 135,528 |
No | output | 1 | 67,764 | 13 | 135,529 |
Provide tags and a correct Python 3 solution for this coding contest problem.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers β the number of vertices n and the number of edges m of the graph (1 β€ n β€ 100, 0 β€ m β€ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 β€ x, y β€ n, x β y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root. | instruction | 0 | 68,160 | 13 | 136,320 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
inp = input().split()
n = int(inp[0])
m = int(inp[1])
def dfs(x):
visited.add(x)
for y in e[x]:
if not y in visited:
dfs(y)
if n >= 3 and n == m:
visited = set()
e = [[] for i in range(n + 1)]
for i in range(m):
x, y = map(int, input().split())
e[x].append(y)
e[y].append(x)
dfs(1)
if len(visited) == n:
print('FHTAGN!')
else:
print('NO')
else:
print('NO')
``` | output | 1 | 68,160 | 13 | 136,321 |
Provide tags and a correct Python 3 solution for this coding contest problem.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers β the number of vertices n and the number of edges m of the graph (1 β€ n β€ 100, 0 β€ m β€ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 β€ x, y β€ n, x β y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root. | instruction | 0 | 68,161 | 13 | 136,322 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
def dfs (num,av):
global res; b.add(num)
for v in g[num]:
if v!=av:
if v in b: res += 1; g[v].remove(num)
else:b.add(v); dfs(v,num)
n,m = map (int,input().split())
g,b,res = [[] for _ in range(n)], set(),0
for _ in range(m):
u,v = map(int,input().split())
g[u-1].append(v-1); g[v-1].append(u-1)
dfs(0,0)
if len(b) == n and res == 1: print("FHTAGN!")
else: print("NO")
``` | output | 1 | 68,161 | 13 | 136,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers β the number of vertices n and the number of edges m of the graph (1 β€ n β€ 100, 0 β€ m β€ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 β€ x, y β€ n, x β y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root. | instruction | 0 | 68,162 | 13 | 136,324 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
n, m = [int(i) for i in input().split()]
c = [int(i) for i in range(n+1)]
def find (u):
if u == c[u]:
return u
c[u] = find(c[u])
return c[u]
ciclos = 0
for i in range(m):
x, y = [int(j) for j in input().split()]
x = find(x)
y = find(y)
if find(x) != find(y):
c[x] = c[y] = max(x, y)
else:
ciclos += 1
conexo = True
componente = find(1)
for i in range(2, n+1, 1):
if find(i) != componente:
conexo = False
if conexo and ciclos == 1:
print('FHTAGN!')
else:
print('NO')
exit(0)
``` | output | 1 | 68,162 | 13 | 136,325 |
Provide tags and a correct Python 3 solution for this coding contest problem.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers β the number of vertices n and the number of edges m of the graph (1 β€ n β€ 100, 0 β€ m β€ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 β€ x, y β€ n, x β y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root. | instruction | 0 | 68,163 | 13 | 136,326 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from collections import *
from sys import stdin
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return list(stdin.readline()[:-1])
class disjointset:
def __init__(self, n):
self.rank, self.parent, self.n, self.nsets, self.edges, self.gdict = [0] * (n + 1), [0] * (n + 1), n, [1] * (
n + 1), [], defaultdict(list)
self.add_nodes(n)
def add_nodes(self, n):
for i in range(1, n + 1):
self.parent[i], self.nsets[i] = i, 1
def add_edge(self, node1, node2, w=None):
self.gdict[node1].append(node2)
self.gdict[node2].append(node1)
self.edges.append([node1, node2])
def dfsUtil(self, v, c):
stack = [v]
while (stack):
s = stack.pop()
for i in self.gdict[s]:
if not self.visit[i]:
stack.append(i)
self.visit[i] = 1
self.color[i] = c
# dfs for graph
def dfs(self):
self.cnt, self.visit, self.color = 0, defaultdict(int), defaultdict(int)
for i in range(1, n + 1):
if self.visit[i] == 0:
self.dfsUtil(i, self.cnt)
self.cnt += 1
def find(self, x):
result, stack = self.parent[x], [x]
while result != x:
x = result
result = self.parent[x]
stack.append(x)
while stack:
self.parent[stack.pop()] = result
return result
def union(self, x, y):
xpar, ypar = self.find(x), self.find(y)
# already union
if xpar == ypar:
return
# perform union by rank
par, child = 0, 0
if self.rank[xpar] < self.rank[ypar]:
par, child = ypar, xpar
elif self.rank[xpar] > self.rank[ypar]:
par, child = xpar, ypar
else:
par, child = xpar, ypar
self.rank[xpar] += 1
self.parent[child] = par
self.nsets[par] += self.nsets[child]
self.n -= 1
def kruskal(self):
result, edges, self.cycle = [], self.edges, defaultdict(int)
# loop over v-1
for i in range(len(edges)):
u, v = edges[i]
upar, vpar = self.find(u), self.find(v)
# no cycle
if upar != vpar:
result.append(edges[i])
self.union(upar, vpar)
else:
if self.cycle[self.color[upar]] == 0:
self.cycle[self.color[upar]] += 1
else:
exit(print('NO'))
n, m = arr_inp(1)
dis, ans = disjointset(n), 0
for i in range(m):
u, v = arr_inp(1)
dis.add_edge(u, v)
dis.dfs()
dis.kruskal()
# print(dis.cycle, dis.n)
print('FHTAGN!' if dis.n == 1 and sum(dis.cycle.values()) == dis.n else 'NO')
``` | output | 1 | 68,163 | 13 | 136,327 |
Provide tags and a correct Python 3 solution for this coding contest problem.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers β the number of vertices n and the number of edges m of the graph (1 β€ n β€ 100, 0 β€ m β€ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 β€ x, y β€ n, x β y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root. | instruction | 0 | 68,164 | 13 | 136,328 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys
def getroot(lab, u):
if lab[u] == -1:
return u
lab[u] = getroot(lab, lab[u])
return lab[u]
def union(lab, cou, a, b):
if cou[a] > cou[b]:
cou[a] += cou[b]
lab[b] = a
else:
cou[b] += cou[a]
lab[a] = b
def inp():
return map(int, input().split())
def solve():
n, m = inp()
lab = [-1 for i in range(n)]
cou = [1 for i in range(n)]
if n != m:
print("NO") #impossible
return
for i in range(m):
u, v = inp()
u = getroot(lab, u-1)
v = getroot(lab, v-1)
if u != v:
union(lab, cou, u, v)
if lab.count(-1) > 1: #not connected
print("NO")
return
print("FHTAGN!")
solve()
``` | output | 1 | 68,164 | 13 | 136,329 |
Provide tags and a correct Python 3 solution for this coding contest problem.
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.
To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.
It is guaranteed that the graph contains no multiple edges and self-loops.
<image>
Input
The first line contains two integers β the number of vertices n and the number of edges m of the graph (1 β€ n β€ 100, 0 β€ m β€ <image>).
Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1 β€ x, y β€ n, x β y). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Output
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
Examples
Input
6 6
6 3
6 4
5 1
2 5
1 4
5 4
Output
FHTAGN!
Input
6 5
5 6
4 6
3 1
5 1
1 2
Output
NO
Note
Let us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., v - 1 and v, v and 1.
A tree is a connected undirected graph consisting of n vertices and n - 1 edges (n > 0).
A rooted tree is a tree where one vertex is selected to be the root. | instruction | 0 | 68,165 | 13 | 136,330 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
n,m=map(int,input().split())
a=[[] for _ in range(n+1)]
vis=[]
for _ in range(m):
x,y=map(int,input().split())
a[x].append(y)
a[y].append(x)
def dfs(x):
vis.append(x)
for z in a[x]:
if not(z in vis):
dfs(z)
dfs(1)
if n<3 or n!=m or len(vis)!=n:
print("NO")
else:
print("FHTAGN!")
``` | output | 1 | 68,165 | 13 | 136,331 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.