message stringlengths 2 65.1k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 0 108k | cluster float64 14 14 | __index_level_0__ int64 0 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.
The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.
When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.
What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?
Constraints
* All values in input are integers.
* 2 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \dots A_N
Output
Print the maximum total comfort the N players can get.
Examples
Input
4
2 2 1 3
Output
7
Input
7
1 1 1 1 1 1 1
Output
6
Submitted Solution:
```
import heapq
n = int(input())
data = list(map(int, input().split()))
data.sort(reverse=True)
q = []
heapq.heappush(q, data[1])
heapq.heappush(q, data[1])
result = data[0]
for i in range(2, n):
result += heapq.heappop(q)
heapq.heappush(q, data[i])
heapq.heappush(q, data[i])
print(result)
``` | instruction | 0 | 29,758 | 14 | 59,516 |
No | output | 1 | 29,758 | 14 | 59,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483 | instruction | 0 | 30,193 | 14 | 60,386 |
Tags: combinatorics, math, probabilities
Correct Solution:
```
#!/usr/bin/env python3
import sys
from math import gcd
#lines = stdin.readlines()
def lcm(a,b):
return a*b//gcd(a,b)
def rint():
return map(int, sys.stdin.readline().split())
def input():
return sys.stdin.readline().rstrip('\n')
def oint():
return int(input())
n = oint()
k = []
l = 1
ka = []
cnt = dict()
for i in range(n):
ka.append(list(rint()))
l = lcm(l, ka[i][0])
for ki in range(1, ka[i][0]+1):
kk = ka[i][ki]
if kk in cnt:
cnt[kk] += 1
else:
cnt[kk] = 1
l*= n
ans1 = 0
for i in range(n):
mul = l // (ka[i][0]*n)
ans2 = 0
for ki in range(1, ka[i][0] +1):
kk = ka[i][ki]
ans2 += (n-cnt[kk])
ans1 += mul*ans2
print(pow(l*n, 998244353-2, 998244353)*(l*n-ans1)%998244353)
``` | output | 1 | 30,193 | 14 | 60,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483 | instruction | 0 | 30,194 | 14 | 60,388 |
Tags: combinatorics, math, probabilities
Correct Solution:
```
from sys import stdin,stdout
from math import gcd
n=int(stdin.readline().strip())
cnt=[0 for i in range(1000100)]
mod=998244353
s=[ list(map(int,stdin.readline().strip().split())) for i in range(n)]
for i in range(n):
for y in range(1,len(s[i])):
cnt[s[i][y]]+=1
ans=[0,1]
for i in range(n):
for y in range(1,len(s[i])):
j=s[i][y]
f1=[1*cnt[j],s[i][0]*n*n]
den=ans[1]*f1[1]
ans=[(den//ans[1])*ans[0]+(den//f1[1])*f1[0],den]
ans[0]%=mod
ans[1]%=mod
print((ans[0]*pow(ans[1],mod-2,mod))%mod)
``` | output | 1 | 30,194 | 14 | 60,389 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483 | instruction | 0 | 30,195 | 14 | 60,390 |
Tags: combinatorics, math, probabilities
Correct Solution:
```
import math
#------------------------------warmup----------------------------
import os
import sys
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----------------------------------------------------
import math
def modInverse(b,m):
g = math.gcd(b, m)
if (g != 1):
return -1
else:
return pow(b, m - 2, m)
def modDivide(a,b,m):
a = a % m
inv = modInverse(b,m)
if(inv == -1):
print("Division not defined")
else:
return ((inv*a) % m)
n=int(input())
k=[0]*n
s1=[]
d=dict()
tot=1
for i in range(n):
s=list(map(int,input().split()))
s1.append(s)
k[i]=s[0]
tot=(tot*k[i])%998244353
for j in range(1,len(s)):
if s[j] in d:
d[s[j]]+=1
else:
d.update({s[j]:1})
ty=0
for i in range(n):
num=0
for j in range(k[i]):
num+=d[s1[i][j+1]]
num*=modDivide(tot,k[i],998244353)
ty+=num
ty%=998244353
#print(ty,tot*n*n)
print(modDivide(ty,(tot*n*n)%998244353,998244353))
``` | output | 1 | 30,195 | 14 | 60,391 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483 | instruction | 0 | 30,196 | 14 | 60,392 |
Tags: combinatorics, math, probabilities
Correct Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def power(a, b, mod):
res = 1
while b:
if b%2:
res = (res*a)%mod
b //= 2
a = (a*a)%mod
return res%mod
MOD = 998244353
n = int(input())
groups = [0]*(10**6+1)
inp = []
for i in range(n):
a = list(map(int, input().split()))
for j in range(1, 1+a[0]):
groups[a[j]] += 1
inp.append(a)
ans = 0
for i in inp:
for j in range(len(i)):
if j:
add = (groups[i[j]]*power((n*n)%MOD, MOD-2, MOD))%MOD
add = (add*power(len(i)-1, MOD-2, MOD))%MOD
ans = (ans+add)%MOD
# ans = (ans + (groups[i[j]]*power((n*n)%MOD, MOD-2, MOD)*power(len(i)-1, MOD-2, MOD))%MOD)%MOD
# ans += (1/n)*(1/len(i))*(groups[j]/n)
print(ans)
``` | output | 1 | 30,196 | 14 | 60,393 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483 | instruction | 0 | 30,197 | 14 | 60,394 |
Tags: combinatorics, math, probabilities
Correct Solution:
```
import sys
from collections import Counter
mod = 998244353
n = int(input())
div_n = pow(n, mod-2, mod)
wants = []
cnt = Counter()
for a in (list(map(int, l.split())) for l in sys.stdin):
wants.append(a[1:])
cnt.update(a[1:])
ans = 0
for i in range(n):
prob = div_n * pow(len(wants[i]), mod-2, mod) * div_n % mod
for x in wants[i]:
ans = (ans + prob * cnt[x]) % mod
print(ans)
``` | output | 1 | 30,197 | 14 | 60,395 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483 | instruction | 0 | 30,198 | 14 | 60,396 |
Tags: combinatorics, math, probabilities
Correct Solution:
```
import sys
input=sys.stdin.readline
def modInverse(a, m):
m0 = m
y = 0
x = 1
if (m == 1):
return 0
while (a > 1):
# q is quotient
q = a // m
t = m
# m is remainder now, process
# same as Euclid's algo
m = a % m
a = t
t = y
# Update x and y
y = x - q * y
x = t
# Make x positive
if (x < 0):
x = x + m0
return x
# Driver code
x=3
a = 5
m = 998244353
# Function call
# print("Modular multiplicative inverse is",
# (modInverse(a, m)*x)%m)
from fractions import Fraction
n=int(input())
ks=[]
for _ in range(n):
temp=list(map(int,input().split()))
ks.append(temp[1:])
g_vs_n={}
for i in range(0,len(ks)):
for j in range(0,len(ks[i])):
if ks[i][j] not in g_vs_n:
g_vs_n[ks[i][j]]=0
g_vs_n[ks[i][j]] +=1
final=Fraction(0,1)
# print(g_vs_n)
for i in range(0,n):
temp=Fraction(0,1)
for j in range(len(ks[i])):
temp+=Fraction(g_vs_n[ks[i][j]],n)
# print(Fraction(g_vs_n[ks[i][j]],n))
# print(temp)
temp*=Fraction(1,len(ks[i]))
# print(temp)
final+=temp
final*=Fraction(1,n)
print((modInverse(final.denominator,m)*final.numerator)%m)
``` | output | 1 | 30,198 | 14 | 60,397 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483 | instruction | 0 | 30,199 | 14 | 60,398 |
Tags: combinatorics, math, probabilities
Correct Solution:
```
from math import gcd
from collections import Counter
import sys
# inf = open('input.txt', 'r')
# reader = (map(int, line.split()) for line in inf)
reader = (map(int, line.split()) for line in sys.stdin)
input = reader.__next__
modulo = 998244353
def lcm(lst):
res = lst[0]
for el in lst[1:]:
res = res * el // gcd(res, el)
return res
def invMod(n) :
return pow(n, modulo - 2, modulo)
def fracMod(a, b) :
return a * invMod(b) % modulo
n, = input()
length_lst = []
presentWanted = Counter()
wishList = []
for i in range(n):
k, *a = input()
length_lst.append(len(a))
wishList.append(a)
for present in a:
presentWanted[present] += 1
lcm_len = lcm(length_lst)
denom = lcm_len % modulo
denom *= pow(n, 2, modulo)
denom %= modulo
nom = 0
for wish in wishList:
wish_len = len(wish)
f = lcm_len // wish_len
f %= modulo
for present in wish:
nom += f * presentWanted[present]
nom %= modulo
ans = fracMod(nom, denom)
print(ans)
# inf.close()
``` | output | 1 | 30,199 | 14 | 60,399 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483 | instruction | 0 | 30,200 | 14 | 60,400 |
Tags: combinatorics, math, probabilities
Correct Solution:
```
from fractions import Fraction as Fr
import sys
import math
input=sys.stdin.readline
#This part is taken from gfg
def modInverse(b,m):
g = math.gcd(b, m)
if (g != 1):
return -1
else:
return pow(b, m - 2, m)
def mod(a,b,m):
a = a % m
inv = modInverse(b,m)
if(inv == -1):
return -999999999
else:
return (inv*a)%m
#End
input=sys.stdin.readline
n=int(input())
d=[0 for i in range(10**6+1)]
a=[]
for i in range(n):
p=[int(x) for x in input().split()]
for j in range(1,p[0]+1):
d[p[j]]+=1
a.append(p)
c=0
ds=0
for i in range(n):
c=Fr(1,n)
c=c*Fr(1,a[i][0])
s=0
for j in range(1,a[i][0]+1):
s=s+(Fr(d[a[i][j]],n))
c=c*s
ds=ds+c
#print()
ds=str(ds)
if "/" not in ds :
print(int(ds)%998244353)
exit(0)
nr=int(ds[:ds.index('/')])
dr=int(ds[ds.index('/')+1:])
print(mod(nr,dr,998244353 ))
``` | output | 1 | 30,200 | 14 | 60,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483
Submitted Solution:
```
MOD=998244353
import math
import sys
def powr(n,N):
temp=1
while(N>0):
if(N%2!=0):
temp=(temp*n)%MOD
n=(n*n)%MOD
N=N//2
return (temp%MOD)
def MODI(a,b):
ans=(powr(a,b)%MOD)
return ans
n=int(input())
pos=dict()
L=[]
for _ in range(n):
s=list(map(int,sys.stdin.readline().strip().split()))
L.append(s)
for i in range(1,len(s)):
if(pos.get(s[i])==None):
pos[s[i]]=1
else:
pos[s[i]]=(pos[s[i]]+1)%MOD
num=[]
den=[]
tot=0
for i in range(0,len(L)):
c=0
for j in range(1,len(L[i])):
c=(c+pos[L[i][j]])%MOD
tot=(tot+(c*MODI(((L[i][0])%MOD)%MOD,MOD-2)%MOD))%MOD
ans=MODI((n*n)%MOD,MOD-2)%MOD
ans=(ans*tot)%MOD
print(ans%MOD)
"""MOD=998244353
import math
def powr(n,N):
temp=1
while(N>0):
if(N%2!=0):
temp=(temp*n)%MOD
n=(n*n)%MOD
N=N//2
return (temp%MOD)
def MODI(a,b):
ans=(powr(a,b)%MOD)
return ans
n=int(input())
pos=[0]*1000006
L=[]
for _ in range(n):
s=[int(x) for x in input().split()]
L.append(s)
for i in range(1,len(s)):
pos[s[i]]=(pos[s[i]]+1)%MOD
num=[]
den=[]
for i in range(0,len(L)):
c=0
for j in range(1,len(L[i])):
c=(c+pos[L[i][j]])%MOD
if(c>0):
num.append(c%MOD)
den.append((n*(len(L[i])-1)%MOD)%MOD)
tot=0
if(len(num)==0):
print(0)
else:
g=den[0]
for i in range(1,len(den)):
t1=((g*den[i])%MOD)
t2=math.gcd(g,den[i])%MOD
g=(t1*MODI(t2,MOD-2)%MOD)%MOD
for i in range(0,len(num)):
t1=MODI(den[i],MOD-2)%MOD
t2=(t1*g)%MOD
num[i]=(num[i]*t2)%MOD
tot=(tot+num[i])%MOD
ans=MODI(g*n,MOD-2)%MOD
ans=(ans*tot)%MOD
print(ans%MOD)
"""
``` | instruction | 0 | 30,201 | 14 | 60,402 |
Yes | output | 1 | 30,201 | 14 | 60,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483
Submitted Solution:
```
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest
# sys.setrecursionlimit(111111)
def main():
mod=998244353
# InverseofNumber(mod)
# InverseofFactorial(mod)
# factorial(mod)
starttime=datetime.datetime.now()
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
tc=1
for _ in range(tc):
kids=ri()
z=[]
t=[]
for i in range(kids):
a=ria()
t+=a[1:]
z.append(a)
d=Counter(t)
# print(d)
ways=0
prob=0
for i in range(kids):
p=kids*z[i][0]*kids
for j in range(z[i][0]):
# probforthisgift=(1/kids)*(1/z[i][0])*(d[z[i][j+1]/kids)
# print(d[z[i][j+1]])
prob=(prob+d[z[i][j+1]]*pow(p,mod-2,mod)+mod)%mod
wi(prob%mod)
#<--Solving Area Ends
endtime=datetime.datetime.now()
time=(endtime-starttime).total_seconds()*1000
if(os.path.exists('input.txt')):
print("Time:",time,"ms")
class FastReader(io.IOBase):
newlines = 0
def __init__(self, fd, chunk_size=1024 * 8):
self._fd = fd
self._chunk_size = chunk_size
self.buffer = io.BytesIO()
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
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, size=-1):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
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()
class FastWriter(io.IOBase):
def __init__(self, fd):
self._fd = fd
self.buffer = io.BytesIO()
self.write = self.buffer.write
def flush(self):
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class FastStdin(io.IOBase):
def __init__(self, fd=0):
self.buffer = FastReader(fd)
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class FastStdout(io.IOBase):
def __init__(self, fd=1):
self.buffer = FastWriter(fd)
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.flush = self.buffer.flush
if __name__ == '__main__':
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()
``` | instruction | 0 | 30,202 | 14 | 60,404 |
Yes | output | 1 | 30,202 | 14 | 60,405 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483
Submitted Solution:
```
"""#!/usr/bin/env pypy"""
import collections
import random
import heapq
import bisect
import math
import time
class Solution2:
def solve(self, A1, A2):
pass
def gcd(a, b):
if not b: return a
return gcd(b, a%b)
def lcm(a, b):
return b*a//gcd(b,a)
class Solution:
def solve(self, kids):
# A = A[::-1]
# B = B[::-1]
# out = 0
# while B:
# if A[-1] == B[-1]:
# B.pop()
# A.pop()
# out += 1
# else:
# setted = set()
# i = 0
# while A:
# setted.add(A.pop())
# while B and B[-1] in setted:
# setted.discard(B.pop())
# out += 1
# if not setted or not B:
# out += 2*i
# break
# i += 1
# #print(setted,A,B,out)
# return out
MOD = 998244353
def inv(a):
g = MOD
r = a
x = 0
y = 1
while r != 0:
q = int(g/r)
g %= r
g, r = r, g
x -= q * y
x, y = y, x
return x + MOD if x < 0 else x
INV = inv(len(kids))
count = collections.defaultdict(int)
for kid in kids:
for present in kid:
count[present] += 1
out = 0
for kid in kids:
tt = 0
for p in kid:
tt += count[p]*INV
tt *= inv(len(kid))
out += int(tt)
out %= MOD
return out * INV % MOD
sol = Solution()
sol2 = Solution2()
#TT = int(input())
for test_case in range(1):
#N, K=input().split()
s = input()
a = []
for _ in range(int(s)):
a.append([int(c) for c in input().split()[1:]])
#b = list(set([random.randrange(1,10000) for _ in range(1000)]))
#a.append(b)
#b = [int(c) for c in input().split()]
#dd = [int(c) for c in input().split()]
out = sol.solve(a)
print(str(out))
#print(str(out))
# out2 = sol2.solve(s)
# for _ in range(100000):
# rand = [random.randrange(60) for _ in range(10)]
# out1 = sol.solve(rand)
# out2 = sol2.solve(rand)
# if out1 != out2:
# print(rand, out1, out2)
# break
``` | instruction | 0 | 30,203 | 14 | 60,406 |
Yes | output | 1 | 30,203 | 14 | 60,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483
Submitted Solution:
```
from math import gcd
from sys import stdin
input=stdin.readline
mod=998244353
n=int(input())
a=[]
for i in range(n):
a.append(list(map(int,input().split())))
b=[0]*(10**6+1)
for i in a:
for j in i[1:]:
b[j]+=1
x=[]
for i in a:
su=0
for j in i[1:]:
su+=b[j]
r=gcd(su,i[0])
x.append([su//r,i[0]//r])
ans=0
n=n**2
a=0
b=1
for i in x:
p=a*i[1]
q=b*i[0]
b=b*i[1]
a=p+q
r=gcd(a,b)
a//=r
b//=r
b*=n
r=gcd(a,b)
a//=r
b//=r
b=pow(b,mod-2,mod)
print((a*b)%mod)
``` | instruction | 0 | 30,204 | 14 | 60,408 |
Yes | output | 1 | 30,204 | 14 | 60,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483
Submitted Solution:
```
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, x, y = egcd(b % a, a)
return (g, y - (b // a) * x, x)
# x = mulinv(b) mod n, (x * b) % n == 1
def mulinv(b, n):
g, x, _ = egcd(b, n)
if g == 1:
return x % n
return 0
mod = 998244353
mx = int(1e6 + 1000)
a = [0] * mx
b = [0] * mx
n = int(input())
mn = n
for i in range(n):
ins = list(map(int, input().split()))
if mn % (ins[0] * n) != 0:
mn *= ins[0] * n
for j in range(ins[0]):
item = ins[j + 1]
item -= 1
a[item] += (1.0 / ins[0]) / n
b[item] += 1.0 / n
s = 0
for i in range(mx):
s += round(a[i] * b[i] * mn)
print(s * mulinv(mn, mod) % mod)
``` | instruction | 0 | 30,205 | 14 | 60,410 |
No | output | 1 | 30,205 | 14 | 60,411 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483
Submitted Solution:
```
import math
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, x, y = egcd(b % a, a)
return (g, y - (b // a) * x, x)
# x = mulinv(b) mod n, (x * b) % n == 1
def mulinv(b, n):
g, x, _ = egcd(b, n)
if g == 1:
return x % n
return 0
mod = 998244353
mx = int(1e6 + 1000)
a = [0] * mx
b = [0] * mx
n = int(input())
mn = n
for i in range(n):
ins = list(map(int, input().split()))
if mn % (ins[0] * n * n) != 0:
x = mn
y = ins[0] * n * n
common = []
for j in range(2, int(math.sqrt(y)) + 1):
while y % j == 0:
y /= j
common.append(j)
for div in common:
if x % div == 0:
x /= div
else:
mn *= div
for j in range(ins[0]):
item = ins[j + 1]
item -= 1
a[item] += (1.0 / ins[0]) / n
b[item] += 1.0 / n
s = 0
for i in range(mx):
s += a[i] * b[i] * mn
s = round(s)
print((s * mulinv(mn, mod)) % mod)
``` | instruction | 0 | 30,206 | 14 | 60,412 |
No | output | 1 | 30,206 | 14 | 60,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483
Submitted Solution:
```
# import sys
# sys.stdin=open("input1.in","r")
# sys.stdout=open("outpul.out","w")
N=int(input())
m=998244353
L=[]
cnt=[0]*(1000007)
for i in range(N):
L.append(list(map(int,input().split())))
k=L[i][0]
for j in range(1,k+1):
cnt[L[i][j]]+=1
ans=0
invN=pow(N,m-2,m)
for i in range(N):
k=L[i][0]
invK=pow(k,m-2,m)
for j in range(1,k+1):
ans=ans+(invN*invK)*(cnt[j]*invN)
print(ans%m)
``` | instruction | 0 | 30,207 | 14 | 60,414 |
No | output | 1 | 30,207 | 14 | 60,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Santa Claus has received letters from n different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the i-th kid asked Santa to give them one of k_i different items as a present. Some items could have been asked by multiple kids.
Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:
* choose one kid x equiprobably among all n kids;
* choose some item y equiprobably among all k_x items kid x wants;
* choose a kid z who will receive the present equipropably among all n kids (this choice is independent of choosing x and y); the resulting triple (x, y, z) is called the decision of the Bot.
If kid z listed item y as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.
Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?
Input
The first line contains one integer n (1 β€ n β€ 10^6) β the number of kids who wrote their letters to Santa.
Then n lines follow, the i-th of them contains a list of items wanted by the i-th kid in the following format: k_i a_{i, 1} a_{i, 2} ... a_{i, k_i} (1 β€ k_i, a_{i, j} β€ 10^6), where k_i is the number of items wanted by the i-th kid, and a_{i, j} are the items themselves. No item is contained in the same list more than once.
It is guaranteed that β _{i = 1}^{n} k_i β€ 10^6.
Output
Print the probatility that the Bot produces a valid decision as follows:
Let this probability be represented as an irreducible fraction x/y. You have to print x β
y^{-1} mod 998244353, where y^{-1} is the inverse element of y modulo 998244353 (such integer that y β
y^{-1} has remainder 1 modulo 998244353).
Examples
Input
2
2 2 1
1 1
Output
124780545
Input
5
2 1 2
2 3 1
3 2 4 3
2 1 4
3 4 3 2
Output
798595483
Submitted Solution:
```
import sys
mod=998244353
# print((2*pow(5,mod-2,mod))%mod)
def inv(k):
return pow(k,mod-2,mod)
# exit()
d={}
k={}
n=int(input())
ans=0
l=[0]*(n)
for _ in range(n):
d[_]=list(map(int,sys.stdin.readline().split()))
for i in d[_][1:]:
k[i]=k.get(i,0) + 1
# print(k)
for i in range(n):
for j in d[i][1:]:
# print(d[i][0],n-k[j])
ans+=(inv((d[i][0]))*(n-k[j]))%mod
ans%=mod
# print(ans)
ans*=inv(n)
ans%=mod
ans*=inv(n)
ans%=mod
print(mod-ans + 1)
``` | instruction | 0 | 30,208 | 14 | 60,416 |
No | output | 1 | 30,208 | 14 | 60,417 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | instruction | 0 | 30,209 | 14 | 60,418 |
Tags: brute force, dfs and similar, graphs, implementation
Correct Solution:
```
def calculate(n, arr):
g = {}
for num1,num2 in arr:
if num1 not in g:
g[num1] = set()
g[num1].add(num2)
if num2 not in g:
g[num2] = set()
g[num2].add(num1)
data = []
for num in g:
if len(g[num]) == 1:
data.append(num)
count = 0
while data:
for src in data:
if len(g[src]):
dst = g[src].pop()
g[dst].remove(src)
g.pop(src)
data = []
for num in g:
if len(g[num]) == 1:
data.append(num)
count += 1
print(count)
s = input()
n,m = list(map(int, s.strip().split(" ")))
arr = []
for i in range(m):
s = input()
num1,num2 = list(map(int, s.strip().split(" ")))
arr.append([num1,num2])
calculate(n, arr)
``` | output | 1 | 30,209 | 14 | 60,419 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | instruction | 0 | 30,210 | 14 | 60,420 |
Tags: brute force, dfs and similar, graphs, implementation
Correct Solution:
```
n, m = (int(_) for _ in input().split())
sp = [[] for _ in range(n)]
for i in range(m):
a, b = (int(_)-1 for _ in input().split())
sp[a].append(b)
sp[b].append(a)
ans = 0
while 1:
vyg = []
for i in range(n):
if len(sp[i]) == 1: vyg.append(i)
if vyg:
for x in vyg:
if sp[x]:
sosed = sp[x][0]
sp[sosed].remove(x)
sp[x] = []
ans += 1
else: break
print(ans)
``` | output | 1 | 30,210 | 14 | 60,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | instruction | 0 | 30,211 | 14 | 60,422 |
Tags: brute force, dfs and similar, graphs, implementation
Correct Solution:
```
n,m = map(int,input().split())
hash = {}
hashi = {}
for i in range(1,n+1):
hashi[i] = []
for i in range(m):
a,b = map(int,input().split())
try:
hash[a]
except:
hash[a] = 1
else:
hash[a]+=1
try:
hash[b]
except:
hash[b] = 1
else:
hash[b]+=1
hashi[a].append(b)
hashi[b].append(a)
count = 0
for i in range(n):
flag = 0
l = []
for j in hash.keys():
if hash[j] == 1:
hash[j]-=1
l.append(j)
flag = 1
if flag == 0:
break
else:
for m in l:
for k in hashi[m]:
hash[k]-=1
count+=1
print(count)
``` | output | 1 | 30,211 | 14 | 60,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | instruction | 0 | 30,212 | 14 | 60,424 |
Tags: brute force, dfs and similar, graphs, implementation
Correct Solution:
```
n, m = [int(x) for x in input().split()]
adj = []
for i in range(101):
adj.append(set())
nodes = set()
for i in range(m):
u, v = [int(x) for x in input().split()]
adj[u].add(v)
adj[v].add(u)
nodes.add(u)
nodes.add(v)
sum = 0
go = True
while go == True:
go = False
mark = set()
for node in nodes:
if len(adj[node]) == 1 and not node in mark:
go = True
x = node
y = 0
for num in adj[node]:
y = num
mark.add(y)
adj[x].remove(y)
adj[y].remove(x)
if go == True:
sum += 1
print(sum)
``` | output | 1 | 30,212 | 14 | 60,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | instruction | 0 | 30,213 | 14 | 60,426 |
Tags: brute force, dfs and similar, graphs, implementation
Correct Solution:
```
n, m=map(int, input().split(' '))
adj=[[0]*n for i in range(n)]
for i in range(m):
x, y=map(int, input().split(' '))
adj[x-1][y-1]+=1
adj[y-1][x-1]+=1
groups=0
while(1 in [sum(x) for x in adj]):
#print(adj)
kk=[]
for x in range(len(adj)):
if(sum(adj[x])==1):
kk.append([x,adj[x].index(1)])
for c in kk:
adj[c[0]][c[1]], adj[c[1]][c[0]]=0,0
groups+=1
print(groups)
``` | output | 1 | 30,213 | 14 | 60,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | instruction | 0 | 30,214 | 14 | 60,428 |
Tags: brute force, dfs and similar, graphs, implementation
Correct Solution:
```
n,m=map(int,input().split())
g=[set() for i in range(n)]
for _ in range(m):
a,b=map(int,input().split())
g[a-1].add(b-1)
g[b-1].add(a-1)
cnt=0
while True:
p=set()
for i in range(n):
if len(g[i])==1:
p.add(i)
g[i]=set()
if len(p)==0:
break
cnt+=1
for i in range(n):
g[i]-=p
print(cnt)
``` | output | 1 | 30,214 | 14 | 60,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | instruction | 0 | 30,215 | 14 | 60,430 |
Tags: brute force, dfs and similar, graphs, implementation
Correct Solution:
```
W = 0
G = 1
n, m = map(int, input().split())
E = []
for i in range(m):
E.append(list(map(int, input().split())))
group = []
color = [-1]
deleted = [True] + [False for i in range(n)]
def get_nbs(v):
nbs = []
for e in E:
if e[0] == v:
nbs.append(e[1])
if e[1] == v:
nbs.append(e[0])
return nbs
def dfs(v):
color[v] = G
nbs = get_nbs(v)
if len(nbs) == 1:
group.append((v, nbs[0]))
deleted[v] = True
for u in nbs:
if color[u] == W:
dfs(u)
g_count = 0
while True:
group = []
color = [-1] + [0 for i in range(n)]
# print(E)
for v in range(1, n + 1):
if not deleted[v] and color[v] == W:
dfs(v)
# print(deleted)
#
# print(group)
if len(group) == 0:
break
else:
g_count += 1
for e in group:
if [e[0], e[1]] in E:
E.remove([e[0], e[1]])
elif [e[1], e[0]] in E:
E.remove([e[1], e[0]])
print(g_count)
``` | output | 1 | 30,215 | 14 | 60,431 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one. | instruction | 0 | 30,216 | 14 | 60,432 |
Tags: brute force, dfs and similar, graphs, implementation
Correct Solution:
```
n,k=map(int,input().split())
a=[set() for i in range(0,n+1)]
for i in range(k):
x,y=map(int,input().split())
a[x].add(y)
a[y].add(x)
ans=0
while True:
outman=set()
for i in range(1,n+1):
if len(a[i])==1:
a[i]=set()
outman.add(i)
if len(outman)==0: break
ans+=1
for i in range(1,n+1): a[i]-=outman
print(ans)
``` | output | 1 | 30,216 | 14 | 60,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Submitted Solution:
```
import sys
from collections import deque
# from collections import Counter
# from math import sqrt
# from math import log
# from math import ceil
# from bisect import bisect_left, bisect_right
#alpha=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# mod=10**9+7
# mod=998244353
# def BinarySearch(a,x):
# i=bisect_left(a,x)
# if(i!=len(a) and a[i]==x):
# return i
# else:
# return -1
# def sieve(n):
# prime=[True for i in range(n+1)]
# p=2
# while(p*p<=n):
# if (prime[p]==True):
# for i in range(p*p,n+1,p):
# prime[i]=False
# p+=1
# prime[0]=False
# prime[1]=False
# s=set()
# for i in range(len(prime)):
# if(prime[i]):
# s.add(i)
# return s
# def gcd(a, b):
# if(a==0):
# return b
# return gcd(b%a,a)
fast_reader=sys.stdin.readline
fast_writer=sys.stdout.write
def input():
return fast_reader().strip()
def print(*argv):
fast_writer(' '.join((str(i)) for i in argv))
fast_writer('\n')
#____________________________________________________________________________________________________________________________________
n,m=map(int, input().split())
d={}
e=[]
for i in range(1,n+1):
d[i]=0
for i in range(m):
a,b=map(int, input().split())
d[a]+=1
d[b]+=1
e.append((a,b))
visited=set()
ans=0
while(True):
# print(d)
# print(e)
f=False
temp=[]
for i in range(m):
a,b=e[i]
if((d[a]==1 or d[b]==1) and (a,b) not in visited):
visited.add((a,b))
temp.append((a,b))
f=True
for i in temp:
a,b=i
d[a]-=1
d[b]-=1
if(not f):
break
else:
ans+=1
print(ans)
``` | instruction | 0 | 30,217 | 14 | 60,434 |
Yes | output | 1 | 30,217 | 14 | 60,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Submitted Solution:
```
n, m = [int(k) for k in input().split()]
dict = {}
for i in range(m):
first, second = [int(k) for k in input().split()]
if first not in dict:
dict[first] = set()
dict[first].add(second)
else: dict[first].add(second)
if second not in dict:
dict[second] = set()
dict[second].add(first)
else: dict[second].add(first)
count = 0
while True:
temp = set()
for key in list(dict):
if len(dict[key]) == 1:
temp.add(key)
dict.pop(key)
if not temp:
break
count += 1
for key in dict:
dict[key] -= temp
print(count)
``` | instruction | 0 | 30,218 | 14 | 60,436 |
Yes | output | 1 | 30,218 | 14 | 60,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Submitted Solution:
```
'''input
6 5
1 4
2 4
3 4
5 4
6 4
'''
n,m = map(int,input().split())
l = [[] for i in range(n)]
for i in range(m):
a,b = map(int,input().split())
a-=1
b-=1
l[a].append(b)
l[b].append(a)
count = 0
while True:
pops = []
for i in range(n):
if len(l[i])==1:
pops.append([i,l[i][0]])
if len(pops):
for a,b in pops:
if a in l[b]: l[b].remove(a)
if b in l[a]: l[a].remove(b)
count+=1
else:
break
print(count)
``` | instruction | 0 | 30,219 | 14 | 60,438 |
Yes | output | 1 | 30,219 | 14 | 60,439 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Submitted Solution:
```
import os,io
from sys import stdout
import collections
# import random
# import math
# from operator import itemgetter
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# from collections import Counter
# from decimal import Decimal
# import heapq
# from functools import lru_cache
# import sys
# import threading
# sys.setrecursionlimit(10**6)
# threading.stack_size(102400000)
# from functools import lru_cache
# @lru_cache(maxsize=None)
######################
# --- Maths Fns --- #
######################
def primes(n):
sieve = [True] * n
for i in range(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
return [2] + [i for i in range(3,n,2) if sieve[i]]
def binomial_coefficient(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def powerOfK(k, max):
if k == 1:
return [1]
if k == -1:
return [-1, 1]
result = []
n = 1
while n <= max:
result.append(n)
n *= k
return result
def divisors(n):
i = 1
result = []
while i*i <= n:
if n%i == 0:
if n/i == i:
result.append(i)
else:
result.append(i)
result.append(n/i)
i+=1
return result
# @lru_cache(maxsize=None)
def digitsSum(n):
if n == 0:
return 0
r = 0
while n > 0:
r += n % 10
n //= 10
return r
######################
# ---- GRID Fns ---- #
######################
def isValid(i, j, n, m):
return i >= 0 and i < n and j >= 0 and j < m
def print_grid(grid):
for line in grid:
print(" ".join(map(str,line)))
######################
# ---- MISC Fns ---- #
######################
def kadane(a,size):
max_so_far = 0
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
def prefixSum(arr):
for i in range(1, len(arr)):
arr[i] = arr[i] + arr[i-1]
return arr
def ceil(n, d):
if n % d == 0:
return n // d
else:
return (n // d) + 1
# INPUTS --------------------------
# s = input().decode('utf-8').strip()
# n = int(input())
# l = list(map(int, input().split()))
# t = int(input())
# for _ in range(t):
# for _ in range(t):
n, k = list(map(int, input().split()))
adj = collections.defaultdict(set)
for _ in range(k):
u, v = list(map(int, input().split()))
adj[u].add(v)
adj[v].add(u)
r = 0
while True:
toremove = []
for u,v in adj.items():
if len(v) == 1:
peer = list(v)[0]
toremove.append((peer, u))
if len(toremove):
r += 1
for u, v in toremove:
if u in adj and v in adj[u]:
adj[u].remove(v)
if v in adj and u in adj[v]:
adj[v].remove(u)
if not len(adj[u]):
del adj[u]
if not len(adj[v]):
del adj[v]
else:
break
print(r)
``` | instruction | 0 | 30,220 | 14 | 60,440 |
Yes | output | 1 | 30,220 | 14 | 60,441 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Submitted Solution:
```
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
``` | instruction | 0 | 30,221 | 14 | 60,442 |
No | output | 1 | 30,221 | 14 | 60,443 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Submitted Solution:
```
n,m=map(int,input().split())
a=[[0 for x in range(n)] for y in range(n) ]
for i in range(m):
i,j=map(int,input().split())
a[i-1][j-1]=a[j-1][i-1]=1
c=0
amt=0
for _ in range(n):
for i in range(n):
if (a[i].count(1)==1):
c+=1
for j in range(n):
a[i][j]=0
for i in a:
if (i.count(1)!=0):
amt+=1
print (amt)
``` | instruction | 0 | 30,222 | 14 | 60,444 |
No | output | 1 | 30,222 | 14 | 60,445 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Submitted Solution:
```
n, m = list(map(int, input().split()))
memo = {}
for i in range(m):
a, b = list(map(int, input().split()))
try:
memo[a].append(b)
except KeyError:
memo[a] = [b, ]
try:
memo[b].append(a)
except KeyError:
memo[b] = [a, ]
# print(memo)
def delete(point):
global temp
# print()
# print(f"delete called with point = {point}")
# print(f"BEFORE: memo = {memo}")
ties = memo[point]
del memo[point]
for tie in ties:
try:
delete(tie)
except KeyError:
if len(ties) == 2:
temp += 1
continue
# print(f"AFTER: memo = {memo}")
temp = 2
counter = 0
def perform():
global counter, temp
try:
for key, value in memo.items():
if len(value) == 1:
# print(f"key = {key}, value = {value}")
delete(key)
counter += (temp+1) // 2
temp = 2
# print(memo)
except RuntimeError:
perform()
perform()
print(counter)
# print(f"counter = {counter}, temp = {temp}")
``` | instruction | 0 | 30,223 | 14 | 60,446 |
No | output | 1 | 30,223 | 14 | 60,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Submitted Solution:
```
n, m = map(int, input().split())
mas1 = []
for i in range(n):
mas1.append(0)
mas2 = []
for i in range(m):
x, y = map(int, input().split())
mas2.append([x, y])
mas2.append([y, x])
for i in range(0, m * 2, 2):
mas1[mas2[i][0] - 1] += 1
mas1[mas2[i][1] - 1] += 1
kol = 0
flag = True
while flag:
otn = []
flag = False
for i1 in range(n):
if mas1[i1] == 1:
otn.append(i1)
flag = True
for i2 in range(m * 2):
if i1 + 1 == mas2[i2][0]:
otn.append(mas2[i2][1] - 1)
break
for i in otn:
mas1[i] -= 1
if flag:
kol += 1
print (kol)
``` | instruction | 0 | 30,224 | 14 | 60,448 |
No | output | 1 | 30,224 | 14 | 60,449 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).
You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).
You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Input
The first line of input will contain two integers n, m (3 β€ n β€ 100 000, 0 β€ m β€ 100 000).
The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 β€ ai, bi β€ n, ai β bi, <image>).
Each pair of people will be described no more than once.
Output
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
Examples
Input
3 0
Output
4
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0
Output
1
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1
Output
0
Note
In the first sample, the four ways are to:
* Make everyone love each other
* Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).
In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other. | instruction | 0 | 30,485 | 14 | 60,970 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin, stdout
import sys
class Node(object):
def __init__(self, label):
self.label = label
self.par = self
self.rank = 0
class DisjointSet(object):
def __init__(self, n):
self.n = n
self.nodes = [Node(i) for i in range(self.n)]
def find(self, u):
if u == u.par:
return u
return self.find(u.par)
def union(self, u, v):
u, v = self.find(u), self.find(v)
if u == v:
return False
if u.rank > v.rank:
u, v = v, u
u.par = v
if u.rank == v.rank:
v.rank += 1
return True
def size(self):
cnt = 0
for node in self.nodes:
if node.par == node:
cnt += 1
return cnt
def color(adj, colors, root):
neighbor_color = 1 - colors[root]
for neighbor in adj[root]:
if colors[neighbor] == -1:
colors[neighbor] = neighbor_color
if color(adj, colors, neighbor):
pass
else:
return False
else:
if colors[neighbor] != neighbor_color:
return False
return True
if __name__ == "__main__":
try:
sys.setrecursionlimit(10000)
mod = 1000000007
n, m = map(int, input().split())
dsu = DisjointSet(n)
reds = []
for _ in range(m):
a, b, c = map(int, input().split())
if c == 0:
reds.append((a - 1, b - 1))
else:
dsu.union(dsu.nodes[a - 1], dsu.nodes[b - 1])
new_graph = {}
cnt = 0
for i in range(n):
comp = dsu.find(dsu.nodes[i])
if comp.label not in new_graph.keys():
new_graph[comp.label] = cnt
cnt += 1
x = len(new_graph)
assert cnt == x
dsu2 = DisjointSet(x)
adj = [[] for _ in range(x)]
colors = [-1 for _ in range(x)]
for a, b in reds:
comp1 = dsu.find(dsu.nodes[a]).label
comp2 = dsu.find(dsu.nodes[b]).label
if comp1 == comp2:
print(0)
exit(0)
else:
index1 = new_graph[comp1]
index2 = new_graph[comp2]
if index1 >= x or index2 >= x:
print(-1)
exit(0)
dsu2.union(dsu2.nodes[index1], dsu2.nodes[index2])
adj[index1].append(index2)
adj[index2].append(index1)
for i in range(x):
if colors[i] == -1:
colors[i] = 0
ans = color(adj, colors, i)
if ans:
pass
else:
print(0)
exit(0)
comps = dsu2.size()
ans = 1
for _ in range(comps - 1):
ans *= 2
ans %= mod
print(ans)
exit(0)
except Exception as e:
print(e)
print(-1)
exit(0)
``` | output | 1 | 30,485 | 14 | 60,971 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).
You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).
You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Input
The first line of input will contain two integers n, m (3 β€ n β€ 100 000, 0 β€ m β€ 100 000).
The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 β€ ai, bi β€ n, ai β bi, <image>).
Each pair of people will be described no more than once.
Output
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
Examples
Input
3 0
Output
4
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0
Output
1
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1
Output
0
Note
In the first sample, the four ways are to:
* Make everyone love each other
* Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).
In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other. | instruction | 0 | 30,486 | 14 | 60,972 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
class DSU(object):
def __init__(self, n):
self.father = list(range(n))
self.size = n
def union(self, x, s):
x = self.find(x)
s = self.find(s)
if x == s:
return
self.father[s] = x
self.size -= 1
def find(self, x):
xf = self.father[x]
if xf != x:
self.father[x] = self.find(xf)
return self.father[x]
def is_invalid(a, b, ds):
return ds.find(a) == ds.find(b)
n, k = map(int, input().split())
ds = DSU(n * 2)
for i in range(k):
first, second, color = map(int, input().split())
first -= 1
second -= 1
if color == 0:
if is_invalid(first, second, ds):
print(0)
exit()
ds.union(first, second + n)
ds.union(first + n, second)
else:
if is_invalid(first, second + n, ds):
print(0)
exit()
ds.union(first, second)
ds.union(first + n, second + n)
sum = 1
for i in range(ds.size // 2 - 1):
sum = (sum * 2) % (10 ** 9 + 7)
print(sum)
``` | output | 1 | 30,486 | 14 | 60,973 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).
You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).
You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Input
The first line of input will contain two integers n, m (3 β€ n β€ 100 000, 0 β€ m β€ 100 000).
The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 β€ ai, bi β€ n, ai β bi, <image>).
Each pair of people will be described no more than once.
Output
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
Examples
Input
3 0
Output
4
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0
Output
1
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1
Output
0
Note
In the first sample, the four ways are to:
* Make everyone love each other
* Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).
In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other. | instruction | 0 | 30,487 | 14 | 60,974 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
class DisjointSet(object):
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
self.num = n # number of disjoint sets
def union(self, x, y):
self._link(self.find_set(x), self.find_set(y))
def _link(self, x, y):
if x == y:
return
self.num -= 1
if self.rank[x] > self.rank[y]:
self.parent[y] = x
else:
self.parent[x] = y
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
def find_set(self, x):
xp = self.parent[x]
if xp != x:
self.parent[x] = self.find_set(xp)
return self.parent[x]
def solve():
n, m = map(int, input().split())
ds = DisjointSet(n * 2)
for i in range(m):
a, b, c = map(int, input().split())
a -= 1
b -= 1
aA = a * 2
aB = aA + 1
bA = b * 2
bB = bA + 1
if c == 0:
if ds.find_set(aA) == ds.find_set(bA):
return 0
ds.union(aA, bB)
ds.union(aB, bA)
else:
if ds.find_set(aA) == ds.find_set(bB):
return 0
ds.union(aA, bA)
ds.union(aB, bB)
return pow(2, (ds.num // 2) - 1, 10**9 + 7)
print(solve())
``` | output | 1 | 30,487 | 14 | 60,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).
You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).
You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Input
The first line of input will contain two integers n, m (3 β€ n β€ 100 000, 0 β€ m β€ 100 000).
The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 β€ ai, bi β€ n, ai β bi, <image>).
Each pair of people will be described no more than once.
Output
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
Examples
Input
3 0
Output
4
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0
Output
1
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1
Output
0
Note
In the first sample, the four ways are to:
* Make everyone love each other
* Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).
In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
Submitted Solution:
```
from sys import stdin, stdout
import sys
class Node(object):
def __init__(self, label):
self.label = label
self.par = self
self.rank = 0
class DisjointSet(object):
def __init__(self, n):
self.n = n
self.nodes = [Node(i) for i in range(self.n)]
def find(self, u):
if u == u.par:
return u
return self.find(u.par)
def union(self, u, v):
u, v = self.find(u), self.find(v)
if u == v:
return False
if u.rank > v.rank:
u, v = v, u
u.par = v
if u.rank == v.rank:
v.rank += 1
return True
def size(self):
cnt = 0
for node in self.nodes:
if node.par == node:
cnt += 1
return cnt
def color(adj, colors, root):
neighbor_color = 1 - colors[root]
for neighbor in adj[root]:
if colors[neighbor] == -1:
colors[neighbor] = neighbor_color
if color(adj, colors, neighbor):
pass
else:
return False
else:
if colors[neighbor] != neighbor_color:
return False
return True
if __name__ == "__main__":
try:
print(sys.setrecursionlimit(10000))
mod = 1000000007
n, m = map(int, input().split())
dsu = DisjointSet(n)
reds = []
for _ in range(m):
a, b, c = map(int, input().split())
if c == 0:
reds.append((a - 1, b - 1))
else:
dsu.union(dsu.nodes[a - 1], dsu.nodes[b - 1])
new_graph = {}
cnt = 0
for i in range(n):
comp = dsu.find(dsu.nodes[i])
if comp.label not in new_graph.keys():
new_graph[comp.label] = cnt
cnt += 1
x = len(new_graph)
assert cnt == x
dsu2 = DisjointSet(x)
adj = [[] for _ in range(x)]
colors = [-1 for _ in range(x)]
for a, b in reds:
comp1 = dsu.find(dsu.nodes[a]).label
comp2 = dsu.find(dsu.nodes[b]).label
if comp1 == comp2:
print(0)
exit(0)
else:
index1 = new_graph[comp1]
index2 = new_graph[comp2]
if index1 >= x or index2 >= x:
print(-1)
exit(0)
dsu2.union(dsu2.nodes[index1], dsu2.nodes[index2])
adj[index1].append(index2)
adj[index2].append(index1)
for i in range(x):
if colors[i] == -1:
colors[i] = 0
ans = color(adj, colors, i)
if ans:
pass
else:
print(0)
exit(0)
comps = dsu2.size()
ans = 1
for _ in range(comps - 1):
ans *= 2
ans %= mod
print(ans)
exit(0)
except Exception as e:
print(e)
print(-1)
exit(0)
``` | instruction | 0 | 30,488 | 14 | 60,976 |
No | output | 1 | 30,488 | 14 | 60,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).
You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).
You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Input
The first line of input will contain two integers n, m (3 β€ n β€ 100 000, 0 β€ m β€ 100 000).
The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 β€ ai, bi β€ n, ai β bi, <image>).
Each pair of people will be described no more than once.
Output
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
Examples
Input
3 0
Output
4
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0
Output
1
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1
Output
0
Note
In the first sample, the four ways are to:
* Make everyone love each other
* Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).
In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
Submitted Solution:
```
from sys import stdin, stdout
class Node(object):
def __init__(self, label):
self.label = label
self.par = self
self.rank = 0
class DisjointSet(object):
def __init__(self, n):
self.n = n
self.nodes = [Node(i) for i in range(self.n)]
def find(self, u):
if u == u.par:
return u
return self.find(u.par)
def union(self, u, v):
u, v = self.find(u), self.find(v)
if u == v:
return False
if u.rank > v.rank:
u, v = v, u
u.par = v
if u.rank == v.rank:
v.rank += 1
return True
def size(self):
cnt = 0
for node in self.nodes:
if node.par == node:
cnt += 1
return cnt
def color(adj, colors, root):
neighbor_color = 1 - colors[root]
for neighbor in adj[root]:
if colors[neighbor] == -1:
colors[neighbor] = neighbor_color
if color(adj, colors, neighbor):
pass
else:
return False
else:
if colors[neighbor] != neighbor_color:
return False
return True
if __name__ == "__main__":
try:
mod = 1000000007
n, m = map(int, input().split())
dsu = DisjointSet(n)
reds = []
for _ in range(m):
a, b, c = map(int, input().split())
if c == 0:
reds.append((a - 1, b - 1))
else:
dsu.union(dsu.nodes[a - 1], dsu.nodes[b - 1])
new_graph = {}
for i in range(n):
comp = dsu.find(dsu.nodes[i])
if comp.label not in new_graph.keys():
new_graph[comp.label] = len(new_graph)
x = len(new_graph)
dsu2 = DisjointSet(x)
adj = [[] for _ in range(x)]
colors = [-1 for _ in range(x)]
for a, b in reds:
comp1 = dsu.find(dsu.nodes[a]).label
comp2 = dsu.find(dsu.nodes[b]).label
if comp1 == comp2:
print(0)
exit(0)
else:
index1 = new_graph[comp1]
index2 = new_graph[comp2]
if index1 >= x or index2 >= x:
print(-1)
exit(0)
dsu2.union(dsu2.nodes[index1], dsu2.nodes[index2])
adj[index1].append(index2)
adj[index2].append(index1)
for i in range(x):
if colors[i] == -1:
colors[i] = 0
if color(adj, colors, i):
pass
else:
print(0)
exit(0)
comps = dsu2.size()
ans = 1
for _ in range(comps - 1):
ans *= 2
ans %= mod
print(ans)
exit(0)
except Exception:
print(-1)
exit(0)
``` | instruction | 0 | 30,489 | 14 | 60,978 |
No | output | 1 | 30,489 | 14 | 60,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).
You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).
You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Input
The first line of input will contain two integers n, m (3 β€ n β€ 100 000, 0 β€ m β€ 100 000).
The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 β€ ai, bi β€ n, ai β bi, <image>).
Each pair of people will be described no more than once.
Output
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
Examples
Input
3 0
Output
4
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0
Output
1
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1
Output
0
Note
In the first sample, the four ways are to:
* Make everyone love each other
* Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).
In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
Submitted Solution:
```
class Node(object):
def __init__(self, label):
self.label = label
self.par = self
self.rank = 0
class DisjointSet(object):
def __init__(self, n):
self.n = n
self.nodes = [Node(i) for i in range(n)]
def find(self, u):
if u == u.par:
return u
return self.find(u.par)
def union(self, u, v):
u, v = self.find(u), self.find(v)
if u == v:
return False
if u.rank > v.rank:
u, v = v, u
u.par = v
if u.rank == v.rank:
v.rank += 1
return True
def size(self):
cnt = 0
for node in self.nodes:
if node.par == node:
cnt += 1
return cnt
def color(adj, colors, root):
neighbor_color = 1 - colors[root]
for neighbor in adj[root]:
if colors[neighbor] == -1:
colors[neighbor] = neighbor_color
answer = color(adj, colors, neighbor)
if not answer:
return False
else:
if colors[neighbor] != neighbor_color:
return False
return True
if __name__ == "__main__":
mod = 1000000007
n, m = map(int, input().split(" "))
dsu = DisjointSet(n)
reds = []
for _ in range(m):
a, b, c = map(int, input().split(" "))
if c == 0:
reds.append((a - 1, b - 1))
else:
dsu.union(dsu.nodes[a - 1], dsu.nodes[b - 1])
new_graph = {}
for i in range(n):
comp = dsu.find(dsu.nodes[i])
if comp not in new_graph.keys():
new_graph[comp] = len(new_graph)
x = len(new_graph)
dsu2 = DisjointSet(x)
adj = [[] for _ in range(x)]
colors = [-1 for _ in range(x)]
for a, b in reds:
comp1 = dsu.find(dsu.nodes[a])
comp2 = dsu.find(dsu.nodes[b])
if comp1 == comp2:
print(0)
exit(0)
else:
index1 = new_graph[comp1]
index2 = new_graph[comp2]
if index1 >= x or index2 >= 0:
print(-1)
exit(0)
dsu2.union(dsu2.nodes[index1], dsu2.nodes[index2])
adj[index1].append(index2)
adj[index2].append(index1)
for i in range(x):
if colors[i] == -1:
answer = color(adj, colors, i)
if not answer:
print(0)
exit(0)
comps = dsu2.size()
ans = 1
for _ in range(comps - 1):
ans *= 2
ans %= mod
print(ans)
``` | instruction | 0 | 30,490 | 14 | 60,980 |
No | output | 1 | 30,490 | 14 | 60,981 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).
You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).
You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.
Input
The first line of input will contain two integers n, m (3 β€ n β€ 100 000, 0 β€ m β€ 100 000).
The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 β€ ai, bi β€ n, ai β bi, <image>).
Each pair of people will be described no more than once.
Output
Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.
Examples
Input
3 0
Output
4
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 0
Output
1
Input
4 4
1 2 1
2 3 1
3 4 0
4 1 1
Output
0
Note
In the first sample, the four ways are to:
* Make everyone love each other
* Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this).
In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
Submitted Solution:
```
from sys import stdin, stdout
class Node(object):
def __init__(self, label):
self.label = label
self.par = self
self.rank = 0
class DisjointSet(object):
def __init__(self, n):
self.n = n
self.nodes = [Node(i) for i in range(self.n)]
def find(self, u):
if u == u.par:
return u
return self.find(u.par)
def union(self, u, v):
u, v = self.find(u), self.find(v)
if u == v:
return False
if u.rank > v.rank:
u, v = v, u
u.par = v
if u.rank == v.rank:
v.rank += 1
return True
def size(self):
cnt = 0
for node in self.nodes:
if node.par == node:
cnt += 1
return cnt
def color(adj, colors, root):
neighbor_color = 1 - colors[root]
for neighbor in adj[root]:
if colors[neighbor] == -1:
colors[neighbor] = neighbor_color
if color(adj, colors, neighbor):
pass
else:
return False
else:
if colors[neighbor] != neighbor_color:
return False
return True
if __name__ == "__main__":
try:
mod = 1000000007
n, m = map(int, input().split())
dsu = DisjointSet(n)
reds = []
for _ in range(m):
a, b, c = map(int, input().split())
if c == 0:
reds.append((a - 1, b - 1))
else:
dsu.union(dsu.nodes[a - 1], dsu.nodes[b - 1])
new_graph = {}
cnt = 0
for i in range(n):
comp = dsu.find(dsu.nodes[i])
if comp.label not in new_graph.keys():
new_graph[comp.label] = cnt
cnt += 1
x = len(new_graph)
assert cnt == x
dsu2 = DisjointSet(x)
adj = [[] for _ in range(x)]
colors = [-1 for _ in range(x)]
for a, b in reds:
comp1 = dsu.find(dsu.nodes[a]).label
comp2 = dsu.find(dsu.nodes[b]).label
if comp1 == comp2:
print(0)
exit(0)
else:
index1 = new_graph[comp1]
index2 = new_graph[comp2]
if index1 >= x or index2 >= x:
print(-1)
exit(0)
dsu2.union(dsu2.nodes[index1], dsu2.nodes[index2])
adj[index1].append(index2)
adj[index2].append(index1)
for i in range(x):
if colors[i] == -1:
colors[i] = 0
ans = color(adj, colors, i)
if ans:
pass
else:
print(0)
exit(0)
comps = dsu2.size()
ans = 1
for _ in range(comps - 1):
ans *= 2
ans %= mod
print(ans)
exit(0)
except Exception:
print(-1)
exit(0)
``` | instruction | 0 | 30,491 | 14 | 60,982 |
No | output | 1 | 30,491 | 14 | 60,983 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.
There are three values about each exam:
* s_i β the day, when questions for the i-th exam will be published,
* d_i β the day of the i-th exam (s_i < d_i),
* c_i β number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i β€ j < d_i.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ n) β the number of days and the number of exams.
Each of the following m lines contains three integers s_i, d_i, c_i (1 β€ s_i < d_i β€ n, 1 β€ c_i β€ n) β the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is:
* (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted),
* zero, if in the j-th day Petya will have a rest,
* i (1 β€ i β€ m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).
Assume that the exams are numbered in order of appearing in the input, starting from 1.
If there are multiple schedules, print any of them.
Examples
Input
5 2
1 3 1
1 5 1
Output
1 2 3 0 3
Input
3 2
1 3 1
1 2 1
Output
-1
Input
10 3
4 7 2
1 10 3
8 9 1
Output
2 2 2 1 1 0 4 3 4 4
Note
In the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | instruction | 0 | 30,671 | 14 | 61,342 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n, m = map(int, input().split())
prep = []
days = [-1] * n
release = []
for i in range(m):
s_, d_, c_ = map(int, input().split())
release.append(s_)
days[d_ - 1] = i
prep.append(c_)
rel_on_day = {}
for i, r in enumerate(release):
if r - 1 in rel_on_day:
rel_on_day[r - 1].append(i)
else:
rel_on_day[r - 1] = [i]
ans = []
waiting = set()
exam_q = []
for d in days:
if d != -1:
exam_q.append(d)
#print(rel_on_day)
for i in range(n):
if i in rel_on_day:
waiting = waiting | set(rel_on_day[i])
# print(waiting)
if days[i] != -1: #exam
if prep[days[i]] == 0:
ans.append(m + 1)
waiting.remove(days[i])
else:
print(-1)
exit(0)
else: #choose closest unstudied exam
chosen = None
for ex in exam_q:
if prep[ex] > 0 and ex in waiting:
chosen = ex
break
if not chosen is None:
prep[ex] -= 1
ans.append(ex + 1)
else:
ans.append(0)
print(" ".join(list(map(str, ans))))
``` | output | 1 | 30,671 | 14 | 61,343 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.
There are three values about each exam:
* s_i β the day, when questions for the i-th exam will be published,
* d_i β the day of the i-th exam (s_i < d_i),
* c_i β number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i β€ j < d_i.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ n) β the number of days and the number of exams.
Each of the following m lines contains three integers s_i, d_i, c_i (1 β€ s_i < d_i β€ n, 1 β€ c_i β€ n) β the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is:
* (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted),
* zero, if in the j-th day Petya will have a rest,
* i (1 β€ i β€ m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).
Assume that the exams are numbered in order of appearing in the input, starting from 1.
If there are multiple schedules, print any of them.
Examples
Input
5 2
1 3 1
1 5 1
Output
1 2 3 0 3
Input
3 2
1 3 1
1 2 1
Output
-1
Input
10 3
4 7 2
1 10 3
8 9 1
Output
2 2 2 1 1 0 4 3 4 4
Note
In the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | instruction | 0 | 30,672 | 14 | 61,344 |
Tags: greedy, implementation, sortings
Correct Solution:
```
from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *
####################################---fast-input-output----#########################################
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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
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:
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")
stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)
def fast(): return stdin.readline().strip()
def zzz(): return [int(i) for i in fast().split()]
z, zz = fast, lambda: list(map(int, z().split()))
szz, graph, mod, szzz = lambda: sorted(
zz()), {}, 10**9 + 7, lambda: sorted(zzz())
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
def output(answer, end='\n'): stdout.write(str(answer) + end)
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
#################################################---Some Rule For Me To Follow---#################################
"""
--instants of Reading problem continuously try to understand them.
--If you Know some-one , Then you probably don't know him !
--Try & again try
"""
##################################################---START-CODING---###############################################
def solve():
n, m = zzz()
deed = [0]*n
exams = []
for i in range(m):
s, d, c = zzz()
s -= 1; d -= 1
if deed[d]: return [-1]
deed[d] = m + 1
exams.append((d, s, c, i + 1))
exams = sorted(exams)
# print(exams,deed)
for d, s, c, idx in exams:
for i in range(s, d):
if deed[i] == 0:
deed[i] = idx
c -= 1
if c == 0: break
if c:
return [-1]
return deed
print(*solve())
``` | output | 1 | 30,672 | 14 | 61,345 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.
There are three values about each exam:
* s_i β the day, when questions for the i-th exam will be published,
* d_i β the day of the i-th exam (s_i < d_i),
* c_i β number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i β€ j < d_i.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ n) β the number of days and the number of exams.
Each of the following m lines contains three integers s_i, d_i, c_i (1 β€ s_i < d_i β€ n, 1 β€ c_i β€ n) β the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is:
* (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted),
* zero, if in the j-th day Petya will have a rest,
* i (1 β€ i β€ m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).
Assume that the exams are numbered in order of appearing in the input, starting from 1.
If there are multiple schedules, print any of them.
Examples
Input
5 2
1 3 1
1 5 1
Output
1 2 3 0 3
Input
3 2
1 3 1
1 2 1
Output
-1
Input
10 3
4 7 2
1 10 3
8 9 1
Output
2 2 2 1 1 0 4 3 4 4
Note
In the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | instruction | 0 | 30,673 | 14 | 61,346 |
Tags: greedy, implementation, sortings
Correct Solution:
```
import sys,math
from collections import deque,defaultdict
import operator as op
from functools import reduce
from itertools import permutations
import heapq
#sys.setrecursionlimit(10**6)
#OneDrive\Documents\codeforces
I=sys.stdin.readline
alpha="abcdefghijklmnopqrstuvwxyz"
"""
x_move=[-1,0,1,0,-1,1,1,-1]
y_move=[0,1,0,-1,1,1,-1,-1]
"""
def ii():
return int(I().strip())
def li():
return list(map(int,I().strip().split()))
def mi():
return map(int,I().strip().split())
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom
def gcd(x, y):
while y:
x, y = y, x % y
return x
def isPrime(n):
if n<=1:
return False
elif n<=2:
return True
else:
for i in range(2,int(n**.5)+1):
if n%i==0:
return False
return True
#print("Case #"+str(_+1)+":",abs(cnt-k))
def main():
n,m=mi()
exams=[]
ans=[0]*n
for i in range(m):
tmp=li()
tmp+=[i+1]
ans[tmp[1]-1]=m+1
exams.append(tmp)
exams=sorted(exams,key=lambda x:x[1])
flag=0
for i in exams:
data=i
if data[1]-data[0]<data[2]:
flag=1
break
need=data[2]
# print(data)
for j in range(data[0],data[1]):
# print(ans)
if ans[j-1]==0 and need>0:
ans[j-1]=data[3]
need-=1
if need!=0:
flag=1
if flag:
print(-1)
else:
print(*ans)
# print(exams)
if __name__ == '__main__':
main()
``` | output | 1 | 30,673 | 14 | 61,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.
There are three values about each exam:
* s_i β the day, when questions for the i-th exam will be published,
* d_i β the day of the i-th exam (s_i < d_i),
* c_i β number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i β€ j < d_i.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ n) β the number of days and the number of exams.
Each of the following m lines contains three integers s_i, d_i, c_i (1 β€ s_i < d_i β€ n, 1 β€ c_i β€ n) β the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is:
* (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted),
* zero, if in the j-th day Petya will have a rest,
* i (1 β€ i β€ m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).
Assume that the exams are numbered in order of appearing in the input, starting from 1.
If there are multiple schedules, print any of them.
Examples
Input
5 2
1 3 1
1 5 1
Output
1 2 3 0 3
Input
3 2
1 3 1
1 2 1
Output
-1
Input
10 3
4 7 2
1 10 3
8 9 1
Output
2 2 2 1 1 0 4 3 4 4
Note
In the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | instruction | 0 | 30,674 | 14 | 61,348 |
Tags: greedy, implementation, sortings
Correct Solution:
```
class exam1:
def __init__(self,ind,ee):
self.ind=ind
self.ee=ee
class exam:
def __init__(self,qq,ee,pp,ind):
self.qq=qq
self.ee=ee
self.pp=pp
self.ind=ind
yoar=list(map(int,input().split()))
n=yoar[0]
m=yoar[1]
ans=[]
examar=[]
paperar=[]
paperdayar=[]
for i in range(n):
ans.append(0)
paperdayar.append([])
for i in range(m):
yoar=list(map(int,input().split()))
qq=yoar[0]-1
ee=yoar[1]-1
pp=yoar[2]
examar.append(exam(qq,ee,pp,i))
ans[ee]=examar[-1]
paperdayar[qq].append(exam1(i,ee))
flag=0
for i in range(n):
if paperdayar[i]!=[]:
for j in paperdayar[i]:
paperar.append(j)
paperar.sort(key = lambda exam1:exam1.ee)
if type(ans[i])==exam:
if examar[ans[i].ind].pp>0:
print(-1)
flag=1
break
else:
if paperar==[]:
ans[i]=0
else:
ans[i]=paperar[0].ind+1
examar[paperar[0].ind].pp-=1
if (examar[paperar[0].ind].pp ==0):
del paperar[0]
if flag==0:
for i in range(n):
if type(ans[i])==exam:
print(m+1,end=" ")
else:
print(ans[i],end=" ")
print()
``` | output | 1 | 30,674 | 14 | 61,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.
There are three values about each exam:
* s_i β the day, when questions for the i-th exam will be published,
* d_i β the day of the i-th exam (s_i < d_i),
* c_i β number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i β€ j < d_i.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ n) β the number of days and the number of exams.
Each of the following m lines contains three integers s_i, d_i, c_i (1 β€ s_i < d_i β€ n, 1 β€ c_i β€ n) β the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is:
* (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted),
* zero, if in the j-th day Petya will have a rest,
* i (1 β€ i β€ m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).
Assume that the exams are numbered in order of appearing in the input, starting from 1.
If there are multiple schedules, print any of them.
Examples
Input
5 2
1 3 1
1 5 1
Output
1 2 3 0 3
Input
3 2
1 3 1
1 2 1
Output
-1
Input
10 3
4 7 2
1 10 3
8 9 1
Output
2 2 2 1 1 0 4 3 4 4
Note
In the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | instruction | 0 | 30,675 | 14 | 61,350 |
Tags: greedy, implementation, sortings
Correct Solution:
```
import heapq
n, m = map(int, input().split())
ans = [0]*n
ary = []
dp = [[0]*n for i in range(n)]
# print(dp)
tmp =0
while tmp < m:
s, d, c = map(int, input().split())
s -= 1; d -= 1
ans[d] = m + 1
ary.append((s, d, c + 1, tmp))
# print('sdc', s,d,c)
dp[s][d] = c + 1
# print('dp', dp[s][d])
tmp += 1
# print(dp)
d = 2
while d< n:
l = 0
while l+d < n:
r = l+d
dp[l][r] += dp[l+1][r] + dp[l][r-1] - dp[l+1][r-1]
# print('lr', l, r ,dp[l][r], dp[l + 1][r], dp[l][r - 1], dp[l + 1][r - 1])
# if dp[l][r] > d:
# print(-1)
# quit(0)
l += 1
d+=1
l = 0
pos = 0
sary = sorted(ary)
# print(sary)
que = []
while l<n:
while pos<m and sary[pos][0] == l:
heapq.heappush(que, [sary[pos][1], sary[pos][2] , sary[pos][3]])
pos += 1
if ans[l] > 0:
l += 1
continue
if que.__len__() == 0:
# ans[l] = 0
l += 1
continue
head = heapq.heappop(que)
# print('head',l, head)
if head[1] + l - 1 > head[0]:
print(-1)
quit(0)
head[1] -= 1
ans[l] = head[2] + 1
if head[1] > 1:
heapq.heappush(que, head)
l += 1
if que.__len__() >0 or pos < m:
print(-1)
else:
print(*ans)
``` | output | 1 | 30,675 | 14 | 61,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.
There are three values about each exam:
* s_i β the day, when questions for the i-th exam will be published,
* d_i β the day of the i-th exam (s_i < d_i),
* c_i β number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i β€ j < d_i.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ n) β the number of days and the number of exams.
Each of the following m lines contains three integers s_i, d_i, c_i (1 β€ s_i < d_i β€ n, 1 β€ c_i β€ n) β the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is:
* (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted),
* zero, if in the j-th day Petya will have a rest,
* i (1 β€ i β€ m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).
Assume that the exams are numbered in order of appearing in the input, starting from 1.
If there are multiple schedules, print any of them.
Examples
Input
5 2
1 3 1
1 5 1
Output
1 2 3 0 3
Input
3 2
1 3 1
1 2 1
Output
-1
Input
10 3
4 7 2
1 10 3
8 9 1
Output
2 2 2 1 1 0 4 3 4 4
Note
In the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | instruction | 0 | 30,676 | 14 | 61,352 |
Tags: greedy, implementation, sortings
Correct Solution:
```
#!/usr/bin/env python3
from sys import stdin, stdout
def rint():
return map(int, stdin.readline().split())
#lines = stdin.readlines()
n, m = rint()
s = [0 for i in range(m)]
d = [0 for i in range(m)]
c = [0 for i in range(m)]
for i in range(m):
s[i], d[i], c[i] = rint()
s_in_day = [set() for i in range(n+1)]
for i in range(m):
day = s[i]
s_in_day[day].add(i)
d_in_day = [-1 for i in range(n+1)]
for i in range(m):
day = d[i]
d_in_day[day] = i
di_sorted = [0 for i in range(m)]
di_sorted.sort(key=lambda x: d[i])
ans = [0 for i in range(n+1)]
candi_exam = set()
for day in range(1, n+1):
for exam in s_in_day[day]:
candi_exam.add(exam)
if d_in_day[day] != -1:
exam = d_in_day[day]
if c[exam] != 0:
print(-1)
exit()
ans[day] = m+1
if exam in candi_exam:
candi_exam.remove(exam)
continue
if len(candi_exam) == 0:
ans[day] = 0
continue
min_d_day = 101
busy_exam = 0
for exam in candi_exam:
if d[exam] < min_d_day:
busy_exam = exam
min_d_day = d[exam]
ans[day] = busy_exam + 1
c[busy_exam] -= 1
if c[busy_exam] == 0:
candi_exam.remove(busy_exam)
for i in range(m):
if c[i] != 0:
print(-1)
exit()
print(*ans[1:])
``` | output | 1 | 30,676 | 14 | 61,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.
There are three values about each exam:
* s_i β the day, when questions for the i-th exam will be published,
* d_i β the day of the i-th exam (s_i < d_i),
* c_i β number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i β€ j < d_i.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ n) β the number of days and the number of exams.
Each of the following m lines contains three integers s_i, d_i, c_i (1 β€ s_i < d_i β€ n, 1 β€ c_i β€ n) β the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is:
* (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted),
* zero, if in the j-th day Petya will have a rest,
* i (1 β€ i β€ m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).
Assume that the exams are numbered in order of appearing in the input, starting from 1.
If there are multiple schedules, print any of them.
Examples
Input
5 2
1 3 1
1 5 1
Output
1 2 3 0 3
Input
3 2
1 3 1
1 2 1
Output
-1
Input
10 3
4 7 2
1 10 3
8 9 1
Output
2 2 2 1 1 0 4 3 4 4
Note
In the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | instruction | 0 | 30,677 | 14 | 61,354 |
Tags: greedy, implementation, sortings
Correct Solution:
```
# from itertools import accumulate
# from bisect import bisect_left
# from collections import OrderedDict
I = lambda: list(map(int, input().split()))
n, m = I()
dates = [0 for i in range(n + 1)]
data = []
for i in range(m):
d = I() + [i + 1]
if dates[d[1]]:
print(-1)
exit(0)
dates[d[1]] = m + 1
data.append(d)
data.sort(key = lambda x: x[1])
for s, d, c, idx in data:
x = 0
for i in range(s, d):
if x == c:
break
if not dates[i]:
dates[i] = idx
x += 1
if x != c:
print(-1)
exit(0)
print(*dates[1:])
``` | output | 1 | 30,677 | 14 | 61,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.
There are three values about each exam:
* s_i β the day, when questions for the i-th exam will be published,
* d_i β the day of the i-th exam (s_i < d_i),
* c_i β number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i β€ j < d_i.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input
The first line contains two integers n and m (2 β€ n β€ 100, 1 β€ m β€ n) β the number of days and the number of exams.
Each of the following m lines contains three integers s_i, d_i, c_i (1 β€ s_i < d_i β€ n, 1 β€ c_i β€ n) β the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is:
* (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted),
* zero, if in the j-th day Petya will have a rest,
* i (1 β€ i β€ m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).
Assume that the exams are numbered in order of appearing in the input, starting from 1.
If there are multiple schedules, print any of them.
Examples
Input
5 2
1 3 1
1 5 1
Output
1 2 3 0 3
Input
3 2
1 3 1
1 2 1
Output
-1
Input
10 3
4 7 2
1 10 3
8 9 1
Output
2 2 2 1 1 0 4 3 4 4
Note
In the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | instruction | 0 | 30,678 | 14 | 61,356 |
Tags: greedy, implementation, sortings
Correct Solution:
```
n, m = map(int, input().split())
ans = [0]*n
f = 0
li = []
for i in range(m):
a, b, c = map(int, input().split())
li.append((b,a,c,i+1))
li.sort()
for i in range(m):
b, a, c, k = li[i]
ans[b-1] = m+1
j = a-1
cnt = 0
while j < b and cnt < c:
if ans[j] == 0:
ans[j] = k
cnt += 1
j+=1
if cnt != c:
f = 1
if f:
print(-1)
else:
print(*ans)
"""
6 2
1 6 3
1 2 1
"""
``` | output | 1 | 30,678 | 14 | 61,357 |
Provide a correct Python 3 solution for this coding contest problem.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or Cβ€F_iβ€D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1β€Nβ€10^3
* 1β€Aβ€Bβ€N
* 1β€Cβ€Dβ€N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0 | instruction | 0 | 30,815 | 14 | 61,630 |
"Correct Solution:
```
N,A,B,C,D=map(int,input().split())
mod=10**9+7
F=[1]*(N+1)
for i in range(1,N+1):
F[i]=F[i-1]*(i)%mod
def power(x,y):
if y==0:
return 1
elif y==1:
return x%mod
elif y%2==0:
return power(x,y//2)**2%mod
else:
return (power(x,y//2)**2)*x%mod
invF=[1]*(N+1)
invF[N]=power(F[N],mod-2)
for i in range(0,N)[::-1]:
invF[i]=(invF[i+1]*(i+1))%mod
invp=[[0]*(N+1) for i in range(N+1)]
for i in range(N+1):
for k in range(N+1):
if k==0:
invp[i][k]=1
else:
invp[i][k]=(invp[i][k-1]*invF[i])%mod
dp=[[0]*(N+1) for i in range(B-A+2)]
dp[0][0]=1
for i in range(A,B+1):
for j in range(N+1):
dp[i-A+1][j]=dp[i-A][j]
for k in range(C,min(D,j//i)+1):
dp[i-A+1][j]+=(dp[i-A][j-k*i]*F[N-j+k*i]*invF[N-j]*invp[i][k]*invF[k])%mod
dp[i-A+1][j]%=mod
print((dp[B-A+1][N])%mod)
``` | output | 1 | 30,815 | 14 | 61,631 |
Provide a correct Python 3 solution for this coding contest problem.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or Cβ€F_iβ€D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1β€Nβ€10^3
* 1β€Aβ€Bβ€N
* 1β€Cβ€Dβ€N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0 | instruction | 0 | 30,817 | 14 | 61,634 |
"Correct Solution:
```
def main():
import sys
input = sys.stdin.readline
mod = 1000000007
nmax = 1001 # change here
fac = [0] * (nmax + 1)
finv = [0] * (nmax + 1)
inv = [0] * (nmax + 1)
fac[0] = 1
fac[1] = 1
finv[0] = 1
finv[1] = 1
inv[1] = 1
for i in range(2, nmax):
fac[i] = fac[i - 1] * i % mod
inv[i] = mod - inv[mod % i] * (mod // i) % mod
finv[i] = finv[i - 1] * inv[i] % mod
N, A, B, C, D = map(int, input().split())
dp = [[0] * (N+1) for _ in range(B+1)]
for i in range(B+1):
dp[i][0] = 1
for i in range(A, B+1):
for j in range(N+1):
dp[i][j] = dp[i-1][j]
for j in range(N+1):
if (N-j) // i < C:
continue
n_max = min(D, (N-j)//i)
for n in range(C, n_max+1):
tmp = (((fac[N-j] * finv[N-j-i*n])%mod * pow(finv[i], n, mod))%mod * finv[n])%mod
dp[i][j+i*n] = (dp[i][j+i*n] + (dp[i-1][j] * tmp)%mod) % mod
print(dp[-1][-1])
if __name__ == '__main__':
main()
``` | output | 1 | 30,817 | 14 | 61,635 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.