text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 109).
Output
Print the smallest integer x > n, so it is divisible by the number k.
Examples
Input
5 3
Output
6
Input
25 13
Output
26
Input
26 13
Output
39
Tags: implementation, math
Correct Solution:
```
s= input("").split(' ')
n= int(s[0])
k= int(s[1])
if k>n:
print(str(k))
else:
a=int(n/k)
counter= k*a
while True:
if(counter>n):
print(str(counter))
break
counter=counter+k
```
| 99,900 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 109).
Output
Print the smallest integer x > n, so it is divisible by the number k.
Examples
Input
5 3
Output
6
Input
25 13
Output
26
Input
26 13
Output
39
Submitted Solution:
```
[n, k] = map(int, input() .split())
a = int(n//k + 1)
b = int(k*a)
print(b)
```
Yes
| 99,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 109).
Output
Print the smallest integer x > n, so it is divisible by the number k.
Examples
Input
5 3
Output
6
Input
25 13
Output
26
Input
26 13
Output
39
Submitted Solution:
```
from math import ceil
c, d=map(int, input().split())
if c%d==0:
g=ceil(c/d)+1
print(d*g)
else:
g=ceil(c/d)
print(d*g)
```
Yes
| 99,902 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 109).
Output
Print the smallest integer x > n, so it is divisible by the number k.
Examples
Input
5 3
Output
6
Input
25 13
Output
26
Input
26 13
Output
39
Submitted Solution:
```
t,x = list(map(int,input().strip().split(' ')))
tmp = (t//x)*x
res = tmp if tmp > t else tmp+x
print(res)
```
Yes
| 99,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 109).
Output
Print the smallest integer x > n, so it is divisible by the number k.
Examples
Input
5 3
Output
6
Input
25 13
Output
26
Input
26 13
Output
39
Submitted Solution:
```
#import sys
#sys.stdin = open('in', 'r')
#n = int(input())
#a = [int(x) for x in input().split()]
n,k = map(int, input().split())
print(k*(n//k) + k)
```
Yes
| 99,904 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 109).
Output
Print the smallest integer x > n, so it is divisible by the number k.
Examples
Input
5 3
Output
6
Input
25 13
Output
26
Input
26 13
Output
39
Submitted Solution:
```
from math import sqrt
n , k = map(int,input().split())
i = n
while i <= sqrt(10**9):
if i > n and i % k == 0 :
print(i)
break
i +=1
```
No
| 99,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 109).
Output
Print the smallest integer x > n, so it is divisible by the number k.
Examples
Input
5 3
Output
6
Input
25 13
Output
26
Input
26 13
Output
39
Submitted Solution:
```
from math import ceil
c, d=map(int, input().split())
if c%d==0:
g=ceil(c/d)+1
print(d*g)
else:
g=ceil(c/d)+1
print(d*g)
```
No
| 99,906 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 109).
Output
Print the smallest integer x > n, so it is divisible by the number k.
Examples
Input
5 3
Output
6
Input
25 13
Output
26
Input
26 13
Output
39
Submitted Solution:
```
n, k = map(int, input().split())
print((n + 1) // k * k)
```
No
| 99,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.
Input
The only line contains two integers n and k (1 ≤ n, k ≤ 109).
Output
Print the smallest integer x > n, so it is divisible by the number k.
Examples
Input
5 3
Output
6
Input
25 13
Output
26
Input
26 13
Output
39
Submitted Solution:
```
a,b=map(int,input().split())
m=list(range(b,a+b,b))
if a==b:
print(a*2)
elif a<b:
print(b)
else:
for i in m:
if i>a :
print(i)
exit(0)
```
No
| 99,908 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Tags: binary search, math
Correct Solution:
```
raw = input().split()
import decimal
n = int(raw[0])
k = int(raw[4])
def get(n,k):
if(n%k==0):
return n//k
else:
return n//k + 1
n = decimal.Decimal(str(get(n,k)))
l = decimal.Decimal(str(raw[1]))
v1 = decimal.Decimal(str(raw[2]))
v2 = decimal.Decimal(str(raw[3]))
print(l/v2*(decimal.Decimal('1')+(decimal.Decimal('2')*(n-decimal.Decimal(1))*(v2-v1))/(decimal.Decimal(2)*v1*n+v2-v1)))
```
| 99,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Tags: binary search, math
Correct Solution:
```
import math
n,L,v1,v2,k = [int(x) for x in input().split()]
n = int(math.ceil(n/k))
a = v2/v1
x = (2*L)/(a+2*n-1)
y = L-(n-1)*x
print((y*n+(n-1)*(y-x))/v2)
```
| 99,910 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Tags: binary search, math
Correct Solution:
```
n, L, v1, v2, k = map(int, input().split())
dif = v2 - v1
n = (n + k - 1) // k * 2
p1 = (n * v2 - dif) * L
p2 = (n * v1 + dif) * v2
print(p1 / p2)
```
| 99,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Tags: binary search, math
Correct Solution:
```
import math
n, l, v1, v2, k = map(int, input().split(' '))
p = math.ceil(n/k)
def calc(d):
cyc = ((d-d/v2*v1)/(v1+v2))
t = cyc + d/v2
#t is the time per cycle
ans = -1
for i in range(p):
tb4 = t * i;
db4 = tb4 * v1
ans = max(ans, (d/v2+tb4+max(0, l-d-db4)/v1))
return ans
lo = 0
hi = 1000000000
for i in range(200):
a1 = (2*lo+hi)/3
a2 = (lo+2*hi)/3
if calc(a1)<calc(a2):
hi=a2
else:
lo=a1
print(calc(lo))
```
| 99,912 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Tags: binary search, math
Correct Solution:
```
#!/usr/local/bin/python3
# -*- coding:utf-8 -*-
import math
inputParams = input().split()
n = int(inputParams[0])
l = int(inputParams[1])
v1 = int(inputParams[2])
v2 = int(inputParams[3])
k = int(inputParams[4])
# 运送次数
times = math.ceil(n / k)
t1 = l / (v2 + (2 * v2 / (v2 + v1)) * v1 * (times - 1))
totalTime = t1 + (2 * v2 / (v1 + v2)) * t1 * (times - 1)
print(str(totalTime))
```
| 99,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Tags: binary search, math
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,l,v1,v2,k=map(int,input().split())
n=int(math.ceil(n/k))
r=v2/v1
x=l*(r+1)
x/=(2*n+r-1)
ans=((n-1)*2*x)/(r+1)
ans+=x/r
print(ans/v1)
```
| 99,914 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Tags: binary search, math
Correct Solution:
```
n,l,v1,v2,k=map(int,input().split())
m=(n-1)//k+1
v=v1+v2
x=l/(1+(m-1)*(v1*(1-v1/v2)/(v2+v1)+v1/v2))
print(x/v2+(l-x)/v1)
```
| 99,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Tags: binary search, math
Correct Solution:
```
n,l,v1,v2,k=map(int,input().split())
n=(n+k-1)//k
a=(v2-v1)/(v1+v2)
t=l/v2/(n-(n-1)*a)
print(n*t+(n-1)*a*t)
# Made By Mostafa_Khaled
```
| 99,916 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Submitted Solution:
```
n,l,v,o,k=map(int,input().split())
T=(n+k-1)//k
e=1-v/o
L=l/v/(T/o+T*e/(v+o)-e/(v+o)-1/o+1/v)
print((l-L)/v+L/o)
```
Yes
| 99,917 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Submitted Solution:
```
n,l,v1,v2,k=map(int,input().split())
n=(n+k-1)//k
a=(v2-v1)/(v1+v2)
t=l/v2/(n-(n-1)*a)
print(n*t+(n-1)*a*t)
```
Yes
| 99,918 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Submitted Solution:
```
n, l, v1, v2, k = map(int, input().split())
diff = v2 - v1
n = (n + k - 1) // k * 2
p1 = (n * v2 - diff) * l
p2 = (n * v1 + diff) * v2
print(p1 / p2)
```
Yes
| 99,919 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Submitted Solution:
```
import sys
import math
data = sys.stdin.read()
data = data.split(' ')
n = int(data[0])
l = int(data[1])
w = int(data[2])
v = int(data[3])
k = int(data[4])
z = math.ceil(n/k)
top = l/w - l/(2*w*z) + l/(2*v*z)
bot = 1 + v/(2*w*z) - 1/(2*z)
print(top/bot)
```
Yes
| 99,920 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,l,v1,v2,k=map(int,input().split())
n=int(math.ceil(n/k))
r=v2/v1
x=l*(r+1)
x/=(2*n+r-1)
ans=((n-1)*2*x)/(r+1)
ans+=x/r
print(ans*v1)
```
No
| 99,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Submitted Solution:
```
n, L, v1, v2, k = map(int, input().split())
dif = v2 - v1
n = (n + k - 1) // 2 * k
p1 = (n * v2 - dif) * L
p2 = (n * v1 + dif) * L
print(p1 / p2)
```
No
| 99,922 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Submitted Solution:
```
n, l, v1, v2, k = map(int, input().split())
n, u = (n + k - 1) // k, v1 * (n - 1)
a, b, c, d, e, f = u + v2, u, l, n, 1-n, l/v2
D, E, F = a * e - b * d, c * e - f * b, a * f - d * c
print((E * n + F * (n - 1)) / D)
```
No
| 99,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once.
Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected.
Input
The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus.
Output
Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6.
Examples
Input
5 10 1 2 5
Output
5.0000000000
Input
3 6 1 2 1
Output
4.7142857143
Note
In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
Submitted Solution:
```
n, l, v1, v2, k = map(int, input().split())
T = 0
if (n==3) and(l==6) and(v1==1) and(v2==2) and(k==1):
l = -123123 # Как бы тупо то ни было
T = 4.7142857143
t = l/v2 # Время, за которое автобус доезжает до места
while l > 0:
n -= k # Автобус забирает пассажиров
T += t # Общее время
l -= t*v1 # От общего расстояния отнимается пройденное школьниками
if n < 1:
break
t = l/(v1+v2) # Время, за которое автобус и школьники встречаются
T += t # Общее время
l -= t*v1 # От общего расстояния отнимается пройденное школьниками
print(format(T, '.10f'))
```
No
| 99,924 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Tags: data structures, dsu
Correct Solution:
```
#!/usr/bin/python3
size = int(input())
num = list(map(int, input().split()))
rem = reversed(list(map(lambda x: int(x) - 1, input().split())))
chunks = [None] * size
res = [-1] * size
ans = [0] * size
ms = -1
def addChunk(n):
chunks[n] = [n, num[n]]
return n
def getRoot(n):
while chunks[n][0] != n:
n = chunks[n][0]
return n
def mergeChunks(parent, child):
proot = getRoot(parent)
croot = getRoot(child)
chunks[croot][0] = proot
chunks[proot][1] += chunks[croot][1]
return proot
for i in rem:
res[i] = num[i]
root = addChunk(i)
if i > 0 and chunks[i - 1] != None:
root = mergeChunks(i - 1, i)
if i + 1 < size and chunks[i + 1] != None:
root = mergeChunks(i, i + 1)
ms = max(ms, chunks[root][1])
ans.append(ms)
for i in range(1, size):
print (ans[-i-1])
print(0)
```
| 99,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Tags: data structures, dsu
Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 9 16:14:34 2016
@author: kostiantyn.omelianchuk
"""
from sys import stdin, stdout
lines = stdin.readlines()
n = int(lines[0])
a = [int(x) for x in lines[1].split()]
b = [int(x) for x in lines[2].split()]
check_array = [0 for i in range(n)]
snm = [i for i in range(n)]
r = [1 for i in range(n)]
sums = dict(zip(range(n), a))
def find_x(x):
if snm[x] != x:
snm[x] = find_x(snm[x])
return snm[x]
def union(x_start, y_start):
x = find_x(x_start)
y = find_x(y_start)
sums[x] += sums[y]
sums[y] = sums[x]
if x == y:
return x
#sums[x] += sums[x_start]
if r[x] == r[y]:
r[x] += 1
if r[x] < r[y]:
snm[x] = y
return y
else:
snm[y] = x
return x
max_list = []
total_max = 0
for i in range(n):
cur_sum = 0
flag = 0
max_list.append(total_max)
#pos = n-i-1
elem = b[n-i-1] - 1
check_array[elem] = 1
#pos_x = find_x(elem)
if elem>0:
if check_array[elem-1] == 1:
pos = union(elem-1,elem)
cur_sum = sums[pos]
#print(sums, check_array, total_max, cur_sum, elem, find_x(elem))
else:
flag += 1
else:
flag += 1
if elem<(n-1):
if check_array[elem+1] == 1:
pos = union(elem,elem+1)
cur_sum = sums[pos]
#print(sums, check_array, total_max, cur_sum, elem, find_x(elem))
else:
flag += 1
else:
flag += 1
if flag == 2:
total_max = max(total_max,sums[elem])
else:
total_max = max(cur_sum, total_max)
max_list.append(total_max)
for j in range(1,n+1):
print(max_list[n-j])
```
| 99,926 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Tags: data structures, dsu
Correct Solution:
```
import sys
MAX = 100005
arr = MAX * [0]
pre = MAX * [0]
ix = MAX * [0]
sun = MAX * [0]
ans = MAX * [0]
vis = MAX * [False]
mx = 0
def find(x):
if x == pre[x]:
return x
pre[x] = find(pre[x])
return pre[x]
def unite(x, y):
dx = find(x)
dy = find(y)
if dx == dy:
return
pre[dx] = dy
sun[dy] += sun[dx]
n = int(input())
arr = [int(i) for i in input().split()]
arr.insert(0, 0)
sun = arr
pre = [i for i in range(n+1)]
ix = [int(i) for i in input().split()]
for i in range(n-1, -1, -1):
x = ix[i]
ans[i] = mx
vis[x] = True
if x != 1 and vis[x-1]:
unite(x-1, x)
if x != n and vis[x+1]:
unite(x, x+1)
mx = max(mx, sun[find(x)])
for i in range(n):
print(ans[i])
```
| 99,927 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Tags: data structures, dsu
Correct Solution:
```
import sys
input = sys.stdin.readline
class Unionfind:
def __init__(self, n):
self.par = [-1]*n
self.rank = [1]*n
def root(self, x):
p = x
while not self.par[p]<0:
p = self.par[p]
while x!=p:
tmp = x
x = self.par[x]
self.par[tmp] = p
return p
def unite(self, x, y):
rx, ry = self.root(x), self.root(y)
if rx==ry: return False
if self.rank[rx]<self.rank[ry]:
rx, ry = ry, rx
self.par[rx] += self.par[ry]
self.par[ry] = rx
if self.rank[rx]==self.rank[ry]:
self.rank[rx] += 1
def is_same(self, x, y):
return self.root(x)==self.root(y)
def count(self, x):
return -self.par[self.root(x)]
n = int(input())
a = list(map(int, input().split()))
p = list(map(int, input().split()))
uf = Unionfind(n)
V = [0]*n
flag = [False]*n
ans = [0]
for pi in p[::-1]:
pi -= 1
V[pi] = a[pi]
flag[pi] = True
if pi-1>=0 and flag[pi-1]:
v = V[uf.root(pi-1)]+V[uf.root(pi)]
uf.unite(pi-1, pi)
V[uf.root(pi)] = v
if pi+1<n and flag[pi+1]:
v = V[uf.root(pi+1)]+V[uf.root(pi)]
uf.unite(pi, pi+1)
V[uf.root(pi)] = v
ans.append(max(ans[-1], V[uf.root(pi)]))
for ans_i in ans[:-1][::-1]:
print(ans_i)
```
| 99,928 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Tags: data structures, dsu
Correct Solution:
```
class DSU:
def __init__(self, n):
self.par = list(range(n))
self.arr = list(map(int, input().split()))
self.siz = [1] * n
self.sht = [0] * n
self.max = 0
def find(self, n):
nn = n
while nn != self.par[nn]:
nn = self.par[nn]
while n != nn:
self.par[n], n = nn, self.par[n]
return n
def union(self, a, b):
a = self.find(a)
b = self.find(b)
if a == b:
return
if self.siz[a] < self.siz[b]:
a, b = b, a
self.par[b] = a
self.siz[a] += self.siz[b]
self.arr[a] += self.arr[b]
if self.arr[a] > self.max:
self.max = self.arr[a]
def add_node(self, n):
self.sht[n] = 1
if self.arr[n] > self.max:
self.max = self.arr[n]
if n != len(self.par) - 1 and self.sht[n + 1]:
self.union(n, n + 1)
if n != 0 and self.sht[n - 1]:
self.union(n, n - 1)
def main():
import sys
input = sys.stdin.readline
n = int(input())
dsu = DSU(n)
per = list(map(int, input().split()))
ans = [0] * n
for i in range(n):
ans[~i] = dsu.max
dsu.add_node(per[~i] - 1)
for x in ans:
print(x)
return 0
main()
```
| 99,929 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Tags: data structures, dsu
Correct Solution:
```
def main():
n, aa = int(input()), [0, *map(int, input().split()), 0]
l, clusters, mx = list(map(int, input().split())), [0] * (n + 2), 0
for i in range(n - 1, -1, -1):
a = clusters[a] = l[i]
l[i] = mx
for i in a - 1, a + 1:
if clusters[i]:
stack, j = [], i
while j != clusters[j]:
stack.append(j)
j = clusters[j]
for i in stack:
clusters[i] = j
aa[a] += aa[j]
clusters[j] = a
if mx < aa[a]:
mx = aa[a]
print('\n'.join(map(str, l)))
if __name__ == '__main__':
main()
```
| 99,930 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Tags: data structures, dsu
Correct Solution:
```
# Bosdiwale code chap kr kya milega
# Motherfuckers Don't copy code for the sake of doing it
# ..............
# ╭━┳━╭━╭━╮╮
# ┃┈┈┈┣▅╋▅┫┃
# ┃┈┃┈╰━╰━━━━━━╮
# ╰┳╯┈┈┈┈┈┈┈┈┈◢▉◣
# ╲┃┈┈┈┈┈┈┈┈┈┈▉▉▉
# ╲┃┈┈┈┈┈┈┈┈┈┈◥▉◤
# ╲┃┈┈┈┈╭━┳━━━━╯
# ╲┣━━━━━━┫
# ……….
# .……. /´¯/)………….(\¯`\
# …………/….//……….. …\\….\
# ………/….//……………....\\….\
# …./´¯/…./´¯\……/¯ `\…..\¯`\
# ././…/…/…./|_…|.\….\….\…\.\
# (.(….(….(…./.)..)...(.\.).).)
# .\…………….\/../…....\….\/…………/
# ..\…………….. /……...\………………../
# …..\…………… (………....)……………./
n = int(input())
arr = list(map(int,input().split()))
ind = list(map(int,input().split()))
parent = {}
rank = {}
ans = {}
total = 0
temp = []
def make_set(v):
rank[v] = 1
parent[v] = v
ans[v] = arr[v]
def find_set(u):
if u==parent[u]:
return u
else:
parent[u] = find_set(parent[u])
return parent[u]
def union_set(u,v):
a = find_set(u)
b = find_set(v)
if a!=b:
if rank[b]>rank[a]:
a,b = b,a
parent[b] = a
rank[a]+=rank[b]
ans[a]+=ans[b]
return ans[a]
for i in range(n-1,-1,-1):
rem = ind[i]-1
make_set(rem)
final = ans[rem]
if rem+1 in parent:
final = union_set(rem,rem+1)
if rem-1 in parent:
final = union_set(rem,rem-1)
total = max(total,final)
temp.append(total)
temp[-1] = 0
temp = temp[-1::-1]
temp = temp[1::]
for i in temp:
print(i)
print(0)
```
| 99,931 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Tags: data structures, dsu
Correct Solution:
```
def main():
def f(x):
l = []
while x != clusters[x]:
l.append(x)
x = clusters[x]
for y in l:
clusters[y] = x
return x
n, aa = int(input()), [0, *map(int, input().split()), 0]
l, clusters, mx = list(map(int, input().split())), [0] * (n + 2), 0
for i in range(n - 1, -1, -1):
a = clusters[a] = l[i]
l[i] = mx
for i in a - 1, a + 1:
if clusters[i]:
j = f(i)
aa[a] += aa[j]
clusters[j] = a
f(i)
if mx < aa[a]:
mx = aa[a]
print('\n'.join(map(str, l)))
if __name__ == '__main__':
main()
```
| 99,932 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Submitted Solution:
```
# bharatkulratan
# 12:09 PM, 26 Jun 2020
import os
from io import BytesIO
class IO:
def __init__(self):
self.input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
def read_int(self):
return int(self.input())
def read_ints(self):
return [int(x) for x in self.input().split()]
class Node:
def __init__(self, data):
self.data = data
self.sum = data
self.rank = 0
self.parent = self
def __repr__(self):
return f"data = {self.data}, sum = {self.sum}, " \
f"rank = {self.rank}, parent = {self.parent.data}"
class UnionFind:
def __init__(self):
# mapping from data to corresponding node
self.map = {}
def makeset(self, index, data):
self.map[index] = Node(data)
def find_parent(self, data):
return self.find(self.map.get(data))
def find(self, node):
# whether they're both same object
if node.parent is node: return node
return self.find(node.parent)
def union(self, left, right):
left_par = self.find(left)
right_par = self.find(right)
if left_par is right_par: return
if left_par.rank >= right_par.rank:
if left_par.rank == right_par.rank: left_par.rank += 1
right_par.parent = left_par
left_par.sum += right_par.sum
else:
left_par.parent = right_par
right_par.sum += left_par.sum
def main():
io = IO()
n = io.read_int()
uf = UnionFind()
arr = io.read_ints()
for index, elem in enumerate(arr):
uf.makeset(index+1, elem)
perm = io.read_ints()
perm.reverse()
result = []
answer = 0
result.append(answer)
entry = [-1] * (n+2)
for pos in perm[:-1]:
left_neighbor = pos-1
right_neighbor = pos+1
if entry[left_neighbor] > -1:
left_parent = uf.find_parent(left_neighbor)
node = uf.find_parent(pos)
uf.union(left_parent, node)
answer = max(answer, uf.find_parent(pos).sum)
if entry[right_neighbor] > -1:
right_parent = uf.find_parent(right_neighbor)
node = uf.find_parent(pos)
uf.union(node, right_parent)
answer = max(answer, uf.find_parent(pos).sum)
if entry[left_neighbor] == -1 and entry[right_neighbor] == -1:
answer = max(answer, uf.find_parent(pos).sum)
entry[pos] = arr[pos-1]
result.append(answer)
for _ in result[::-1]: print(_)
if __name__ == "__main__":
main()
```
Yes
| 99,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Submitted Solution:
```
import math,sys,bisect,heapq,os
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
def input(): return sys.stdin.readline().rstrip('\r\n')
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
ans = 0
def solve():
n, = aj()
a = aj()
p = aj()
valid = [False for i in range(n)]
parent = [0] * n
size = [0] * n
stat = [0] * n
def find(x):
while parent[x] != x:
x = parent[x]
return x
def union(a, b):
x = find(a)
y = find(b)
if x == y:
return
elif size[x] < size[y]:
parent[x] = y
size[y] += size[x]
stat[y] += stat[x]
else:
parent[y] = x
size[x] += size[y]
stat[x] += stat[y]
ans = [0]
for i in range(n - 1, 0, -1):
k = p[i] - 1
valid[k] = True
parent[k] = k
stat[k] = a[k]
if k > 0 and valid[k - 1]:
union(k, k - 1)
if k < n - 1 and valid[k + 1]:
union(k, k + 1)
t = stat[find(k)]
m = max(ans[-1], t)
ans.append(m)
while ans:
print(ans.pop())
try:
#os.system("online_judge.py")
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
solve()
```
Yes
| 99,934 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split()))
mod = 10**9+7; Mod = 998244353; INF = float('inf')
#______________________________________________________________________________________________________
# from math import *
# from bisect import *
# from heapq import *
# from collections import defaultdict as dd
# from collections import OrderedDict as odict
# from collections import Counter as cc
# from collections import deque
sys.setrecursionlimit(2*(10**5)+100) #this is must for dfs
# ___________________________________________________________
from heapq import *
n = int(input())
a = [0]+list(map(int,input().split()))
b = list(map(int,input().split()))
ans = []
best = 0
vis = [False for i in range(n+1)]
value = a.copy()
par = [-1]*(n+1)
def find(c):
if par[c]<0:
return c,-value[c]
par[c],trash = find(par[c])
return par[c],trash
def union(a1,b1):
if vis[b1]==False:
return value[a1]
pa,val1 = find(a1)
pb,val2 = find(b1)
if pa==pb:
return False
if par[pa]>par[pb]:
par[pb]+=par[pa]
par[pa] = pb
value[pb]+=value[pa]
return value[pb]
else:
par[pa]+=par[pb]
par[pb] = pa
value[pa]+=value[pb]
return value[pa]
for i in range(n):
ans.append(best)
ind = b.pop()
vis[ind] = True
if ind+1<=n:
res = union(ind,ind+1)
if res:
best = max(best,res)
if ind-1>0:
res = union(ind,ind-1)
if res:
best = max(best,res)
# print("HEAP",h)
for i in ans[::-1]:
print(i)
```
Yes
| 99,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Submitted Solution:
```
###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ######### #
###### ######### # # # # # # ######### #
# # # # # # # # # # #### # # #
# # # # # # # ## # # # # #
###### # # ####### ####### # # ##### # # # #
from __future__ import print_function # for PyPy2
from itertools import permutations as perm
# from fractions import Fraction
from collections import *
from sys import stdin
from bisect import *
from heapq import *
from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")
n, = gil()
a = [0] + gil()
for i in range(n+1):
a[i] += a[i-1]
idx = gil()
ans = []
h = [0] # max Heap
l, r = [0]*(n+2), [0]*(n+2)
while idx:
ans.append(-h[0])
# add element
i = idx.pop()
li, ri = i - l[i-1], i + r[i+1]
cnt = ri-li+1
r[li] = l[ri] = cnt
rangeSm = a[li-1] - a[ri]
heappush(h, rangeSm)
ans.reverse()
print(*ans, sep='\n')
```
Yes
| 99,936 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Submitted Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 9 16:14:34 2016
@author: kostiantyn.omelianchuk
"""
from sys import stdin, stdout
lines = stdin.readlines()
n = int(lines[0])
a = [int(x) for x in lines[1].split()]
b = [int(x) for x in lines[2].split()]
#check_array = [0 for i in range(n)]
check_dict = {}
snm = [i for i in range(n)]
r = [1 for i in range(n)]
sums = dict(zip(range(n), a))
def find_x(x):
if snm[x] != x:
snm[x] = find_x(snm[x])
return snm[x]
def union(x, y):
#x = find_x(x)
#y = find_x(y)
sums[x] += sums[y]
sums[y] = sums[x]
if x == y:
return
#sums[x] += sums[x_start]
if r[x] == r[y]:
r[x] += 1
if r[x] < r[y]:
snm[x] = y
else:
snm[y] = x
max_list = []
total_max = 0
for i in range(n):
cur_sum = 0
flag = 0
max_list.append(total_max)
pos = n-i-1
elem = b[pos] - 1
#check_array[elem] = 1
check_dict[elem] = 1
pos_x = find_x(elem)
if elem>0:
if check_dict.get(elem-1,0) == 1:
pos_y = find_x(elem-1)
union(pos_x,pos_y)
cur_sum = sums[pos_y]
#print(sums, check_array, total_max, cur_sum, elem, find_x(elem))
else:
flag += 1
else:
flag += 1
if elem<(n-1):
if check_dict.get(elem+1,0) == 1:
pos_y = find_x(elem+1)
union(pos_x,pos_y)
cur_sum = sums[pos_y]
#print(sums, check_array, total_max, cur_sum, elem, find_x(elem))
else:
flag += 1
else:
flag += 1
if flag == 2:
total_max = max(total_max,sums[pos_x])
else:
total_max = max(cur_sum, total_max)
max_list.append(total_max)
for j in range(1,n+1):
print(max_list[n-j])
```
No
| 99,937 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Submitted Solution:
```
n = int(input())
a = input()
nums = list(map(int, a.split()))
a = input()
breaks = list(map(int, a.split()))
for b in breaks:
m = 0
nums[b-1] = 0
seq = []
for each in nums:
now = 0
if each == 0:
for each in seq:
now = max(0, now+each)
m = max(m, now)
seq = []
else:
seq.append(each)
for each in seq:
now = max(0, now+each)
m = max(m, now)
seq = []
print(m)
```
No
| 99,938 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Submitted Solution:
```
size = int(input())
num = list(map(int, input().split(" ")))
rem = list(map(lambda x: int(x) - 1, input().split(" ")))
def subsum(lst):
ms = 0
cs = 0
for i in lst:
cs += i
if i == 0 and cs > ms:
ms = cs
cs = 0
return ms if ms > cs else cs
for i in rem:
num[i] = 0
print (subsum(num))
```
No
| 99,939 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array consisting of n non-negative integers a1, a2, ..., an.
You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.
After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the length of the array.
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
The third line contains a permutation of integers from 1 to n — the order used to destroy elements.
Output
Print n lines. The i-th line should contain a single integer — the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.
Examples
Input
4
1 3 2 5
3 4 1 2
Output
5
4
3
0
Input
5
1 2 3 4 5
4 2 3 5 1
Output
6
5
5
1
0
Input
8
5 5 4 4 6 6 5 5
5 2 8 7 1 3 4 6
Output
18
16
11
8
8
6
6
0
Note
Consider the first sample:
1. Third element is destroyed. Array is now 1 3 * 5. Segment with maximum sum 5 consists of one integer 5.
2. Fourth element is destroyed. Array is now 1 3 * * . Segment with maximum sum 4 consists of two integers 1 3.
3. First element is destroyed. Array is now * 3 * * . Segment with maximum sum 3 consists of one integer 3.
4. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0.
Submitted Solution:
```
#!/usr/bin/python3
size = int(input())
num = list(map(int, input().split()))
rem = list(map(int, input().split()))
chunks = [None] * size
res = [-1] * size
ans = [0]
ms = -1
def addChunk(n):
chunks[n] = [n, num[n]]
return n
def getRoot(n):
return n if chunks[n][0] == n else getRoot(chunks[n][0])
def mergeChunks(parent, child):
proot = getRoot(parent)
croot = getRoot(child)
chunks[croot][0] = proot
chunks[proot][1] += chunks[croot][1]
return proot
ii = size
while ii >= 0:
ii -= 1
i = rem[ii] - 1
res[i] = num[i]
root = addChunk(i)
if i > 0 and chunks[i - 1] != None:
root = mergeChunks(i - 1, i)
if i + 1 < size and chunks[i + 1] != None:
root = mergeChunks(i, i + 1)
ms = max(ms, chunks[root][1])
ans.append(ms)
for i in range(2, size):
print (ans[-i-1])
print(0)
```
No
| 99,940 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Tags: dfs and similar, graphs
Correct Solution:
```
# coding: utf-8
n, m, k = list(map(int, input().split()))
govs = list(map(int, input().split()))
graph = [[] for _ in range(n+1)]
for _ in range(m):
u, v = list(map(int, input().split()))
graph[u].append(v)
graph[v].append(u)
visited = [False] * (n+1)
components = []
has_gov = []
def dfs(node, i):
if visited[node]:
return
visited[node] = True
if node in govs:
has_gov[i] = True
components[i].append(node)
for neighbour in graph[node]:
dfs(neighbour, i)
i = -1
max_component_size = -1
biggest_component = 0
for node in range(1, n+1):
if visited[node]:
continue
i += 1
components.append([])
has_gov.append(False)
dfs(node, i)
if len(components[i]) > max_component_size and has_gov[i]:
max_component_size = len(components[i])
biggest_component = i
for i in range(len(components)):
if has_gov[i]:
continue
no_gov_component = components[i]
for j in range(len(no_gov_component)):
components[biggest_component].append(no_gov_component[j])
new_edges = 0
for i in range(len(components)):
if not has_gov[i]:
continue
component = components[i]
s = len(component)
edges = (s*(s-1)) // 2
removed_edges = 0
for j in component:
for k in component:
if j != k and k in graph[j]:
removed_edges += 1
removed_edges = removed_edges // 2
new_edges += (edges - removed_edges)
print(new_edges)
```
| 99,941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Tags: dfs and similar, graphs
Correct Solution:
```
#inputs
n, m, ngovs = [int(x) for x in input().split()]
govs=[int(i)-1 for i in input().split()]
#build graph
graph=[list([]) for i in range(n)]
visited=[False for i in range(n)]
for i in range(m):
verts = tuple(int(x) -1 for x in input().split())
graph[verts[0]].append(verts[1])
graph[verts[1]].append(verts[0])
#DFS
res = 0
cur_max = 0
def dfs(node):
if not visited[node]:
visited[node]=1
seen[0]+=1
for i in graph[node]:
if not visited[i]:
dfs(i)
for i in govs:
seen=[0]
dfs(i)
res+=seen[0]*(seen[0]-1)//2
cur_max=max(cur_max,seen[0])
res-=cur_max*(cur_max-1)//2
for i in range(n):
if not visited[i]:
seen=[0]
dfs(i)
cur_max+=seen[0]
res= res - m+cur_max*(cur_max-1)//2
print(res)
```
| 99,942 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Tags: dfs and similar, graphs
Correct Solution:
```
V, E, K = map(int, input().split())
C = set(map(int, input().split()))
C = set(map(lambda x: x - 1, C))
g = [[] for i in range(V)]
for i in range(E):
u, v = map(int, input().split())
u, v = u - 1, v - 1
g[u].append(v)
g[v].append(u)
components = list()
visited = set()
def dfs(u, c):
visited.add(u)
components[c].add(u)
for v in g[u]:
if not (v in visited):
dfs(v, c)
c = 0
for i in range(V):
if i in visited:
continue
components.append(set())
dfs(i, c)
c += 1
countries = set()
mc = 0
mcl = 0
for comp in range(c):
if len(components[comp] & C):
countries.add(comp)
if len(components[comp]) > mcl:
mcl = len(components[comp])
mc = comp
for comp in range(c):
if not (comp in countries):
for t in components[comp]:
components[mc].add(t)
# components[mc] = components[mc] | components[comp]
components[comp] = set()
t = 0
for comp in range(c):
l = len(components[comp])
t += l * (l - 1) // 2
print(t - E)
```
| 99,943 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Tags: dfs and similar, graphs
Correct Solution:
```
def solve():
order = list
length = len
unique = set
nodes, edges, distinct = order(map(int, input().split(" ")))
govt = {x-1: 1 for x in order(map(int, input().split(" ")))}
connections = {}
# Add edges
for _ in range(edges):
x, y = order(map(int, input().split(" ")))
if x-1 not in connections:
connections[x-1] = [y-1]
else:
connections[x-1].append(y-1)
if y-1 not in connections:
connections[y-1] = [x-1]
else:
connections[y-1].append(x-1)
discovered = {}
cycles = {m: [] for m in ["G", "N"]}
for i in range(nodes):
is_govt = False if i not in govt else True
# Node is already been lookd at
if i in discovered:
continue
cycle = [i]
# Nodes with no edges to other nodes
if i not in connections:
discovered[i] = 1
if is_govt:
cycles["G"].append(cycle)
else:
cycles["N"].append(cycle)
continue
path = connections[i]
# Find all the nodes reachable
while length(path) > 0:
node = path.pop(0)
if node in discovered:
continue
discovered[node] = 1
if node in govt:
is_govt = True
path = connections[node] + path
cycle.append(node)
if is_govt:
cycles["G"].append(order(unique(cycle)))
else:
cycles["N"].append(order(unique(cycle)))
ordered_cycles = sorted(cycles["G"], key=len)
highest = length(ordered_cycles[-1])
ordered_cycles.pop(length(ordered_cycles) - 1)
for cycle in cycles["N"]:
highest += length(cycle)
total = highest * (highest - 1) // 2
for j in ordered_cycles:
total += length(j) * (length(j) - 1) // 2
print(total - edges)
solve()
```
| 99,944 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Tags: dfs and similar, graphs
Correct Solution:
```
class graph:
def __init__(self,size):
self.G=dict()
for i in range(size):
self.G[i]=set()
self.sz=size
self.ne=0
def ae(self,u,v):
self.G[u].add(v)
self.G[v].add(u)
self.ne+=1
def se(self,u):
return self.G[u]
def nume(self):
return self.ne
def dfs(G,v):
num,mk=1,mark[v]
vv[v]=1
for u in G.se(v):
if not vv[u]:
n1,mk1=dfs(G,u)
num+=n1
mk|=mk1
return num,mk
n,m,k=(int(z) for z in input().split())
G=graph(n)
hh=[int(z)-1 for z in input().split()]
mark=[0]*n
vv=[0]*n
for i in hh:
mark[i]=1
for i in range(m):
u,v=(int(z)-1 for z in input().split())
G.ae(u,v)
sunmk=0
mkcc=[]
for u in range(n):
if not vv[u]:
n2,mk2=dfs(G,u)
if mk2:
mkcc.append(n2)
else:
sunmk+=n2
mkcc.sort()
ans=0
##print(mkcc,sunmk)
for i in mkcc[:len(mkcc)-1]:
ans+=i*(i-1)//2
ans+=(mkcc[-1]+sunmk)*(mkcc[-1]+sunmk-1)//2
ans-=m
print(ans)
```
| 99,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Tags: dfs and similar, graphs
Correct Solution:
```
class Union:
def __init__(self, n):
self.ancestors = [i for i in range(n+1)]
self.size = [0]*(n+1)
def get_root(self, node):
if self.ancestors[node] == node:
return node
self.ancestors[node] = self.get_root(self.ancestors[node])
return self.ancestors[node]
def merge(self, a, b):
a, b = self.get_root(a), self.get_root(b)
self.ancestors[a] = b
def combination(number):
return (number * (number - 1)) >> 1
n, m, k = map(int, input().split())
biggest, others, res = 0, n, -m
homes = list(map(int, input().split()))
union = Union(n)
for _ in range(m):
a, b = map(int, input().split())
union.merge(a, b)
for i in range(1, n+1):
union.size[union.get_root(i)] += 1
for home in homes:
size = union.size[union.get_root(home)]
biggest = max(biggest, size)
res += combination(size)
others -= size
res -= combination(biggest)
res += combination(biggest + others)
print(res)
```
| 99,946 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Tags: dfs and similar, graphs
Correct Solution:
```
entrada = input().split(" ")
n = int(entrada[0])
m = int(entrada[1])
k = int(entrada[2])
lista = []
nodes = list(map(int, input().split(" ")))
for i in range(n):
lista.append([])
for i in range(m):
valores = input().split(" ")
u = int(valores[0])
v = int(valores[1])
lista[u - 1].append(v - 1)
lista[v - 1].append(u - 1)
usado = [False] * n
parc1 = 0
parc2 = -1
def calc(valor):
global x, y
x += 1
y += len(lista[valor])
usado[valor] = True
for i in lista[valor]:
if not usado[i]:
calc(i)
for i in range(k):
x = 0
y = 0
calc(nodes[i] - 1)
parc1 += (x * (x - 1) - y) // 2
parc2 = max(parc2, x)
n -= x
aux3 = 0
lenght = len(lista)
for i in range(lenght):
if not usado[i]:
aux3 += len(lista[i])
parc1 += ((parc2 + n) * (n + parc2 - 1) - parc2 * (parc2 - 1)) // 2
maximumNumber = parc1 - (aux3 // 2)
print(maximumNumber)
```
| 99,947 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
class YobaDSU():
def __init__(self, keys, weights):
self.A = [[i,0,w] for i, w in zip(keys, weights)]
self.size = len(self.A)
def get(self, i):
p = i
while self.A[p][0] != p: p = self.A[p][0]
j = self.A[i][0]
while j != p:
self.A[i][0] = p
i, j = j, self.A[j][0]
return (p, self.A[p][2])
def __getitem__(self, i):
return self.get(i)[0]
def union(self, i, j):
u, v = self[i], self[j]
if u == v: return
self.size -= 1
if self.A[u][1] > self.A[v][1]:
self.A[v][0] = u
self.A[u][2] += self.A[v][2]
else:
self.A[u][0] = v
self.A[v][2] += self.A[u][2]
if self.A[u][1] == self.A[v][1]:
self.A[v][1] += 1
def __len__(self): return self.size
class WeightedDSU(YobaDSU):
def __init__(self, weights):
self.A = [[i,0,w] for i, w in enumerate(weights)]
self.size = len(self.A)
class DSU(YobaDSU):
def __init__(self, n):
self.A = [[i,0,1] for i in range(n)]
self.size = n
def solve():
n, m, k = map(int, input().split())
C = [int(x)-1 for x in input().split()]
D = DSU(n)
for line in sys.stdin:
u, v = map(int, line.split())
D.union(u-1, v-1)
S = [D.get(c)[1] for c in C]
free = n - sum(S)
argmax = max(enumerate(S), key = lambda x: x[1])
S[argmax[0]] += free
return sum(s*(s-1)//2 for s in S) - m
print(solve())
```
| 99,948 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def solve():
nodes, edges, distinct = list(map(int, input().split(" ")))
govt = {x-1: 1 for x in list(map(int, input().split(" ")))}
connections = {}
# Add edges
for _ in range(edges):
x, y = list(map(int, input().split(" ")))
if x-1 not in connections:
connections[x-1] = [y-1]
else:
connections[x-1].append(y-1)
if y-1 not in connections:
connections[y-1] = [x-1]
else:
connections[y-1].append(x-1)
discovered = {}
cycles = {m: [] for m in ["G", "N"]}
for i in range(nodes):
is_govt = False if i not in govt else True
# Node is already been lookd at
if i in discovered:
continue
cycle = [i]
# Nodes with no edges to other nodes
if i not in connections:
discovered[i] = 1
if is_govt:
cycles["G"].append(cycle)
else:
cycles["N"].append(cycle)
continue
path = connections[i]
# Find all the nodes reachable
while len(path) > 0:
node = path.pop(0)
if node in discovered:
continue
discovered[node] = 1
if node in govt:
is_govt = True
path = connections[node] + path
cycle.append(node)
if is_govt:
cycles["G"].append(list(set(cycle)))
else:
cycles["N"].append(list(set(cycle)))
ordered_cycles = sorted(cycles["G"], key=len)
highest = len(ordered_cycles[-1])
ordered_cycles.pop(len(ordered_cycles) - 1)
for cycle in cycles["N"]:
highest += len(cycle)
total = highest * (highest - 1) // 2
for j in ordered_cycles:
if len(j) == 1:
continue
total += len(j) * (len(j) - 1) // 2
print(total - edges)
solve()
```
Yes
| 99,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
entrada = input().split(" ")
n = int(entrada[0])
m = int(entrada[1])
k = int(entrada[2])
lista = []
nodes = list(map(int, input().split(" ")))
for i in range(n):
lista.append([])
for i in range(m):
valores = input().split(" ")
u = int(valores[0])
v = int(valores[1])
lista[u - 1].append(v - 1)
lista[v - 1].append(u - 1)
usado = [False] * n
aux1 = 0
aux2 = -1
def calc(valor):
global x, y
x += 1
usado[valor] = True
y += len(lista[valor])
for i in lista[valor]:
if not usado[i]:
calc(i)
for i in range(k):
# global x, y
x = 0
y = 0
calc(nodes[i] - 1)
aux1 += (x * (x - 1) - y) // 2
aux2 = max(aux2, x)
n -= x
aux3 = 0
lenght = len(lista)
for i in range(lenght):
if not usado[i]:
aux3 += len(lista[i])
aux1 += ((aux2 + n) * (n + aux2 - 1) - aux2 * (aux2 - 1)) // 2
maximumNumber = aux1 - aux3 // 2
print(maximumNumber)
```
Yes
| 99,950 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def dfs(u,vis):
vis.add(u)
for v in g[u]:
if v not in vis:
dfs(v,vis)
n,m,k = map(int,list(input().split()))
govs_ind = map(int,list(input().split()))
orig = set()
countries = set(range(1,n+1))
g = [ [] for i in range(n+1) ]
for i in range(m):
u,v = map(int,list(input().split()))
if(u>v):
u,v = v,u
orig.add((u,v))
g[u].append(v)
g[v].append(u)
gov_nods = []
for u in govs_ind:
vis = set()
dfs(u,vis)
gov_nods.append(vis)
no_govs = countries.copy()
nvoss = 0
for reg in gov_nods:
no_govs -= reg
size = len(reg)
nvoss += (size*(size-1))//2
size = len(no_govs)
nvoss += (size*(size-1))//2
maxi = 0
for i in range(len(gov_nods)):
if len(gov_nods[i]) > len(gov_nods[maxi]) :
maxi = i
max_gov = gov_nods[maxi]
nvoss += len(max_gov)*len(no_govs)
nvoss -= len(orig)
print(nvoss)
# nvos = set()
# for reg in gov_nods:
# for u in reg:
# for v in reg:
# if u!=v:
# if u<v:
# nvos.add((u,v))
# else:
# nvos.add((v,u))
# for u in no_govs:
# for v in no_govs:
# if u!=v:
# if u<v:
# nvos.add((u,v))
# else:
# nvos.add((v,u))
# maxi = 0
# for i in range(len(gov_nods)):
# if len(gov_nods[i]) > len(gov_nods[maxi]) :
# maxi = i
# max_gov = gov_nods[maxi]
# for u in max_gov :
# for v in no_govs:
# if u!=v:
# if u<v:
# nvos.add((u,v))
# else:
# nvos.add((v,u))
# res = nvos-orig
# print(len(res))
# for reg in gov_nods:
# print("size: ", len(reg))
# C:\Users\Usuario\HOME2\Programacion\ACM
```
Yes
| 99,951 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
import sys
from copy import deepcopy
input = sys.stdin.readline
v, e, g = map(int, input().split())
connect = [set() for i in range(v)]
gov = list(map(int, input().split()))
for i in range(e):
x,y = map(int, input().split())
connect[x-1].add(y)
connect[y-1].add(x)
sizes = []#
for i in gov:
reached = {i}
while True:
old = deepcopy(reached)
for j in range(v):
if j+1 in reached:
reached.update(connect[j])
elif not connect[j].isdisjoint(reached):
reached.add(j+1)
if old == reached:
break
sizes.append(len(reached))
ans = -e
for i in sizes:
ans += i*(i-1)//2
big = max(sizes)
for i in range(v-sum(sizes)):
ans += big
big += 1
print(ans)
```
Yes
| 99,952 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def dfs(x,v,g,ks,kk):
rtv = 0
if v.__contains__(x) == False:
v.add(x)
if ks.__contains__(x):
kk.add(x)
rtv = 1
for i in range(1,n+1):
if g[x][i] == 1 and v.__contains__(i) == False :
rtv += dfs(i,v,g,ks,kk)
return rtv
n,m,k = map(int,input().strip().split(' '))
ks = set(map(int,input().strip().split(' ')))
g = [ [0]*(n+1) for i in range(n+1)]
for i in range(m):
x,y = map(int,input().strip().split(' '))
g[x][y] = 1
subts = [0]*(n+1)
subtk = [0]*(n+1)
v = set({})
for i in range(1,n+1):
kk = set({})
subts[i] = dfs(i,v,g,ks,kk)
if len(kk) > 0:
subtk[i] = 1
ans = 0
mk = 0
mi = 0
for i in range(1,n+1):
if subtk[i] == 1:
if mk < subts[i]:
mk = subts[i]
mi = i
for i in range(1,n+1):
if subtk[i] == 0:
subts[mi] += subts[i]
subts[i] = 0
for i in range(1,n+1):
if subts[i] != 0:
ans += int((subts[i]*(subts[i] - 1))/2)
#print(subts,subtk)
print(ans - m)
```
No
| 99,953 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def dfs(x,v,g,ks,kk):
rtv = 0
if v.__contains__(x) == False:
v.add(x)
if ks.__contains__(x):
kk.add(x)
rtv = 1
for i in range(1,n+1):
if g[x][i] == 1 and v.__contains__(i) == False :
rtv += dfs(i,v,g,ks,kk)
return rtv
n,m,k = map(int,input().strip().split(' '))
ks = set(map(int,input().strip().split(' ')))
g = [ [0]*(n+1) for i in range(n+1)]
for i in range(m):
x,y = map(int,input().strip().split(' '))
g[x][y] = 1
subts = [0]*(n+1)
subtk = [0]*(n+1)
v = set({})
for i in range(1,n+1):
kk = set({})
subts[i] = dfs(i,v,g,ks,kk)
if len(kk) > 0:
subtk[i] = 1
ans = 0
mk = 0
cnk = 0
for i in range(1,n+1):
ans += int((subts[i]*(subts[i] - 1))/2)
if subtk[i] == 1:
mk = max(mk,subts[i])
for i in range(1,n+1):
if subtk[i] == 0:
ans += mk*subts[i]
#print(subts,subtk)
print(ans - m)
```
No
| 99,954 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
n, m, k = map(int, input().split())
governments = list(map(int, input().split()))
vis = [False]*(n+1)
g = [ set() for i in range(n+1) ]
lista = []
def dfs(v, lista):
vis[v] = True
lista[0].add(v)
lista[1] += len(g[v])
if (v in governments):
lista[2] = v
for u in g[v]:
if (not vis[u]):
dfs(u, lista)
return lista
for i in range(m):
a, b = map(int, input().split())
g[a].add(b)
g[b].add(a)
for v in range(1, len(g)):
if (not vis[v]):
lista.append(dfs(v, [set(), 0, None]))
biggest_group = [-1, None]
for group, n_edges, government in lista:
if (government):
tmp_group = [len(group), government]
if(tmp_group[0] > biggest_group[0]):
biggest_group = tmp_group
nodes = 0
edges = 0
off = 0
for group, n_edges, government in lista:
n_edges = n_edges/2
if (not government or government == biggest_group[1]):
nodes += len(group)
edges += n_edges
else:
off += (len(group)*(len(group) -1 )/2)-n_edges
print(int((nodes*(nodes-1)/2)-edges) + int(off))
```
No
| 99,955 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def dfs(node):
tot = 0
edge = 0
stack = [node]
while stack:
ele = stack.pop(-1)
seen[ele] = 1
tot += 1
for each in adj[ele]:
if seen[each] == 0:
stack.append(each)
return tot
n,m,k = map(int,input().split())
arr = list(map(int,input().split()))
seen = [0] * (n+1)
adj = [list() for i in range(n+1)]
for _ in range(m):
a,b = map(int,input().split())
adj[a].append(b)
adj[b].append(a)
mx = 0
totEdge = n
ans = 0
for each in arr:
s = dfs(each)
mx = max(s,mx)
ans += s*(s-1)//2
totEdge -= s
ans += (totEdge+mx) * (totEdge+mx-1) // 2
ans -= mx*(mx-1) // 2 + m
print(ans)
```
No
| 99,956 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.
There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp.
<image>
Help Dima to find a suitable way to cut the garland, or determine that this is impossible.
While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.
Input
The first line contains single integer n (3 ≤ n ≤ 106) — the number of lamps in the garland.
Then n lines follow. The i-th of them contain the information about the i-th lamp: the number lamp ai, it is hanging on (and 0, if is there is no such lamp), and its temperature ti ( - 100 ≤ ti ≤ 100). The lamps are numbered from 1 to n.
Output
If there is no solution, print -1.
Otherwise print two integers — the indexes of the lamps which mean Dima should cut the wires they are hanging on. If there are multiple answers, print any of them.
Examples
Input
6
2 4
0 5
4 2
2 1
1 1
4 2
Output
1 4
Input
6
2 4
0 6
4 2
2 1
1 1
4 2
Output
-1
Note
The garland and cuts scheme for the first example:
<image>
Submitted Solution:
```
""" This is a solution to the problem Garland on codeforces.com
Given a rooted tree with node weights (possibly negative),
determine the two edges to be cut such that the sum of the weights in the remaining three subtrees is equal.
For details, see
http://codeforces.com/problemset/problem/767/C
"""
from sys import stdin
import sys
sys.setrecursionlimit(20000)
# compute subtree sums for all nodes, let S = total weight
# find two subtrees A, B with weight 1/3 S (check for divisibility first)
# distinguish two cases:
# - A is subtree of B: then A has total weight 2/3 S, B has weight 1/3 S
# - A and B are not descendants of one another
class RootedTree:
def __init__(self, n):
self._adj = {}
for i in range(n + 1):
self._adj[i] = []
def __repr__(self):
return str(self._adj)
@property
def root(self):
if len(self._adj[0]) == 0:
raise ValueError("Root not set.")
return self._adj[0][0]
def add_node(self, parent, node):
self._adj[parent].append(node)
def get_children(self, parent):
return self._adj[parent]
#lines = open("input.txt", 'r').readlines()
lines = stdin.readlines()
n = int(lines[0])
def print_found_nodes(found_nodes):
print(" ".join(map(str, found_nodes)))
tree = RootedTree(n)
weights = [0] * (n + 1)
for node, line in enumerate(lines[1:]):
parent, weight = list(map(int, line.split()))
tree.add_node(parent, node + 1)
weights[node + 1] = weight
sum_weights = [0] * (n + 1)
def compute_subtree_sum(node):
global tree
global sum_weights
weight_sum = weights[node]
for child in tree.get_children(node):
compute_subtree_sum(child)
weight_sum = weight_sum + sum_weights[child]
sum_weights[node] = weight_sum
compute_subtree_sum(tree.root)
def divisible_by_three(value):
return abs(value) % 3 == 0
total_sum = sum_weights[tree.root]
if n == 12873:
print(str(sum_weights[3656]) + " " + str(sum_weights[1798]))
elif not divisible_by_three(total_sum):
print("-1")
else:
part_sum = total_sum / 3
found_nodes = []
def find_thirds(node):
global sum_weights
global tree
global total_sum
global found_nodes
if len(found_nodes) == 2:
return
for child in tree.get_children(node):
if sum_weights[child] == total_sum / 3:
found_nodes.append(child)
if len(found_nodes) == 2:
return
else:
find_thirds(child)
found_nodes = [tree.root]
while len(found_nodes) == 1:
node = found_nodes[0]
found_nodes = []
find_thirds(node)
if len(found_nodes) == 2:
#if n == 12873:
# print("a " + str(sum_weights[tree.root]) + " " + str(sum_weights[found_nodes[0]]) + " " + str(sum_weights[found_nodes[1]]))
print_found_nodes(found_nodes)
else:
def find_one_third(node):
global sum_weights
global tree
global total_sum
global found_nodes
if len(found_nodes) >= 2:
return
for child in tree.get_children(node):
if sum_weights[child] == total_sum / 3:
found_nodes.append(child)
return
find_one_third(child)
def find_two_thirds(node):
global sum_weights
global tree
global total_sum
global found_nodes
if len(found_nodes) == 2:
return
for child in tree.get_children(node):
if sum_weights[child] == (total_sum * 2) / 3:
found_nodes.append(child)
find_one_third(child)
if len(found_nodes) == 2:
return
else:
found_nodes = []
find_two_thirds(child)
found_nodes = [tree.root]
while len(found_nodes) == 1:
node = found_nodes[0]
found_nodes = []
find_two_thirds(node)
if len(found_nodes) == 2:
#if n == 12873:
# print("b " + str(sum_weights[tree.root]) + " " + str(sum_weights[found_nodes[0]]) + " " + str(sum_weights[found_nodes[1]]))
print_found_nodes(found_nodes)
else:
print("-1")
```
No
| 99,957 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.
There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp.
<image>
Help Dima to find a suitable way to cut the garland, or determine that this is impossible.
While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.
Input
The first line contains single integer n (3 ≤ n ≤ 106) — the number of lamps in the garland.
Then n lines follow. The i-th of them contain the information about the i-th lamp: the number lamp ai, it is hanging on (and 0, if is there is no such lamp), and its temperature ti ( - 100 ≤ ti ≤ 100). The lamps are numbered from 1 to n.
Output
If there is no solution, print -1.
Otherwise print two integers — the indexes of the lamps which mean Dima should cut the wires they are hanging on. If there are multiple answers, print any of them.
Examples
Input
6
2 4
0 5
4 2
2 1
1 1
4 2
Output
1 4
Input
6
2 4
0 6
4 2
2 1
1 1
4 2
Output
-1
Note
The garland and cuts scheme for the first example:
<image>
Submitted Solution:
```
def ri():
return map(int, input().split())
class Node:
def __init__(self):
self.adj = set()
self.t = 0
self.v = 0
def dfs(node, s):
global cut
if cut != -1:
return
node[s].v = 1
for a in node[s].adj:
if node[a].v == 0:
node[a].v = 1
dfs(node, a)
if cut != -1:
return
node[s].t += node[a].t
if node[s].t == val:
cut = s
n = int(input())
node = []
par = []
for i in range(0, n+1):
node.append(Node())
val = 0
par = [0]*(n+1)
for i in range(1, n+1):
p, t = ri()
if p == 0:
root = i
node[i].t = t
val += t
if p != 0:
par[i] = p
node[i].adj.add(p)
node[p].adj.add(i)
cut = -1
if val%3:
print(-1)
exit()
else:
val = val//3
dfs(node, root)
ans = []
ans.append(cut)
for i in range(1, n+1):
node[i].s = 0
node[i].v = 0
node[par[cut]].adj.remove(cut)
cut = -1
dfs(node, root)
ans.append(cut)
print(' '.join(map(str, ans)))
```
No
| 99,958 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.
There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp.
<image>
Help Dima to find a suitable way to cut the garland, or determine that this is impossible.
While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.
Input
The first line contains single integer n (3 ≤ n ≤ 106) — the number of lamps in the garland.
Then n lines follow. The i-th of them contain the information about the i-th lamp: the number lamp ai, it is hanging on (and 0, if is there is no such lamp), and its temperature ti ( - 100 ≤ ti ≤ 100). The lamps are numbered from 1 to n.
Output
If there is no solution, print -1.
Otherwise print two integers — the indexes of the lamps which mean Dima should cut the wires they are hanging on. If there are multiple answers, print any of them.
Examples
Input
6
2 4
0 5
4 2
2 1
1 1
4 2
Output
1 4
Input
6
2 4
0 6
4 2
2 1
1 1
4 2
Output
-1
Note
The garland and cuts scheme for the first example:
<image>
Submitted Solution:
```
import sys
n = int(input())
temp = [-1] * n
parent = [-1] * n
treeTemp = [-1] * n
childStart = [-1] * n
childNext = [-1] * n
sumTemp = 0
for i in range(n):
parent[i], temp[i] = (int(x) for x in input().split())
treeTemp[i] = temp[i]
parent[i] -= 1
sumTemp += temp[i]
if (parent[i] >= 0):
if (childStart[parent[i]] < 0):
childStart[parent[i]] = i
else:
childNext[i] = childStart[parent[i]]
childStart[parent[i]] = i
if(parent[i] == -1):
root = i
if (sumTemp % 3 != 0):
print(-1)
sys.exit()
else:
iterator = root
while (iterator != -1):
if (childStart[iterator] == -1):
if (iterator != root):
treeTemp[parent[iterator]] += treeTemp[iterator]
iterator = parent[iterator]
else:
iterator = childStart[iterator]
childStart[parent[iterator]] = childNext[childStart[parent[iterator]]]
treesCount = 0
treeInd = 0
sumTemp /= 3
for i in range(n):
if (treeTemp[i] == sumTemp):
if (treesCount == 0):
treesCount = 1
treeInd = i
else:
j = i
while (parent[j] != treeInd and parent[j] != -1):
j = parent[j]
if (j == root):
print(treeInd + 1, i + 1)
sys.exit()
print(-1)
```
No
| 99,959 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.
There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp.
<image>
Help Dima to find a suitable way to cut the garland, or determine that this is impossible.
While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.
Input
The first line contains single integer n (3 ≤ n ≤ 106) — the number of lamps in the garland.
Then n lines follow. The i-th of them contain the information about the i-th lamp: the number lamp ai, it is hanging on (and 0, if is there is no such lamp), and its temperature ti ( - 100 ≤ ti ≤ 100). The lamps are numbered from 1 to n.
Output
If there is no solution, print -1.
Otherwise print two integers — the indexes of the lamps which mean Dima should cut the wires they are hanging on. If there are multiple answers, print any of them.
Examples
Input
6
2 4
0 5
4 2
2 1
1 1
4 2
Output
1 4
Input
6
2 4
0 6
4 2
2 1
1 1
4 2
Output
-1
Note
The garland and cuts scheme for the first example:
<image>
Submitted Solution:
```
def tot_brightness(cur):
if visited[cur]:
return 0
visited[cur] = 1
if cur+1 in parent:
nex = parent.index(cur+1)
return brightness[nex] + tot_brightness(nex)
else:
return 0
def getRightChild(cur, tsum):
if tsum == req_sum:
return lchild(cur)
elif tsum > req_sum:
return -1
else:
if cur+1 in parent:
nex = parent.index(cur+1)
return getRightChild(nex, tsum+brightness[nex])
def lchild(cur):
if cur+1 in parent:
return parent.index(cur+1)
else:
return -1
def child(cur):
pos = 0
while cur+1 in parent[pos:]:
k = parent[pos:].index(cur+1)
if visited[pos+k] == 0:
return pos+k
pos += k+1
return -1
def getLeftChild(cur, tsum):
if (right_sum - tsum) == req_sum:
return child(cur), tsum
elif (right_sum - tsum) < req_sum:
return -1, 0
else:
visited[cur] = 1
nex = 0
while cur+1 in parent[nex:]:
k = parent[nex:].index(cur+1)
print('>>>>', nex, k)
if visited[nex+k] == 0:
return getLeftChild(nex+k, tsum+brightness[nex+k])
nex += k+1
n = int(input())
parent = []
brightness = []
for i in range(n):
a, b = input().split()
parent.append(int(a))
brightness.append(int(b))
visited = [0]*len(parent)
start = parent.index(0)
left_sum = tot_brightness(start)
right_sum = 0
for i in range(len(visited)):
if visited[i] == 0:
right_sum += brightness[i]
tot_sum = left_sum + right_sum + brightness[start]
if tot_sum%3 == 0:
req_sum = tot_sum / 3
mid_sum = 0
visited[start] = 0
left, midsum = getLeftChild(start, mid_sum)
if left != -1:
right = getRightChild(start, mid_sum+brightness[start])
if right != 1:
print(right+1, left+1)
else:
print(-1)
else:
print(-1)
else:
print(-1)
```
No
| 99,960 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
def sum_num(num):
num = num-1
sum = 0
while num>0:
sum+=num
num = num-1
return sum
class UnionFindSet(object):
def __init__(self, data_list):
self.father_dict = {}
self.size_dict = {}
self.m_num = {}
for node in data_list:
self.father_dict[node] = node
self.size_dict[node] = 1
self.m_num[node] = 0
def find_head(self, node):
father = self.father_dict[node]
if(node != father):
father = self.find_head(father)
self.father_dict[node] = father
return father
def is_same_set(self, node_a, node_b):
return self.find_head(node_a) == self.find_head(node_b)
def union(self, node_a, node_b):
if node_a is None or node_b is None:
return
a_head = self.find_head(node_a)
b_head = self.find_head(node_b)
if(a_head != b_head):
a_set_size = self.size_dict[a_head]
b_set_size = self.size_dict[b_head]
a_m = self.m_num[a_head]
b_m = self.m_num[b_head]
if(a_set_size >= b_set_size):
self.father_dict[b_head] = a_head
self.size_dict[a_head] = a_set_size + b_set_size
self.m_num[a_head] = a_m+b_m+1
self.m_num.pop(b_head)
self.size_dict.pop(b_head)
else:
self.father_dict[a_head] = b_head
self.size_dict[b_head] = a_set_size + b_set_size
self.m_num[b_head] =a_m+b_m+1
self.m_num.pop(a_head)
self.size_dict.pop(a_head)
else:
self.m_num[a_head]+=1
first_line = input()
first_line = first_line.split(" ")
first_line = [int(i) for i in first_line]
m_1 = first_line[1]
list_1 = []
list_item = []
for i in range(m_1):
line = input()
line = line.split(" ")
line = [int(i) for i in line]
list_1 += line
list_item.append(line)
flag = False
d_set = set(list_1)
union_find_set = UnionFindSet(list(d_set))
for item in list_item:
union_find_set.union(item[0], item[1])
m_d=union_find_set.m_num
s_d=union_find_set.size_dict
for key in m_d:
sum = sum_num(s_d[key])
if m_d[key] != sum:
flag=True
break
if flag:
print("NO")
else:
print("YES")
```
| 99,961 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from collections import deque
def bfs(start):
res = []
queue = deque([start])
while queue:
vertex = queue.pop()
if not vis[vertex]:
vis[vertex] = 1
res.append(vertex)
for i in s[vertex]:
if not vis[i]:
queue.append(i)
return res
n, m = [int(i) for i in input().split()]
s = [[] for i in range(n)]
for i in range(m):
a, b = [int(i) for i in input().split()]
s[a-1].append(b-1)
s[b-1].append(a-1)
vis = [0 for i in range(n)]
r = 0
for i in range(n):
if not vis[i]:
d = bfs(i)
for j in d:
if len(s[j]) != len(d)-1:
r = 1
print("NO")
break
if r:
break
else:
print("YES")
```
| 99,962 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys,threading
sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
def main():
global al,va,ca,ml,ec,v,z
n,m=map(int,input().split())
ml=[-1]*(n+1)
al=[[]for i in range(n+1)]
for i in range(m):
a,b=map(int,input().split())
al[a].append(b)
al[b].append(a)
ml[a]=1
ml[b]=1
va=[0]*(n+1)
ca=[-1]*(n+1)
#print(ans,al)
z=True
for e in range(1,n+1):
if(va[e]==0):
ec=0
v=0
ec,v=dfs(e)
ec=ec//2
#print(v,ec)
if(ec==(v*(v-1))//2):
pass
else:
z=False
break
#print(ca,z)
if(z==False):
print("NO")
else:
print("YES")
def dfs(n):
global al,va,ca,ec,v
va[n]=1
v=v+1
ec=ec+len(al[n])
for e in al[n]:
if(va[e]==0):
dfs(e)
return ec,v
t=threading.Thread(target=main)
t.start()
t.join()
```
| 99,963 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys
n,m = map(int,input().split())
store = [set([i]) for i in range(n+1)]
for i in range(m):
a,b = map(int,input().split())
store[a].update([a,b])
store[b].update([a,b])
# print(store)
no = 0
"""cnt is a array of track which item are checked or not"""
cnt = [0]*(n+1)
for i in range(1,n+1):
if cnt[i] == 1:
# already checked this item
continue
for j in store[i]:
# j = single item of set
# print(j)
cnt[j] = 1
if store[j] != store[i]:
# print('store[i]: store[j]:',store[i],store[j])
no = 1
if no == 0:
print('YES')
else:
print('NO')
```
| 99,964 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from collections import defaultdict
from sys import stdin
from math import factorial
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 [str(x) for x in stdin.readline().split()]
def nCr(n, r):
f, m = factorial, 1
for i in range(n, n - r, -1):
m *= i
return int(m // f(r))
class disjointset:
def __init__(self, n):
self.rank, self.parent, self.n, self.nsets, self.edges = defaultdict(int), defaultdict(int), n, defaultdict(
int), defaultdict(int)
for i in range(1, n + 1):
self.parent[i], self.nsets[i] = i, 1
def find(self, x):
if self.parent[x] == x:
return x
result = self.find(self.parent[x])
self.parent[x] = result
return result
def union(self, x, y):
xpar, ypar = self.find(x), self.find(y)
# already union
if xpar == ypar:
self.edges[xpar] += 1
return
# perform union by rank
if self.rank[xpar] < self.rank[ypar]:
self.parent[xpar] = ypar
self.edges[ypar] += self.edges[xpar] + 1
self.nsets[ypar] += self.nsets[xpar]
elif self.rank[xpar] > self.rank[ypar]:
self.parent[ypar] = xpar
self.edges[xpar] += self.edges[ypar] + 1
self.nsets[xpar] += self.nsets[ypar]
else:
self.parent[ypar] = xpar
self.rank[xpar] += 1
self.edges[xpar] += self.edges[ypar] + 1
self.nsets[xpar] += self.nsets[ypar]
def components(self):
for i in self.parent:
if self.parent[i] == i:
if self.edges[i] != nCr(self.nsets[i], 2):
exit(print('NO'))
class graph:
# initialize graph
def __init__(self, gdict=None):
if gdict is None:
gdict = defaultdict(list)
self.gdict = gdict
# add edge
def add_edge(self, node1, node2):
self.gdict[node1].append(node2)
self.gdict[node2].append(node1)
def dfsUtil(self, v):
stack = [v]
while (stack):
s = stack.pop()
if not self.visit[s]:
self.visit[s] = 1
self.vertix += 1
for i in self.gdict[s]:
if not self.visit[i]:
stack.append(i)
self.edge[min(i, s), max(i, s)] = 1
# dfs for graph
def dfs(self, ver):
self.edge, self.vertix, self.visit = defaultdict(int), 0, defaultdict(int)
for i in ver:
if self.visit[i] == 0:
self.dfsUtil(i)
if len(self.edge) != nCr(self.vertix, 2):
exit(print('NO'))
self.edge, self.vertix = defaultdict(int), 0
n, m = arr_inp(1)
bear, cnt = graph(), disjointset(n)
for i in range(m):
x, y = arr_inp(1)
# bear.add_edge(x, y)
cnt.union(x, y)
cnt.components()
print('YES')
```
| 99,965 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys
import collections
def bfs(u, adjList, vis):
dq = collections.deque()
dq.append(u)
vis[u] = True
edgeCnt = 0
vertexCnt = 0
while dq:
u = dq.popleft()
vertexCnt += 1
edgeCnt += len(adjList[u])
for v in adjList[u]:
if not vis[v]:
vis[v] = True
dq.append(v)
edgeCnt = edgeCnt // 2
return bool(edgeCnt == ((vertexCnt * vertexCnt - vertexCnt) // 2))
def main():
# sys.stdin = open("in.txt", "r")
it = iter(map(int, sys.stdin.read().split()))
n = next(it)
m = next(it)
adjList = [[] for _ in range(n+3)]
for _ in range(m):
u = next(it)
v = next(it)
adjList[u].append(v)
adjList[v].append(u)
vis = [False] * (n+3)
for u in range(1, n+1):
if not vis[u]:
if not bfs(u, adjList, vis):
sys.stdout.write("NO\n")
return
sys.stdout.write("YES\n")
if __name__ == '__main__':
main()
```
| 99,966 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
inp = lambda : map(int, input().split())
n, m = inp()
lines = [set([i]) for i in range(n + 1)]
for i in range(m):
x, y = inp()
lines[x].add(y)
lines[y].add(x)
f = [True] * (n + 1)
for i in range(n):
if f[i]:
f[i] = False
for j in lines[i]:
f[j] = False
if lines[i] != lines[j]:
print("NO")
quit()
print("YES")
```
| 99,967 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys,os,io
import math,bisect,operator
inf,mod = float('inf'),10**9+7
# sys.setrecursionlimit(10 ** 6)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
Neo = lambda : list(map(int,input().split()))
G = defaultdict(list)
def addEdge(a,b):
G[a].append(b)
G[b].append(a)
N,M = Neo()
vis = [False]*(N+1)
def dfs(node):
s = deque()
vis[node] = True
s.append(node)
C = []
while s:
x= s.pop()
C.append(x)
for i in G.get(x,[]):
if not(vis[i]):
vis[i] = True
s.append(i)
return C
edge = set()
for i in range(M):
u,v = Neo()
edge.add((u,v))
edge.add((v,u))
addEdge(u,v)
for i in range(1,N+1):
if not vis[i]:
C = dfs(i)
n= len(C)
for i in range(n):
for j in range(i+1,n):
if not((C[i],C[j]) in edge):
print('NO')
exit(0)
print('YES')
```
| 99,968 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
from sys import *
f = lambda: map(int, stdin.readline().split())
n, m = f()
g = [[i] for i in range(n + 1)]
for j in range(m):
u, v = f()
g[u].append(v)
g[v].append(u)
k = 'YES'
for t in g: t.sort()
for t in g:
s = len(t)
if s > 1 and not all(g[x] == t for x in t):
k = 'NO'
break
for j in t: g[j] = []
print(k)
```
Yes
| 99,969 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
from collections import defaultdict
n,m=map(int,input().split())
d=defaultdict(list)
for i in range(m):
a,b=map(int,input().split())
a-=1
b-=1
d[a].append(b)
d[b].append(a)
vis=[0]*n
for i in range(n):
if vis[i]==0:
q=[i]
ce=0
cv=0
vis[i]=1
while q:
t=q.pop()
cv+=1
ce+=len(d[t])
for i in d[t]:
if not vis[i]:
vis[i]=1
q.append(i)
if ce!=cv*(cv-1):
print('NO')
exit()
print('YES')
```
Yes
| 99,970 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
#from collections import OrderedDict
from collections import defaultdict
#from functools import reduce
#from itertools import groupby
#sys.setrecursionlimit(10**6)
#from itertools import accumulate
from collections import Counter
import math
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
'''
from threading import stack_size,Thread
sys.setrecursionlimit(10**6)
stack_size(10**8)
'''
def listt():
return [int(i) for i in input().split()]
def gcd(a,b):
return math.gcd(a,b)
def lcm(a,b):
return (a*b) // gcd(a,b)
def factors(n):
step = 2 if n%2 else 1
return set(reduce(list.__add__,([i, n//i] for i in range(1, int(math.sqrt(n))+1, step) if n % i == 0)))
def comb(n,k):
factn=math.factorial(n)
factk=math.factorial(k)
fact=math.factorial(n-k)
ans=factn//(factk*fact)
return ans
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n > 2 and n % 2 == 0:
return False
max_div = math.floor(math.sqrt(n))
for i in range(3, 1 + max_div, 2):
if n % i == 0:
return False
return True
def maxpower(n,x):
B_max = int(math.log(n, x)) #tells upto what power of x n is less than it like 1024->5^4
return B_max
def binaryToDecimal(n):
return int(n,2)
#d=sorted(d.items(),key=lambda a:a[1]) sort dic accc to values
#g=pow(2,6)
#a,b,n,m=map(int,input().split())
#print ("{0:.8f}".format(min(l)))
n,m=map(int,input().split())
v=[0]*150005
s=[set([i])for i in range(150005)]
for _ in range(m):
a,b=map(int,input().split())
s[a].add(b)
s[b].add(a)
for i in range(n):
if not v[i]:
for j in s[i]:
v[j]=1
if s[j]!=s[i]:
print('NO')
exit(0)
print('YES')
```
Yes
| 99,971 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
n , m = map(int , input().split())
marked = [0] * n
adjlist = [set([i]) for i in range(n)]
for i in range(m):
v1 , v2 = map(int , input().split())
v1 -= 1
v2 -= 1
adjlist[v1].add(v2)
adjlist[v2].add(v1)
for i in range(n):
if not marked[i]:
for j in adjlist[i]:
marked[j] = 1
if adjlist[i] != adjlist[j] :
print('NO')
exit(0)
print('YES')
```
Yes
| 99,972 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
used = []
color = 1
count_v = 0
def dfs(u, g):
count = 0
used[u] = color
global count_v
count_v += 1
for v in g[u]:
count += 1
if not used[v]:
count += dfs(v, g)
return count
def main():
n, m = map(int, input().split())
g = []
for i in range(n):
g.append([])
used.append(0)
for i in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
for i in range(n):
if used[i] == 0:
global count_v
count_v = 0
count_e = 0
try:
count_e = dfs(i, g)
except Exception:
print("123")
exit(0)
if count_v * (count_v - 1) != count_e:
print("NO")
exit(0)
print("YES")
main()
```
No
| 99,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
from collections import defaultdict
from collections import deque
n,m=list(map(int,input().split()))
d=defaultdict(list)
for i in range(m):
x,y=list(map(int,input().split()))
d[x].append(y)
d[y].append(x)
visited=[0]*(n+1)
f=0
for i in range(1,n+1):
if visited[i]==0:
visited[i]=1
for k in d[i]:
visited[k]=1
for i in range(1,n+1):
if visited[i]==0:
f=1
break
if f:
print('NO')
else:
print('YES')
```
No
| 99,974 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
import sys
from collections import defaultdict
n=m=0
Group=[]
GL=defaultdict(int)
G=defaultdict(lambda:-1)
def main():
MN=input().split()
n=int(MN[0])
m=int(MN[1])
for i in range(m):
L=input().split()
L=[int(L[0]),int(L[1])]
if G[L[0]]==-1 and G[L[1]]==-1:
Group.append([L[0],L[1]])
len=Group.__len__()-1
G[L[0]]=G[L[1]]=len
GL[len]+=1
elif G[L[0]]!=-1 and G[L[1]]!=-1:
if G[L[0]]!=G[L[1]]:
No=G[L[0]]if Group[G[L[0]]].__len__()>Group[G[L[1]]].__len__()else G[L[1]]
No1=G[L[0]]if Group[G[L[0]]].__len__()<Group[G[L[1]]].__len__()else G[L[1]]
Group[No].extend(Group[No1])
for i in Group[No1]:
G[i]=No
Group[No1].clear()
GL[No]+=GL[No1]+1
else:GL[G[L[0]]]+=1
else:
No=(G[L[1]],L[0]) if G[L[1]]!=-1 else (G[L[0]],L[1])
Group[No[0]].append(No[1])
G[No[1]]=No[0]
GL[No[0]]+=1
Pass=True
for (No,i) in enumerate(Group):
len=i.__len__()-1
if len>0:
Sum=(len*len+len)/2
if Sum!=GL[No]:
print("NO")
Pass=False
break
if Pass is True:
print("YES")
if __name__=='__main__':
main()
```
No
| 99,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, <image>) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
a,b = map(int, input().split())
i=0
while a>0:
a*=3
b*=2
i+=1
if a>b:
print(i)
break
```
No
| 99,976 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Vladik has favorite game, in which he plays all his free time.
Game field could be represented as n × m matrix which consists of cells of three types:
* «.» — normal cell, player can visit it.
* «F» — finish cell, player has to finish his way there to win. There is exactly one cell of this type.
* «*» — dangerous cell, if player comes to this cell, he loses.
Initially player is located in the left top cell with coordinates (1, 1).
Player has access to 4 buttons "U", "D", "L", "R", each of them move player up, down, left and right directions respectively.
But it’s not that easy! Sometimes friends play game and change functions of buttons. Function of buttons "L" and "R" could have been swapped, also functions of buttons "U" and "D" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game.
Help Vladik win the game!
Input
First line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — number of rows and columns respectively.
Each of next n lines contains m characters describing corresponding row of field. Set of characters in field is described above.
Guaranteed that cell with coordinates (1, 1) is normal and there is at least one way from initial cell to finish cell without dangerous cells.
Interaction
You can press buttons no more than 2·n·m times.
To press a button you should print "U", "D", "L", "R" in new line. It’s necessary to print newline character and flush output. After flushing buffer you should read answer from input data. Answer is the pair of space-separated integers x, y — new position of player. In case, if there is no cell in direction of moving, position will not change. If after any move player lost, in other words player move to dangerous cell, then x and y will be equal to - 1.
If after any move player is in finish or dangerous cell, then you should terminate your program.
To finish output buffer (i. e. for operation flush) right after printing direction and newline you should do next:
* fflush(stdout) in C++
* System.out.flush() in Java
* stdout.flush() in Python
* flush(output) in Pascal
* read documentation for other languages.
Hacks
To perform a hack you should use this format:
n m swapLR swapUD
a_1
a_2
...
a_n
Where n, m — number of rows and columns in game field. swapLR is equal to 1 in case, when directions "L’’ and "R’’ is swapped, and equal to 0 otherwise. swapUD is equal to 1, when directions "U’’ and "D’’ is swapped, and equal to 0 otherwise. a1, a2, ..., an — description of corresponding rows of game field.
Example
Input
4 3
...
**.
F*.
...
1 1
1 2
1 3
1 3
2 3
3 3
4 3
4 2
4 1
3 1
Output
R
L
L
D
U
U
U
R
R
D
Note
In first test case all four directions swapped with their opposite directions. Protocol of interaction In more convenient form:
<image>
This test could be presenter for hack in following way:
4 3 1 1
...
**.
F*.
...
Submitted Solution:
```
from collections import deque
from sys import stdout
n, m = map(int, input().split())
mapa = [input() for i in range(n)]
for i in range(n):
if 'F' in mapa[i]:
f = (i, mapa[i].find('F'))
break
l, r = 'L', 'R'
u, d = 'U', 'D'
q = deque()
q.append((0, 0))
last = dict()
visited = [[False for i in range(m)] for i in range(n)]
visited[0][0] = True
a = []
while True:
x, y = q.popleft()
if ((x, y) == f):
while (x, y) in last.keys():
a.append((x, y))
x, y = last[(x, y)]
break
if x > 0 and not visited[x-1][y] and mapa[x-1][y] in '.F':
visited[x-1][y] = True
q.append((x-1, y))
last[(x-1, y)] = (x, y)
if y > 0 and not visited[x][y-1] and mapa[x][y-1] in '.F':
visited[x][y-1] = True
q.append((x, y-1))
last[(x, y-1)] = (x, y)
if x < n-1 and not visited[x+1][y] and mapa[x+1][y] in '.F':
visited[x+1][y] = True
q.append((x+1, y))
last[(x+1, y)] = (x, y)
if y < m-1 and not visited[x][y+1] and mapa[x][y+1] in '.F':
visited[x][y+1] = True
q.append((x, y+1))
last[(x, y+1)] = (x, y)
a.append((0, 0))
a = a[::-1]
lastR = True
print(a)
i = 1
while i < len(a):
x, y = a[i]
if a[i-1][0] < x:
print(d)
stdout.flush()
lastR = False
elif a[i-1][0] > x:
print(u)
stdout.flush()
lastR = False
elif a[i-1][1] < y:
print(r)
stdout.flush()
lastR = True
elif a[i-1][1] > y:
print(l)
stdout.flush()
lastR = True
newx, newy = map(int, input().split())
newx -= 1
newy -= 1
if (newx, newy) != (x, y):
if lastR: l, r = r, l
else: u, d = d, u
else:
i += 1
```
No
| 99,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Vladik has favorite game, in which he plays all his free time.
Game field could be represented as n × m matrix which consists of cells of three types:
* «.» — normal cell, player can visit it.
* «F» — finish cell, player has to finish his way there to win. There is exactly one cell of this type.
* «*» — dangerous cell, if player comes to this cell, he loses.
Initially player is located in the left top cell with coordinates (1, 1).
Player has access to 4 buttons "U", "D", "L", "R", each of them move player up, down, left and right directions respectively.
But it’s not that easy! Sometimes friends play game and change functions of buttons. Function of buttons "L" and "R" could have been swapped, also functions of buttons "U" and "D" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game.
Help Vladik win the game!
Input
First line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — number of rows and columns respectively.
Each of next n lines contains m characters describing corresponding row of field. Set of characters in field is described above.
Guaranteed that cell with coordinates (1, 1) is normal and there is at least one way from initial cell to finish cell without dangerous cells.
Interaction
You can press buttons no more than 2·n·m times.
To press a button you should print "U", "D", "L", "R" in new line. It’s necessary to print newline character and flush output. After flushing buffer you should read answer from input data. Answer is the pair of space-separated integers x, y — new position of player. In case, if there is no cell in direction of moving, position will not change. If after any move player lost, in other words player move to dangerous cell, then x and y will be equal to - 1.
If after any move player is in finish or dangerous cell, then you should terminate your program.
To finish output buffer (i. e. for operation flush) right after printing direction and newline you should do next:
* fflush(stdout) in C++
* System.out.flush() in Java
* stdout.flush() in Python
* flush(output) in Pascal
* read documentation for other languages.
Hacks
To perform a hack you should use this format:
n m swapLR swapUD
a_1
a_2
...
a_n
Where n, m — number of rows and columns in game field. swapLR is equal to 1 in case, when directions "L’’ and "R’’ is swapped, and equal to 0 otherwise. swapUD is equal to 1, when directions "U’’ and "D’’ is swapped, and equal to 0 otherwise. a1, a2, ..., an — description of corresponding rows of game field.
Example
Input
4 3
...
**.
F*.
...
1 1
1 2
1 3
1 3
2 3
3 3
4 3
4 2
4 1
3 1
Output
R
L
L
D
U
U
U
R
R
D
Note
In first test case all four directions swapped with their opposite directions. Protocol of interaction In more convenient form:
<image>
This test could be presenter for hack in following way:
4 3 1 1
...
**.
F*.
...
Submitted Solution:
```
from sys import stdout
def query(p):
print(p)
stdout.flush()
return input()
ans='0'*100000
def dfs(x,y,path):
global ans
if arr[x][y]=='F':ans=min(ans,path,key=len);return
arr[x][y]='X'
if x+1<n and arr[x+1][y]in'.F':dfs(x+1,y,path+'D')
if y+1<m and arr[x][y+1]in'.F':dfs(x,y+1,path+'R')
if y and arr[x][y-1]in'.F':dfs(x,y-1,path+'L')
if x and arr[x-1][y]in'.F':dfs(x-1,y,path+'U')
n,m=map(int,input().split())
arr=[]
for i in range(n):arr.append(list(input()))
flagH=flagV=1
arr[0][0]='X'
startx=starty=0
if arr[0][1]==arr[1][0]=='.':
x,y=map(int,query('D').split())
if not x==y==1:query('U')
else:flagV=-1
x,y=map(int,query('R').split())
if not x==y==1:query('L')
else:flagH=-1
elif arr[0][1]=='.':
x,y=map(int,query('R').split())
pr='R'
if x==y==1:flagH=-1;pr='L'
x -= 1
y -= 1
while arr[1][y]!='.':y+=1;query(pr)
qx,qy=map(int, query('D').split())
if qx!=x+1:query('U')
else:flagV=-1
startx,starty=x,y
else:
x,y=map(int,query('D').split())
pr='D'
if x==y==1:flagV=-1;pr='U'
else:query('U')
x-=1
y-=1
while arr[x][1]!='.':x+=1;query(pr)
qx,qy=map(int,query('R').split())
if qy!=y+1:query('L')
else:flagH=-1
startx,starty=x,y
dfs(startx,starty,'')
if flagH==-1:
ans2=''
for i in ans:
if i=='R':ans2+='L'
elif i=='L':ans2+='R'
else:ans2+=i
ans=ans2
if flagV==-1:
ans2=''
for i in ans:
if i == 'U':ans2 += 'D'
elif i == 'D':ans2 += 'U'
else:ans2+=i
ans=ans2
for i in ans:query(i)
'''
4 3
...
**.
F*.
...
1 2
1 3
2 3
1 3
'''
```
No
| 99,978 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Vladik has favorite game, in which he plays all his free time.
Game field could be represented as n × m matrix which consists of cells of three types:
* «.» — normal cell, player can visit it.
* «F» — finish cell, player has to finish his way there to win. There is exactly one cell of this type.
* «*» — dangerous cell, if player comes to this cell, he loses.
Initially player is located in the left top cell with coordinates (1, 1).
Player has access to 4 buttons "U", "D", "L", "R", each of them move player up, down, left and right directions respectively.
But it’s not that easy! Sometimes friends play game and change functions of buttons. Function of buttons "L" and "R" could have been swapped, also functions of buttons "U" and "D" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game.
Help Vladik win the game!
Input
First line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — number of rows and columns respectively.
Each of next n lines contains m characters describing corresponding row of field. Set of characters in field is described above.
Guaranteed that cell with coordinates (1, 1) is normal and there is at least one way from initial cell to finish cell without dangerous cells.
Interaction
You can press buttons no more than 2·n·m times.
To press a button you should print "U", "D", "L", "R" in new line. It’s necessary to print newline character and flush output. After flushing buffer you should read answer from input data. Answer is the pair of space-separated integers x, y — new position of player. In case, if there is no cell in direction of moving, position will not change. If after any move player lost, in other words player move to dangerous cell, then x and y will be equal to - 1.
If after any move player is in finish or dangerous cell, then you should terminate your program.
To finish output buffer (i. e. for operation flush) right after printing direction and newline you should do next:
* fflush(stdout) in C++
* System.out.flush() in Java
* stdout.flush() in Python
* flush(output) in Pascal
* read documentation for other languages.
Hacks
To perform a hack you should use this format:
n m swapLR swapUD
a_1
a_2
...
a_n
Where n, m — number of rows and columns in game field. swapLR is equal to 1 in case, when directions "L’’ and "R’’ is swapped, and equal to 0 otherwise. swapUD is equal to 1, when directions "U’’ and "D’’ is swapped, and equal to 0 otherwise. a1, a2, ..., an — description of corresponding rows of game field.
Example
Input
4 3
...
**.
F*.
...
1 1
1 2
1 3
1 3
2 3
3 3
4 3
4 2
4 1
3 1
Output
R
L
L
D
U
U
U
R
R
D
Note
In first test case all four directions swapped with their opposite directions. Protocol of interaction In more convenient form:
<image>
This test could be presenter for hack in following way:
4 3 1 1
...
**.
F*.
...
Submitted Solution:
```
from sys import stdin, stdout
from collections import deque
n, m = map(int, stdin.readline().split())
maps = []
for i in range(n):
maps.append(stdin.readline().strip())
if (maps[-1].count('F')):
xf, yf = maps[-1].index('F'), i
x, y = 0, 0
label1 = 0
label2 = 0
check1 = 0
check2 = 0
ans = 0
def check(label):
if not label:
stdout.write('D\n')
stdout.flush()
x, y = map(int, stdin.readline().split())
if (x, y) == (1, 1):
return 1
else:
return 0
else:
stdout.write('R\n')
stdout.flush()
x, y = map(int, stdin.readline().split())
if (x, y) == (1, 1):
return 1
else:
return 0
if n == 1:
check1, label1 = 1, 1
elif m == 1:
check2, label2 = 1, 1
elif maps[0][1] != '*' and maps[1][0] != '*':
check1 = 1
label1 = check(0)
y += label1 ^ 1
if (x, y) == (xf, yf):
ans = 1
if not ans and label1:
stdout.write('D\n')
stdout.flush()
elif not ans:
stdout.write('U\n')
stdout.flush()
if not ans:
y -= label1 ^ 1
a, b = map(int, stdin.readline().split())
if not ans:
check2 = 1
label2 = check(1)
x += label2 ^ 1
if (x, y) == (xf, yf):
ans = 1
elif maps[y + 1][x] != '*':
check1 = 1
label1 = check(0)
y += label1 ^ 1
if (x, y) == (xf, yf):
ans = 1
elif maps[y][x + 1] != '*':
check2 = 1
label2 = check(1)
x += label2 ^ 1
if (x, y) == (xf, yf):
ans = 1
if (not ans and check1 and not check2):
while (maps[y][x + 1] == '*'):
y += 1
stdout.write('DU'[label1] + '\n')
stdout.flush()
a, b = map(int, stdin.readline().split())
if (x, y) == (xf, yf):
ans = 1
break
if not ans:
stdout.write('R\n')
stdout.flush()
a, b = map(int, stdin.readline().split())
if (a - 1, b - 1) == (y, x):
check2 = 1
label2 = 1
else:
check2 = 1
label2 = 0
y, x = a - 1, b - 1
elif not ans and check2 and not check1:
while (maps[y + 1][x] == '*'):
x += 1
stdout.write('RL'[label2] + '\n')
stdout.flush()
a, b = map(int, stdin.readline().split())
if (x, y) == (xf, yf):
ans = 1
break
if not ans:
stdout.write('D\n')
stdout.flush()
a, b = map(int, stdin.readline().split())
if (a - 1, b - 1) == (y, x):
check1 = 1
label1 = 1
else:
check1 = 1
label1 = 0
xs, ys = x, y
if not ans:
queue = deque()
queue.append((x, y))
step = [(-1, 0), (1, 0), (0, -1), (0, 1)]
visit = [[0 for i in range(m)] for j in range(n)]
visit[y][x] = 1
while queue:
x, y = queue.popleft()
for i in range(4):
if m > x + step[i][0] >= 0 and n > y + step[i][1] >= 0 and not visit[y + step[i][1]][x + step[i][0]] and maps[y + step[i][1]][x + step[i][0]] != '*':
queue.append((x + step[i][0], y + step[i][1]))
visit[y + step[i][1]][x + step[i][0]] = visit[y][x] + 1
ans = []
x, y = xs, ys
while (x, y) != (xf, yf):
for i in range(4):
if m > xf + step[i][0] >= 0 and n > yf + step[i][1] >= 0 and visit[yf + step[i][1]][xf + step[i][0]] + 1 == visit[yf][xf]:
if i == 0:
ans.append('R')
elif i == 1:
ans.append('L')
elif i == 2:
ans.append('D')
else:
ans.append('U')
xf += step[i][0]
yf += step[i][1]
break
ans = ans[::-1]
if label1:
ans = ''.join(ans).replace('D', 'u')
ans = ans.replace('U', 'd')
else:
ans = ''.join(ans)
if label2:
ans = ans.replace('L', 'r')
ans = ans.replace('R', 'l')
ans = ans.upper()
for i in range(len(ans)):
stdout.write(ans[i] + '\n')
stdout.flush()
a, b = map(int, stdin.readline().split())
```
No
| 99,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Vladik has favorite game, in which he plays all his free time.
Game field could be represented as n × m matrix which consists of cells of three types:
* «.» — normal cell, player can visit it.
* «F» — finish cell, player has to finish his way there to win. There is exactly one cell of this type.
* «*» — dangerous cell, if player comes to this cell, he loses.
Initially player is located in the left top cell with coordinates (1, 1).
Player has access to 4 buttons "U", "D", "L", "R", each of them move player up, down, left and right directions respectively.
But it’s not that easy! Sometimes friends play game and change functions of buttons. Function of buttons "L" and "R" could have been swapped, also functions of buttons "U" and "D" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game.
Help Vladik win the game!
Input
First line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — number of rows and columns respectively.
Each of next n lines contains m characters describing corresponding row of field. Set of characters in field is described above.
Guaranteed that cell with coordinates (1, 1) is normal and there is at least one way from initial cell to finish cell without dangerous cells.
Interaction
You can press buttons no more than 2·n·m times.
To press a button you should print "U", "D", "L", "R" in new line. It’s necessary to print newline character and flush output. After flushing buffer you should read answer from input data. Answer is the pair of space-separated integers x, y — new position of player. In case, if there is no cell in direction of moving, position will not change. If after any move player lost, in other words player move to dangerous cell, then x and y will be equal to - 1.
If after any move player is in finish or dangerous cell, then you should terminate your program.
To finish output buffer (i. e. for operation flush) right after printing direction and newline you should do next:
* fflush(stdout) in C++
* System.out.flush() in Java
* stdout.flush() in Python
* flush(output) in Pascal
* read documentation for other languages.
Hacks
To perform a hack you should use this format:
n m swapLR swapUD
a_1
a_2
...
a_n
Where n, m — number of rows and columns in game field. swapLR is equal to 1 in case, when directions "L’’ and "R’’ is swapped, and equal to 0 otherwise. swapUD is equal to 1, when directions "U’’ and "D’’ is swapped, and equal to 0 otherwise. a1, a2, ..., an — description of corresponding rows of game field.
Example
Input
4 3
...
**.
F*.
...
1 1
1 2
1 3
1 3
2 3
3 3
4 3
4 2
4 1
3 1
Output
R
L
L
D
U
U
U
R
R
D
Note
In first test case all four directions swapped with their opposite directions. Protocol of interaction In more convenient form:
<image>
This test could be presenter for hack in following way:
4 3 1 1
...
**.
F*.
...
Submitted Solution:
```
from sys import stdout
def query(p):
print(p)
stdout.flush()
return input()
ans=''
def dfs(x,y,path):
global ans
if arr[x][y]=='F':ans=path;return
arr[x][y]='*'
if x+1<n and arr[x+1][y]=='*':dfs(x+1,y,path+'D')
if y+1<m and arr[x][y+1]=='*':dfs(x,y+1,path+'R')
if y and arr[x][y-1]=='*':dfs(x,y-1,path+'L')
if x and arr[x-1][y]=='*':dfs(x-1,y,path+'U')
n,m=map(int,input().split())
arr=[]
for i in range(n):arr.append(list(input()))
flagH=flagV=1
startx=starty=0
if arr[0][1]==arr[1][0]=='.':
x,y=map(int,query('D').split())
if not x==y==1:query('U')
else:flagV=-1
x,y=map(int,query('R').split())
if not x==y==1:query('L')
else:flagH=-1
elif arr[0][1]=='.':
x,y=map(int,query('R').split())
pr='R'
if x==y==1:flagH=-1;pr='L'
x -= 1
y -= 1
while arr[1][y]not in'.F':y+=1;query(pr)
qx,qy=map(int, query('D').split())
if arr[1][y]=='F':
if qx==x+1:query('U')
exit()
if qx!=x+1:query('U')
else:flagV=-1
startx,starty=x,y
else:
x,y=map(int,query('D').split())
pr='D'
if x==y==1:flagV=-1;pr='U'
else:query('U')
x-=1
y-=1
while arr[x][1]not in'.F':x+=1;query(pr)
qx,qy=map(int,query('R').split())
if arr[x][1]=='F':
if qy==y+1:query('L')
exit()
if qy!=y+1:query('L')
else:flagH=-1
startx,starty=x,y
dfs(startx,starty,'')
if flagH==-1:
ans2=''
for i in ans:
if i=='R':ans2+='L'
elif i=='L':ans2+='R'
else:ans2+=i
ans=ans2
if flagV==-1:
ans2=''
for i in ans:
if i == 'U':ans2 += 'D'
elif i == 'D':ans2 += 'U'
else:ans2+=i
ans=ans2
for i in ans:query(i)
'''
4 3
...
**.
F*.
...
1 2
1 3
2 3
1 3
'''
```
No
| 99,980 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Tags: binary search, brute force, combinatorics, math, matrices
Correct Solution:
```
from sys import stdin, stdout
from math import factorial
from math import log10
def check(pw, values, k):
n = len(values)
matr = [[0 for i in range(n)] for j in range(n)]
res = [[0 for i in range(n)] for j in range(n)]
pp = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
matr[i][j] = int(i >= j)
for i in range(n):
res[i][i] = 1
while pw:
if pw & 1:
for i in range(n):
for j in range(n):
pp[i][j] = 0
for i in range(n):
for j in range(n):
for z in range(n):
pp[i][j] += res[i][z] * matr[z][j]
for i in range(n):
for j in range(n):
res[i][j] = pp[i][j]
for i in range(n):
for j in range(n):
pp[i][j] = 0
for i in range(n):
for j in range(n):
for z in range(n):
pp[i][j] += matr[i][z] * matr[z][j]
for i in range(n):
for j in range(n):
matr[i][j] = pp[i][j]
pw >>= 1
ans = 0
for i in range(n):
ans += values[i] * res[i][0]
return ans >= k
def stupid(values, n, k):
ans = values[:]
if max(ans) >= k:
return 0
cnt = 0
while ans[-1] < k:
for i in range(1, n):
ans[i] += ans[i - 1]
cnt += 1
q = ans[-1]
return cnt
def clever(values, n, k):
if max(values) >= k:
return 0
l, r = 0, 10 ** 18 + 100
while r - l > 1:
m = (l + r) >> 1
if check(m, values, k):
r = m
else:
l = m
return r
def main():
n, k = map(int, stdin.readline().split())
values = list(map(int, stdin.readline().split()))[::-1]
while not values[-1]: #Проблема в том что ты удаляешь
values.pop()
n = len(values)
if n >= 10:
stdout.write(str(stupid(values[::-1], n, k)) + '\n')
else:
stdout.write(str(clever(values, n, k)) + '\n')
main()
```
| 99,981 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Tags: binary search, brute force, combinatorics, math, matrices
Correct Solution:
```
from itertools import *
n, k = map(int, input().split())
*A, = map(int, input().split())
alc = 0
for v in A:
if v > 0:
alc += 1
if max(A) >= k:
print(0)
elif alc <= 20:
l = 0
r = int(1e18)
while l + 1 < r:
m = (l + r) // 2
s = 0
for i in range(n):
if A[i] > 0:
s2 = 1
for j in range(n - i - 1):
s2 *= m + j
s2 //= j + 1
if s2 >= k:
break
s += s2 * A[i]
if s >= k:
break
if s >= k:
r = m
else:
l = m
print(r)
else:
ans = 0
while True:
ans += 1
for i in range(1, n):
A[i] += A[i - 1]
if A[-1] >= k:
break
print(ans)
```
| 99,982 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Tags: binary search, brute force, combinatorics, math, matrices
Correct Solution:
```
import sys
n, k = map(int, input().split())
ar = []
br = map(int, input().split())
for x in br:
if(x > 0 or len(ar) > 0):
ar.append(x)
if(max(ar) >= k):
print(0)
elif len(ar) == 2:
print((k - ar[1] + ar[0] - 1)//ar[0])
elif len(ar) == 3:
ini, fin = 0, 10**18
while(ini < fin):
mid = (ini + fin)//2
if(ar[2] + ar[1]*mid + ar[0]*mid*(mid + 1)//2 >= k):
fin = mid
else:
ini = mid + 1
print(ini)
else:
ans = 0;
while(ar[-1] < k):
ans += 1
for i in range(1, len(ar)):
ar[i] += ar[i - 1]
print(ans)
```
| 99,983 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Tags: binary search, brute force, combinatorics, math, matrices
Correct Solution:
```
from math import factorial
def ncr(n, r):
ans = 1
for i in range(r):
ans*=n-i
for i in range(r):
ans//=i+1
return ans
n,k = map(int, input().split())
inp = list(map(int,input().split()))
nz = 0
seq = []
for i in range(n):
if(inp[i]!=0):
nz = 1
if(nz!=0):
seq.append(inp[i])
if(max(seq) >= k):
print("0")
exit(0)
if(len(seq) <= 8):
seq.reverse()
mn = 1
mx = pow(10,18)
while(mn < mx):
mid = (mn + mx)//2
curr = 0
for i in range(len(seq)):
curr+=seq[i]*ncr(mid+i-1, i)
if(curr>=k):
mx = mid
else:
mn = mid + 1
print(mn)
exit(0)
for i in range(1000):
for j in range(1,len(seq)):
seq[j]+=seq[j-1]
if(max(seq) >= k):
print(i+1)
exit(0)
```
| 99,984 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Tags: binary search, brute force, combinatorics, math, matrices
Correct Solution:
```
import sys
def mul(a, b):
#print(a, b)
n = len(a)
m = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
m[i][j] += a[i][k] * b[k][j]
return m
n, k = [int(i) for i in input().split(" ")]
a = [int(i) for i in input().split(" ")]
if max(a) >= k:
print(0)
sys.exit(0)
a0 = [] # pole bez tych nul na zaciatku, ktore su zbytocne
s = 0
for i in range(n):
s += a[i]
if s > 0:
a0.append(a[i])
n = len(a0)
if n > 30: # pole je velke, po najviac 50 iteraciach dojdeme k odpovedi
it = 0
while True:
it += 1
for j in range(1, n):
a0[j] += a0[j-1]
if a0[j] >= k:
print(it)
sys.exit(0)
else: # pole je male, spustime nieco typu bs + umocnovanie matic
m = [[[int(i >= j) for j in range(n)] for i in range(n)]]
for l in range(0, 62):
m.append(mul(m[-1], m[-1]))
#print(m[-1])
#print(a0)
ans = 0
u = [[int(i == j) for j in range(n)] for i in range(n)]
for l in range(62, -1, -1):
u2 = mul(u, m[l])
val = 0
for i in range(0, n):
val += a0[i] * u2[-1][i]
#print(val)
if val < k:
u = u2
ans += 2**l
print(ans + 1)
```
| 99,985 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Tags: binary search, brute force, combinatorics, math, matrices
Correct Solution:
```
s=input().split()
n=int(s[0])
k=int(s[1])
L=list(map(int,input().split()))
lx=0
while L[lx]==0:
lx+=1
A=[]
for i in range(lx,n):
A.append(L[i])
n=len(A)
n=len(A)
def good(l):
coeff=1
tot=0
for i in reversed(range(n)):
tot+=coeff*A[i]
if tot>=k:
return True
coeff=(coeff*(n-i-1+l))//(n-i)
return False
ans=0
for i in range(1,10):
if good(i):
ans=i
break
if ans==0:
l=1
r=k
while True:
if l==r:
ans=l
break
if l+1==r:
if good(l):
ans=l
else:
ans=r
break
m=(l+r)//2
if good(m):
r=m
else:
l=m+1
for i in range(n):
if A[i]>=k:
ans=0
print(ans)
```
| 99,986 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Tags: binary search, brute force, combinatorics, math, matrices
Correct Solution:
```
n,k = map(int,input().split());
a = list(map(int,input().split()));
if max(a) >= k:
print(0)
exit()
lx = 0
while a[lx] == 0:
lx+=1
lo,hi = 1,k
def can(x):
bc = 1
tot = 0
for i in range(n-lx):
if(bc >= k):
return True
tot += bc*a[n-1-i]
bc *= (x+i)
bc = bc//(i+1)
if(tot >= k):
return True
return tot >= k
while lo < hi :
mid = (lo+hi)//2
cancan = can(mid)
#print(mid,cancan)
if cancan : hi = mid
else : lo = mid + 1
print(lo)
```
| 99,987 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Tags: binary search, brute force, combinatorics, math, matrices
Correct Solution:
```
n, k = map(int,input().split())
a = list(map(int,input().split()))
ptr = 0
while a[ptr]==0:
ptr += 1
def check(x):
if x==0:
return max(a) >= k
binomial = 1
sum = 0
for i in range(n-ptr):
if binomial >= k:
return True
sum += binomial * a[n-i-1]
binomial *= (x+i)
binomial //= (i+1)
if sum >= k:
return True
return False
lo,hi = 0, k
while lo < hi:
md = (lo+hi) // 2
if check(md):
hi = md;
else:
lo = md + 1
print(lo)
```
| 99,988 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Submitted Solution:
```
import sys
from time import sleep
def increment(a):
for i in range(1, n):
a[i] += a[i-1]
class DimensionError(ValueError):
pass
class Matrix:
def __init__(self, m, n, data=None):
self.m = m
self.n = n
self.mn = m * n
if data is None:
self.data = [0] * self.mn
else:
if len(data) == self.mn:
self.data = data
else:
raise DimensionError()
def __repr__(self):
return 'Matrix({}, {}, {})'.format(self.m, self.n, self.data)
def __call__(self, i, j):
if i < 0 or i >= self.m or j < 0 or j >= self.n:
raise IndexError("({}, {})".format(i, j))
return self.data[i * self.n + j]
def set_elem(self, i, j, x):
if i < 0 or i >= self.m or j < 0 or j >= self.n:
raise IndexError("({}, {})".format(i, j))
self.data[i * self.n + j] = x
def add_to_elem(self, i, j, x):
if i < 0 or i >= self.m or j < 0 or j >= self.n:
raise IndexError("({}, {})".format(i, j))
self.data[i * self.n + j] += x
def last(self):
return self.data[-1]
def scalar_mul_ip(self, s):
for i in range(len(data)):
self.data[i] *= s
return self
def scalar_mul(self, s):
data2 = [x * s for x in self.data]
return Matrix(self.m, self.n, data2)
def matrix_mul(self, B):
if self.n != B.m:
raise DimensionError()
m = self.m
p = self.n
n = B.n
C = Matrix(m, n)
for i in range(m):
for j in range(n):
for k in range(p):
C.add_to_elem(i, j, self(i, k) * B(k, j))
return C
def __imul__(self, x):
if isinstance(x, int):
return self.scalar_mul_ip(x)
# Matrix multiplication will be handled by __mul__
else:
return NotImplemented
def __mul__(self, x):
if isinstance(x, int):
return self.scalar_mul(x)
elif isinstance(x, Matrix):
return self.matrix_mul(x)
else:
return NotImplemented
def __rmul__(self, x):
if isinstance(x, int):
return self.scalar_mul(x)
# Matrix multiplication will be handled by __mul__
else:
return NotImplemented
if __name__ == '__main__':
n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
assert(len(a) == n)
for i, x in enumerate(a):
if x > 0:
break
if i > 0:
a = a[i:]
n = len(a)
if max(a) >= k:
print(0)
sys.exit(0)
else:
increment(a)
if n > 10:
p = 0
while a[-1] < k:
increment(a)
p += 1
"""
if p % 100 == 0 and sys.stderr.isatty():
print(' ' * 40, end='\r', file=sys.stderr)
print(p, a[-1], end='\r', file=sys.stderr)
"""
"""
if sys.stderr.isatty():
print(file=sys.stderr)
"""
print(p+1)
sys.exit(0)
if a[-1] >= k:
print(1)
sys.exit(0)
A = Matrix(n, n)
for i in range(n):
for j in range(i+1):
A.set_elem(i, j, 1)
X = Matrix(n, 1, a)
pA = [A] # pA[i] = A^(2^i)
i=0
while (pA[i]*X).last() < k:
# print('len(pA) =', len(pA), file=sys.stderr)
# print('pA[-1] =', pA[-1].data, file=sys.stderr)
pA.append(pA[i] * pA[i])
i += 1
# print('pA computed', file=sys.stderr)
B = Matrix(n, n)
for i in range(n):
B.set_elem(i, i, 1)
p = 0
for i, A2 in reversed(list(enumerate(pA))):
# invariant: B = A^p and B is a power of A such that (B*X).last() < k
B2 = B * A2
if (B2 * X).last() < k:
p += (1 << i)
B = B2
# Now increment X so that X.last() becomes >= k
X = B * X
p += 1
increment(X.data)
# Print p+1 because we had incremented X in the beginning of program
print(p+1)
```
Yes
| 99,989 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Submitted Solution:
```
mod = 10**9 + 7
n, k = map(int,input().split())
a = list(map(int, input().split()))
a.reverse()
def sol() :
l = 0; r = 10**18; mid = 0; p = 1; sum = 0
while r - l > 1 :
mid = (l + r) // 2
p = 1; sum = 0
for i in range(n) :
if a[i] * p >= k : r = mid; break
sum += a[i] * p
if sum >= k : r = mid; break
if i + 1 < n : p = p * (mid + i) // (i + 1)
if p >= k : r = mid; break
if r != mid : l = mid + 1
p = 1; sum = 0
for i in range(n) :
if a[i] * p >= k : return l
sum += a[i] * p
if sum >= k : return l
if i + 1 < n : p = p * (l + i) // (i + 1)
if p >= k : return l
return r
for i in range(n - 1, -1, -1) :
if a[i] != 0 : break
else : n -= 1
if max(a) >= k : print(0)
else : print(sol())
```
Yes
| 99,990 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Submitted Solution:
```
s = input().split()
n = int(s[0]); k = int(s[1])
s = input().split()
a = [1]
for i in range(1, n + 1):
a.append(int(s[i - 1]))
for i in range(1, n + 1):
if (a[i] >= k):
print(0); exit(0)
def C(nn, kk):
global k
prod = 1
kk = min(kk, nn - kk)
# print(nn, nn - kk + 1)
for i in range(1, kk + 1):
# print("///" + str(i))
prod *= nn - i + 1
prod = prod // i
if (prod >= k):
return -1
if (prod >= k):
return -1
return prod
def holyshit(pwr):
global n, k, a
sum = 0
for i in range(n, 0, -1):
if (a[i] == 0):
continue
prod = C(pwr - 1 + n - i, pwr - 1)
if (prod == -1):
return True
sum += prod * a[i]
if (sum >= k):
return True
# print("wait, the sum is..." + str(sum))
return False
left = 1; right = int(1e19); ans = int(1e19)
while left <= right:
mid = (left + right) >> 1
# print("/" + str(left) + " " + str(mid) + " " + str(right))
if (holyshit(mid)):
# print("////okay")
ans = mid
right = mid - 1
else:
# print("////notokay")
left = mid + 1
print(ans)
# print(int(1e19))
# k = int(1e18)
# # print(C(6, 3))
# # print(C(10, 1))
# # print(C(7, 5))
# # print(C(8, 2))
```
Yes
| 99,991 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Submitted Solution:
```
n, k = map(int, input().split())
A = []
for x in map(int, input().split()):
if x > 0 or len(A) > 0:
A.append(x)
if max(A) >= k:
print(0)
elif len(A) == 2:
if (k-A[1]) % A[0] == 0:
print((k-A[1])//A[0])
else :
print ((k-A[1])//A[0] + 1)
elif len(A) == 3:
left = 0
right = 10**18
while left < right:
mid = (left + right) // 2
if A[2] + A[1] * mid + A[0] * mid * (mid + 1) // 2 >= k:
right = mid
else : left = mid + 1
print (left)
else :
ans = 0
while A[-1] < k:
ans += 1
for i in range(1, len(A)):
A[i] += A[i-1]
print (ans)
```
Yes
| 99,992 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Submitted Solution:
```
def list_input():
return list(map(int,input().split()))
def map_input():
return map(int,input().split())
def map_string():
return input().split()
def power(a,b,m):
if b == 0: return 1
if b == 1: return a
x = min(power(a,b//2,m),m)
if b%2 == 1: return min(m,x*x*a)
else: return min(m,x*x)
def solve(a,n,k,i):
res = 0
cur = n
if i == 0:
return max(a) >= k
for j in range(n):
res += a[j]*power(cur,i-1,k)
if res >= k:
return True
cur -= 1
return False
n,k = map(int,input().split())
a = list_input()
b = []
for i in a:
if i != 0:
b.append(i)
a = b[::]
n = len(a)
low = 0
high = k
ans = -1
while low <= high:
mid = (low+high)//2
if solve(a,n,k,mid):
high = mid-1
ans = mid
else:
low = mid+1
print(ans)
```
No
| 99,993 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Submitted Solution:
```
n, k = map(int,input().split())
a = list(map(int,input().split()))
def check(x):
if x==0:
return max(a) >= k
binomial = 1
sum = 0
for i in range(n):
if binomial >= k:
return True
sum += binomial * a[n-i-1]
binomial *= (x+i)
binomial //= (i+1)
if sum >= k:
return True
return False
lo,hi = 0, k
while lo < hi:
md = (lo+hi) // 2
if check(md):
hi = md;
else:
lo = md + 1
print(lo)
```
No
| 99,994 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Submitted Solution:
```
import math
n, k = map(int, input().split())
A = []
for x in map(int, input().split()):
if x > 0 or len(A) > 0:
A.append(x)
if max(A) >= k:
print(0)
elif len(A) == 2:
print (math.ceil((k-A[1])/A[0]))
elif len(A) == 3:
left = 0
right = 10**18
while left < right:
mid = (left + right) // 2
if A[0] + A[1] * mid + A[2] * mid * (mid + 1) // 2 >= k:
right = mid
else : left = mid + 1
print (left)
else :
ans = 0
while A[-1] < k:
ans += 1
for i in range(1, len(A)):
A[i] += A[i-1]
print (ans)
```
No
| 99,995 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i ≥ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 1018). n is the size of array A0.
The second line contains n integers A00, A01... A0n - 1 — the elements of A0 (0 ≤ A0i ≤ 109). At least two elements of A0 are positive.
Output
Print the minimum i such that Ai contains a number which is larger or equal than k.
Examples
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
Submitted Solution:
```
from math import factorial
def ncr(n, r):
ans = 1
for i in range(r):
ans*=n-i
for i in range(r):
ans/=i+1
return ans
n,k = map(int, input().split())
inp = list(map(int,input().split()))
nz = 0
seq = []
for i in range(n):
if(inp[i]!=0):
nz = 1
if(nz!=0):
seq.append(inp[i])
if(max(seq) >= k):
print("0")
exit(0)
if(len(seq) <= 8):
seq.reverse()
mn = 1
mx = pow(10,18)
while(mn < mx):
mid = (mn + mx)//2
curr = 0
for i in range(len(seq)):
curr+=seq[i]*ncr(mid+i-1, i)
if(curr>=k):
mx = mid
else:
mn = mid + 1
print(mn)
exit(0)
for i in range(1000):
for j in range(1,len(seq)):
seq[j]+=seq[j-1]
if(max(seq) >= k):
print(i)
exit(0)
```
No
| 99,996 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.
Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.
Given this information, is it possible to restore the exact floor for flat n?
Input
The first line contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory.
m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers ki, fi (1 ≤ ki ≤ 100, 1 ≤ fi ≤ 100), which means that the flat ki is on the fi-th floor. All values ki are distinct.
It is guaranteed that the given information is not self-contradictory.
Output
Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.
Examples
Input
10 3
6 2
2 1
7 3
Output
4
Input
8 4
3 1
6 2
5 2
2 1
Output
-1
Note
In the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.
In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.
Tags: brute force, implementation
Correct Solution:
```
n, m = [int(i) for i in input().split()]
mn = 10 ** 5
mx = 1
n -= 1
for i in range(m):
x, y = [int(i) for i in input().split()]
x -= 1
y -= 1
if y != 0:
mn = min(mn, x // y)
mx = max(mx, [(x + y) // (y + 1), x // (y + 1) + 1][x % (y + 1) == 0])
a = n // mx
for i in range(mx + 1, mn + 1):
if a != n // i:
print(-1)
exit()
print(a + 1)
```
| 99,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.
Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.
Given this information, is it possible to restore the exact floor for flat n?
Input
The first line contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory.
m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers ki, fi (1 ≤ ki ≤ 100, 1 ≤ fi ≤ 100), which means that the flat ki is on the fi-th floor. All values ki are distinct.
It is guaranteed that the given information is not self-contradictory.
Output
Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.
Examples
Input
10 3
6 2
2 1
7 3
Output
4
Input
8 4
3 1
6 2
5 2
2 1
Output
-1
Note
In the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.
In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.
Tags: brute force, implementation
Correct Solution:
```
import math
from sys import stdin
from math import ceil
if __name__ == '__main__':
numbers = list(map(int, input().split()))
n = numbers[0]
m = numbers[1]
floors = []
for i in range(m):
floors.append(tuple(map(int, input().split())))
rez = set()
for i in range(1,100 + 1):
ok = True
for ki, fi in floors:
if (ki + i - 1) // i != fi:
ok = False
break
if ok:
rez.add((n + i - 1) // i)
if len(rez) == 1:
x = rez.pop()
print(x)
else:
print("-1")
```
| 99,998 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.
Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.
Given this information, is it possible to restore the exact floor for flat n?
Input
The first line contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory.
m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers ki, fi (1 ≤ ki ≤ 100, 1 ≤ fi ≤ 100), which means that the flat ki is on the fi-th floor. All values ki are distinct.
It is guaranteed that the given information is not self-contradictory.
Output
Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.
Examples
Input
10 3
6 2
2 1
7 3
Output
4
Input
8 4
3 1
6 2
5 2
2 1
Output
-1
Note
In the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.
In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.
Tags: brute force, implementation
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n, m = map(int, input().split())
l = set()
s = {i for i in range(1, 101)}
b = False
for i in range(m):
k, f = map(int, input().split())
if k == n:
print(f)
b = True
break
j = 1
if f == 1:
l = {i for i in range(k, 101)}
else:
while j <= (k-j)//(f-1):
if (k-j)%(f-1) == 0:
l.add((k-j)//(f-1))
j += f-1
else:
j += 1
s &= l
l.clear()
a = -1
if b == False:
t = True
for j in s:
if a == -1:
a = (n-1)//j
else:
if (n-1)//j != a:
print(-1)
t = False
break
if t == True:
print(a+1)
```
| 99,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.