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 |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.
Input
The first input line contains 3 space-separated integer numbers n, m, v (3 β€ n β€ 105, 0 β€ m β€ 105, 1 β€ v β€ n), n β amount of servers, m β amount of direct connections, v β index of the server that fails and leads to the failure of the whole system.
Output
If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each β description of all the direct connections in the system. Each direct connection is described by two numbers β indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.
Examples
Input
5 6 3
Output
1 2
2 3
3 4
4 5
1 3
3 5
Input
6 100 1
Output
-1 | instruction | 0 | 11,919 | 14 | 23,838 |
Tags: graphs
Correct Solution:
```
servers, conn, failturePoint = map(int, input().split(' '))
def main():
global conn
if conn > (servers - 1) * (servers - 2) / 2 + 1 or conn < servers - 1:
return -1
for i in range(1, servers+1):
if i != failturePoint:
print(str(i) + ' ' + str(failturePoint))
conn -= servers - 1
parent = 1 if failturePoint != 1 else 2
for i in range(1, servers+1):
if i != parent and i != failturePoint:
for j in range(i+1, servers+1):
if j != parent and j != failturePoint:
if conn == 0:
break
else:
print(str(i) + ' ' + str(j))
conn -= 1
res = main()
if res == -1:
print(res)
``` | output | 1 | 11,919 | 14 | 23,839 |
Provide tags and a correct Python 3 solution for this coding contest problem.
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.
Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input
The first line contains two integers n and t (1 β€ n β€ 105; 1 β€ t β€ 109) β the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 β€ ai β€ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.
Output
Print a single integer β the maximum number of books Valera can read.
Examples
Input
4 5
3 1 2 1
Output
3
Input
3 3
2 2 3
Output
1 | instruction | 0 | 11,944 | 14 | 23,888 |
Tags: binary search, brute force, implementation, two pointers
Correct Solution:
```
n, t = map(int, input().split())
a = [int(a) for a in input().split()]
j = -1
ans = 0
s = 0
for i in range(n):
s += a[i]
while s > t:
j += 1
s -= a[j]
ans = max(i-j, ans)
print(ans)
``` | output | 1 | 11,944 | 14 | 23,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.
Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input
The first line contains two integers n and t (1 β€ n β€ 105; 1 β€ t β€ 109) β the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 β€ ai β€ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.
Output
Print a single integer β the maximum number of books Valera can read.
Examples
Input
4 5
3 1 2 1
Output
3
Input
3 3
2 2 3
Output
1 | instruction | 0 | 11,945 | 14 | 23,890 |
Tags: binary search, brute force, implementation, two pointers
Correct Solution:
```
n, t = map(int, input().split())
a = list(map(int, input().split()))
summ = 0
j = 0
ans = 0
for i in range(n):
summ += a[i]
while (summ > t):
summ -= a[j]
j += 1
ans = max(ans, i - j + 1)
print(ans)
``` | output | 1 | 11,945 | 14 | 23,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.
Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input
The first line contains two integers n and t (1 β€ n β€ 105; 1 β€ t β€ 109) β the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 β€ ai β€ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.
Output
Print a single integer β the maximum number of books Valera can read.
Examples
Input
4 5
3 1 2 1
Output
3
Input
3 3
2 2 3
Output
1 | instruction | 0 | 11,946 | 14 | 23,892 |
Tags: binary search, brute force, implementation, two pointers
Correct Solution:
```
# http://codeforces.com/problemset/problem/279/B
n,t = map(int, input().split())
a = list(map(int, input().split()))
i = j = s = 0
for j in range(len(a)):
s+=a[j]
if s > t:
s -= a[i]
i+=1
print(j-i+1)
``` | output | 1 | 11,946 | 14 | 23,893 |
Provide tags and a correct Python 3 solution for this coding contest problem.
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.
Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input
The first line contains two integers n and t (1 β€ n β€ 105; 1 β€ t β€ 109) β the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 β€ ai β€ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.
Output
Print a single integer β the maximum number of books Valera can read.
Examples
Input
4 5
3 1 2 1
Output
3
Input
3 3
2 2 3
Output
1 | instruction | 0 | 11,947 | 14 | 23,894 |
Tags: binary search, brute force, implementation, two pointers
Correct Solution:
```
if __name__ == '__main__':
n, t = map(int, input().split())
all_a = list(map(int, input().split()))
sums = []
s, start = t, 0
for stop, element in enumerate(all_a):
s -= element
while s < 0:
s += all_a[start]
start += 1
sums.append(stop-start)
print(max(sums) + 1)
``` | output | 1 | 11,947 | 14 | 23,895 |
Provide tags and a correct Python 3 solution for this coding contest problem.
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.
Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input
The first line contains two integers n and t (1 β€ n β€ 105; 1 β€ t β€ 109) β the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 β€ ai β€ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.
Output
Print a single integer β the maximum number of books Valera can read.
Examples
Input
4 5
3 1 2 1
Output
3
Input
3 3
2 2 3
Output
1 | instruction | 0 | 11,949 | 14 | 23,898 |
Tags: binary search, brute force, implementation, two pointers
Correct Solution:
```
n,m=map(int,input().split())
a=list(map(int,input().split()))
s=pointer=ans=0
for i in range(n):
s+=a[i]
while s>m:
s-=a[pointer]
pointer+=1
ans=max(ans,i-pointer+1)
print(ans)
``` | output | 1 | 11,949 | 14 | 23,899 |
Provide tags and a correct Python 3 solution for this coding contest problem.
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.
Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input
The first line contains two integers n and t (1 β€ n β€ 105; 1 β€ t β€ 109) β the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 β€ ai β€ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.
Output
Print a single integer β the maximum number of books Valera can read.
Examples
Input
4 5
3 1 2 1
Output
3
Input
3 3
2 2 3
Output
1 | instruction | 0 | 11,950 | 14 | 23,900 |
Tags: binary search, brute force, implementation, two pointers
Correct Solution:
```
n,t = map(int, input().split())
L = list(map(int, input().split()))
i,j,s = 0,0,0
for i in range(n):
s = s + L[i]
if s > t:
s = s - L[j]
j += 1
print(n-j)
``` | output | 1 | 11,950 | 14 | 23,901 |
Provide tags and a correct Python 3 solution for this coding contest problem.
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.
Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
Input
The first line contains two integers n and t (1 β€ n β€ 105; 1 β€ t β€ 109) β the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 β€ ai β€ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.
Output
Print a single integer β the maximum number of books Valera can read.
Examples
Input
4 5
3 1 2 1
Output
3
Input
3 3
2 2 3
Output
1 | instruction | 0 | 11,951 | 14 | 23,902 |
Tags: binary search, brute force, implementation, two pointers
Correct Solution:
```
n, t = map(int,input().split())
a = list(map(int,input().split()))
time = 0
count = 0
x = 0
for i in range(len(a)):
time += a[i]
count += 1
if time > t:
time -= a[x]
x += 1
count -= 1
print(count)
``` | output | 1 | 11,951 | 14 | 23,903 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighboring ones.
The mushroom gnomes loved it when everything was in order, that's why they always planted the mushrooms in one line in the order of their weights' increasing. Well... The gnomes planted the mushrooms and went to eat. After x minutes they returned and saw that new mushrooms had grown up, so that the increasing order had been violated. The gnomes replanted all the mushrooms in the correct order, that is, they sorted the mushrooms in the order of the weights' increasing. And went to eat again (those gnomes were quite big eaters). What total weights modulo p will the mushrooms have in another y minutes?
Input
The first line contains four integers n, x, y, p (1 β€ n β€ 106, 0 β€ x, y β€ 1018, x + y > 0, 2 β€ p β€ 109) which represent the number of mushrooms, the number of minutes after the first replanting, the number of minutes after the second replanting and the module. The next line contains n integers ai which represent the mushrooms' weight in the non-decreasing order (0 β€ ai β€ 109).
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Output
The answer should contain a single number which is the total weights of the mushrooms modulo p in the end after x + y minutes.
Examples
Input
2 1 0 657276545
1 2
Output
6
Input
2 1 1 888450282
1 2
Output
14
Input
4 5 0 10000
1 2 3 4
Output
1825 | instruction | 0 | 12,072 | 14 | 24,144 |
Tags: math, matrices
Correct Solution:
```
#!/usr/bin/pypy3
from sys import stdin, stdout
input, print = stdin.readline, stdout.write
p = 0
def readints():
return list(map(int, input().split()))
def writeln(x):
print(str(x) + '\n')
def mod(x):
return (x % p + p) % p
def matmul(a, b):
n = len(a)
c = [[0 for x in range(n)] for y in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % p
return c
def matpow(b, p):
n = len(b)
res = [[0 if x != y else 1 for x in range(n)] for y in range(n)]
while p:
if p & 1:
res = matmul(res, b)
b = matmul(b, b)
p >>= 1
return res
def main():
global p
n, x, y, p = readints()
a = [each % p for each in sorted(readints())]
if n == 1:
writeln(a[0])
return
"""
[a sum] * [[1 -1], = [a sum]
[0 3]]
[sc mv] * [[0 1],
[1, 1]] = [mv mv+sc]
"""
b = matpow([
[1, -1],
[0, 3]], x)
sum0 = matmul([
[a[0] + a[-1], sum(a)],
[0, 0]], b)[0][1]
b = matpow([
[0, 1],
[1, 1]], x)
maxa = matmul(
[[a[-2], a[-1]],
[0, 0]], b)[0][1]
b = matpow([
[1, -1],
[0, 3]], y)
sum1 = matmul([
[a[0] + maxa, sum0],
[0, 0]], b)[0][1]
writeln(mod(sum1))
if __name__ == '__main__':
main()
``` | output | 1 | 12,072 | 14 | 24,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighboring ones.
The mushroom gnomes loved it when everything was in order, that's why they always planted the mushrooms in one line in the order of their weights' increasing. Well... The gnomes planted the mushrooms and went to eat. After x minutes they returned and saw that new mushrooms had grown up, so that the increasing order had been violated. The gnomes replanted all the mushrooms in the correct order, that is, they sorted the mushrooms in the order of the weights' increasing. And went to eat again (those gnomes were quite big eaters). What total weights modulo p will the mushrooms have in another y minutes?
Input
The first line contains four integers n, x, y, p (1 β€ n β€ 106, 0 β€ x, y β€ 1018, x + y > 0, 2 β€ p β€ 109) which represent the number of mushrooms, the number of minutes after the first replanting, the number of minutes after the second replanting and the module. The next line contains n integers ai which represent the mushrooms' weight in the non-decreasing order (0 β€ ai β€ 109).
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Output
The answer should contain a single number which is the total weights of the mushrooms modulo p in the end after x + y minutes.
Examples
Input
2 1 0 657276545
1 2
Output
6
Input
2 1 1 888450282
1 2
Output
14
Input
4 5 0 10000
1 2 3 4
Output
1825 | instruction | 0 | 12,073 | 14 | 24,146 |
Tags: math, matrices
Correct Solution:
```
#!/usr/bin/pypy3
from sys import stdin, stdout
input, print = stdin.readline, stdout.write
p = 0
def readints():
return list(map(int, input().split()))
def writeln(x):
print(str(x) + '\n')
def mod(x):
return (x % p + p) % p
def matmul(a, b):
n = len(a)
c = [[0 for x in range(n)] for y in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % p
return c
def matpow(b, p):
n = len(b)
res = [[0 if x != y else 1 for x in range(n)] for y in range(n)]
while p:
if p & 1:
res = matmul(res, b)
b = matmul(b, b)
p >>= 1
return res
n, x, y, p = readints()
a = [each % p for each in sorted(readints())]
if n == 1:
writeln(a[0])
exit(0)
"""
[a sum] * [[1 -1], = [a sum]
[0 3]]
[sc mv] * [[0 1],
[1, 1]] = [mv mv+sc]
"""
b = matpow([
[1, -1],
[0, 3]], x)
sum0 = matmul([
[a[0] + a[-1], sum(a)],
[0, 0]], b)[0][1]
b = matpow([
[0, 1],
[1, 1]], x)
maxa = matmul(
[[a[-2], a[-1]],
[0, 0]], b)[0][1]
b = matpow([
[1, -1],
[0, 3]], y)
sum1 = matmul([
[a[0] + maxa, sum0],
[0, 0]], b)[0][1]
writeln(mod(sum1))
``` | output | 1 | 12,073 | 14 | 24,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied:
* A = B;
* the man number A is the father of the man number B;
* there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B.
Of course, if the man number A is an ancestor of the man number B and A β B, then the man number B is not an ancestor of the man number A.
The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens.
1. A list of candidates is prepared, containing some (possibly all) of the n men in some order.
2. Each of the n men decides to give a gift.
3. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself.
4. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.
This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?
Input
In the first line of the input two integers n and m (0 β€ m < n β€ 100 000) are given β the number of the men in the Sasha's family and the number of family relations in it respectively.
The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 β€ pi, qi β€ n, pi β qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 β€ i β€ n the man numbered ai is an ancestor of the man numbered i.
Output
Print an integer k (1 β€ k β€ n) β the number of the men in the list of candidates, in the first line.
Print then k pairwise different positive integers not exceeding n β the numbers of the men in the list in an order satisfying every of the men's wishes, one per line.
If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line.
Examples
Input
3 2
1 2
2 3
1 2 1
Output
-1
Input
4 2
1 2
3 4
1 2 3 3
Output
3
2
1
3
Note
The first sample explanation:
* if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1);
* if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2);
* if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2).
* if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1). | instruction | 0 | 12,108 | 14 | 24,216 |
Tags: constructive algorithms, dfs and similar, graphs, trees
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
n,m = map(int,input().split())
path = [[] for _ in range(n)]
indeg = [0]*n
for _ in range(m):
p1,q1 = map(int,input().split())
path[p1-1].append(q1-1)
indeg[q1-1] += 1
gif = list(map(int,input().split()))
fin,poi = [],[0]*n
for i in range(n):
if indeg[i]:
continue
st,st1 = [i],[i]
while len(st):
x,y = st[-1],poi[st[-1]]
if y == len(path[x]):
st.pop()
continue
z = path[x][y]
if gif[z] == z+1:
st1.append(z)
elif gif[z] != gif[x]:
print(-1)
return
st.append(z)
poi[x] += 1
fin += list(map(lambda xx:xx+1,st1[::-1]))
print(len(fin))
print(*fin,sep='\n')
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 12,108 | 14 | 24,217 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied:
* A = B;
* the man number A is the father of the man number B;
* there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B.
Of course, if the man number A is an ancestor of the man number B and A β B, then the man number B is not an ancestor of the man number A.
The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens.
1. A list of candidates is prepared, containing some (possibly all) of the n men in some order.
2. Each of the n men decides to give a gift.
3. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself.
4. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.
This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?
Input
In the first line of the input two integers n and m (0 β€ m < n β€ 100 000) are given β the number of the men in the Sasha's family and the number of family relations in it respectively.
The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 β€ pi, qi β€ n, pi β qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 β€ i β€ n the man numbered ai is an ancestor of the man numbered i.
Output
Print an integer k (1 β€ k β€ n) β the number of the men in the list of candidates, in the first line.
Print then k pairwise different positive integers not exceeding n β the numbers of the men in the list in an order satisfying every of the men's wishes, one per line.
If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line.
Examples
Input
3 2
1 2
2 3
1 2 1
Output
-1
Input
4 2
1 2
3 4
1 2 3 3
Output
3
2
1
3
Note
The first sample explanation:
* if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1);
* if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2);
* if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2).
* if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1). | instruction | 0 | 12,109 | 14 | 24,218 |
Tags: constructive algorithms, dfs and similar, graphs, trees
Correct Solution:
```
# [https://codeforces.com/contest/681/submission/37694242 <- https://codeforces.com/contest/681/status/D <- https://codeforces.com/contest/681 <- https://codeforces.com/blog/entry/45425 <- https://codeforces.com/problemset/problem/681/D <- https://algoprog.ru/material/pc681pD]
(n, m) = map(int, input().split())
adj = [[] for _ in range(n)]
cp = [-1] * n
for i in range(m):
p, c = map(int, input().split())
adj[p - 1].append(c - 1)
cp[c - 1] = p - 1
pres = [i - 1 for i in map(int, input().split())]
level = [0] * n
from collections import deque
def bfs(v):
q = deque([v])
while q:
v = q.pop()
if cp[v] >= 0:
level[v] = level[cp[v]] + 1
for nv in adj[v]:
q.append(nv)
for i in range(n):
if cp[i] == -1:
bfs(i)
for i in range(n):
if level[i] > 0:
par = cp[i]
if pres[i] != pres[par] and level[pres[i]] <= level[par]:
print(-1)
exit()
pres = list(set(pres))
pres = sorted(pres, key = lambda i : level[i], reverse = True)
print(len(pres))
pres = [i + 1 for i in pres]
print("\n".join(map(str, pres)))
``` | output | 1 | 12,109 | 14 | 24,219 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied:
* A = B;
* the man number A is the father of the man number B;
* there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B.
Of course, if the man number A is an ancestor of the man number B and A β B, then the man number B is not an ancestor of the man number A.
The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens.
1. A list of candidates is prepared, containing some (possibly all) of the n men in some order.
2. Each of the n men decides to give a gift.
3. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself.
4. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.
This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?
Input
In the first line of the input two integers n and m (0 β€ m < n β€ 100 000) are given β the number of the men in the Sasha's family and the number of family relations in it respectively.
The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 β€ pi, qi β€ n, pi β qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 β€ i β€ n the man numbered ai is an ancestor of the man numbered i.
Output
Print an integer k (1 β€ k β€ n) β the number of the men in the list of candidates, in the first line.
Print then k pairwise different positive integers not exceeding n β the numbers of the men in the list in an order satisfying every of the men's wishes, one per line.
If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line.
Examples
Input
3 2
1 2
2 3
1 2 1
Output
-1
Input
4 2
1 2
3 4
1 2 3 3
Output
3
2
1
3
Note
The first sample explanation:
* if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1);
* if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2);
* if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2).
* if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1). | instruction | 0 | 12,110 | 14 | 24,220 |
Tags: constructive algorithms, dfs and similar, graphs, trees
Correct Solution:
```
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
cp = [-1] * n
for i in range(m):
p, c = map(int, input().split())
adj[p - 1].append(c - 1)
cp[c - 1] = p - 1
pres = [i - 1 for i in map(int, input().split())]
level = [0] * n
from collections import deque
def bfs(v):
q = deque([v])
while q:
v = q.pop()
if cp[v] >= 0:
level[v] = level[cp[v]] + 1
for nv in adj[v]:
q.append(nv)
for i in range(n):
if cp[i] == -1:
bfs(i)
for i in range(n):
if level[i] > 0:
par = cp[i]
if pres[i] != pres[par] and level[pres[i]] <= level[par]:
print(-1)
exit()
pres = list(set(pres))
pres = sorted(pres, key = lambda i : level[i], reverse = True)
print(len(pres))
pres = [i + 1 for i in pres]
print("\n".join(map(str, pres)))
``` | output | 1 | 12,110 | 14 | 24,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied:
* A = B;
* the man number A is the father of the man number B;
* there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B.
Of course, if the man number A is an ancestor of the man number B and A β B, then the man number B is not an ancestor of the man number A.
The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens.
1. A list of candidates is prepared, containing some (possibly all) of the n men in some order.
2. Each of the n men decides to give a gift.
3. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself.
4. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.
This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?
Input
In the first line of the input two integers n and m (0 β€ m < n β€ 100 000) are given β the number of the men in the Sasha's family and the number of family relations in it respectively.
The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 β€ pi, qi β€ n, pi β qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 β€ i β€ n the man numbered ai is an ancestor of the man numbered i.
Output
Print an integer k (1 β€ k β€ n) β the number of the men in the list of candidates, in the first line.
Print then k pairwise different positive integers not exceeding n β the numbers of the men in the list in an order satisfying every of the men's wishes, one per line.
If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line.
Examples
Input
3 2
1 2
2 3
1 2 1
Output
-1
Input
4 2
1 2
3 4
1 2 3 3
Output
3
2
1
3
Note
The first sample explanation:
* if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1);
* if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2);
* if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2).
* if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1).
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
n,m = map(int,input().split())
path = [[] for _ in range(n)]
indeg = [0]*n
for _ in range(m):
p1,q1 = map(int,input().split())
path[p1-1].append(q1-1)
indeg[q1-1] += 1
gif = list(map(int,input().split()))
fin = []
poi = [0]*n
for i in range(n):
if indeg[i]:
continue
st,st1 = [i],[i]
while len(st):
x,y = st[-1],poi[st[-1]]
if y == len(path[x]):
st.pop()
continue
z = path[x][y]
if gif[z] == z+1:
st.append(z)
st1.append(z)
elif gif[z] != x+1:
print(-1)
return
poi[x] += 1
fin += list(map(lambda xx:xx+1,st1[::-1]))
print(len(fin))
print(*fin,sep='\n')
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 12,111 | 14 | 24,222 |
No | output | 1 | 12,111 | 14 | 24,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied:
* A = B;
* the man number A is the father of the man number B;
* there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B.
Of course, if the man number A is an ancestor of the man number B and A β B, then the man number B is not an ancestor of the man number A.
The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens.
1. A list of candidates is prepared, containing some (possibly all) of the n men in some order.
2. Each of the n men decides to give a gift.
3. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself.
4. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.
This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?
Input
In the first line of the input two integers n and m (0 β€ m < n β€ 100 000) are given β the number of the men in the Sasha's family and the number of family relations in it respectively.
The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 β€ pi, qi β€ n, pi β qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 β€ i β€ n the man numbered ai is an ancestor of the man numbered i.
Output
Print an integer k (1 β€ k β€ n) β the number of the men in the list of candidates, in the first line.
Print then k pairwise different positive integers not exceeding n β the numbers of the men in the list in an order satisfying every of the men's wishes, one per line.
If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line.
Examples
Input
3 2
1 2
2 3
1 2 1
Output
-1
Input
4 2
1 2
3 4
1 2 3 3
Output
3
2
1
3
Note
The first sample explanation:
* if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1);
* if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2);
* if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2).
* if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1).
Submitted Solution:
```
n, k = list(map(int, input().split()))
c = [[-1] * n for i in range(n)]
for i in range(n - 1):
temp = list(map(int, input().split()))
index = 0
for j in range(i + 1, n):
c[j][i] = c[i][j] = temp[index]
index += 1
sum = 0
if k == 1 or (k > 2 and n == k + 1):
for i in range(n):
for j in range(n):
if c[i][j] != -1:
sum += c[i][j]
print(int(sum / n))
elif k == 2:
count = n * (n - 1) / 2
for i in range(n):
adj = []
for j in range(n):
if c[i][j] != -1:
adj.append(j)
for j in range(len(adj)):
for z in range(j + 1, len(adj)):
sum += c[i][adj[j]] + c[i][adj[z]]
print(int(sum/count))
``` | instruction | 0 | 12,112 | 14 | 24,224 |
No | output | 1 | 12,112 | 14 | 24,225 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha lives in a big happy family. At the Man's Day all the men of the family gather to celebrate it following their own traditions. There are n men in Sasha's family, so let's number them with integers from 1 to n.
Each man has at most one father but may have arbitrary number of sons.
Man number A is considered to be the ancestor of the man number B if at least one of the following conditions is satisfied:
* A = B;
* the man number A is the father of the man number B;
* there is a man number C, such that the man number A is his ancestor and the man number C is the father of the man number B.
Of course, if the man number A is an ancestor of the man number B and A β B, then the man number B is not an ancestor of the man number A.
The tradition of the Sasha's family is to give gifts at the Man's Day. Because giving gifts in a normal way is boring, each year the following happens.
1. A list of candidates is prepared, containing some (possibly all) of the n men in some order.
2. Each of the n men decides to give a gift.
3. In order to choose a person to give a gift to, man A looks through the list and picks the first man B in the list, such that B is an ancestor of A and gives him a gift. Note that according to definition it may happen that a person gives a gift to himself.
4. If there is no ancestor of a person in the list, he becomes sad and leaves the celebration without giving a gift to anyone.
This year you have decided to help in organizing celebration and asked each of the n men, who do they want to give presents to (this person is chosen only among ancestors). Are you able to make a list of candidates, such that all the wishes will be satisfied if they give gifts according to the process described above?
Input
In the first line of the input two integers n and m (0 β€ m < n β€ 100 000) are given β the number of the men in the Sasha's family and the number of family relations in it respectively.
The next m lines describe family relations: the (i + 1)th line consists of pair of integers pi and qi (1 β€ pi, qi β€ n, pi β qi) meaning that the man numbered pi is the father of the man numbered qi. It is guaranteed that every pair of numbers appears at most once, that among every pair of two different men at least one of them is not an ancestor of another and that every man has at most one father.
The next line contains n integers a1, a2, ..., an (1 β€ ai β€ n), ith of which means that the man numbered i wants to give a gift to the man numbered ai. It is guaranteed that for every 1 β€ i β€ n the man numbered ai is an ancestor of the man numbered i.
Output
Print an integer k (1 β€ k β€ n) β the number of the men in the list of candidates, in the first line.
Print then k pairwise different positive integers not exceeding n β the numbers of the men in the list in an order satisfying every of the men's wishes, one per line.
If there are more than one appropriate lists, print any of them. If there is no appropriate list print - 1 in the only line.
Examples
Input
3 2
1 2
2 3
1 2 1
Output
-1
Input
4 2
1 2
3 4
1 2 3 3
Output
3
2
1
3
Note
The first sample explanation:
* if there would be no 1 in the list then the first and the third man's wishes would not be satisfied (a1 = a3 = 1);
* if there would be no 2 in the list then the second man wish would not be satisfied (a2 = 2);
* if 1 would stay before 2 in the answer then the second man would have to give his gift to the first man, but he wants to give it to himself (a2 = 2).
* if, at the other hand, the man numbered 2 would stay before the man numbered 1, then the third man would have to give his gift to the second man, but not to the first (a3 = 1).
Submitted Solution:
```
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
cp = [-1] * n
for i in range(m):
p, c = map(int, input().split())
adj[p - 1].append(c - 1)
cp[c - 1] = p - 1
pres = [i - 1 for i in map(int, input().split())]
level = [0] * n
from collections import deque
def bfs(v):
q = deque([v])
while q:
v = q.pop()
if cp[v] > 0:
level[v] = level[cp[v]] + 1
for nv in adj[v]:
q.append(nv)
for i in range(n):
if cp[i] == -1:
bfs(i)
for i in range(n):
if level[i] > 0:
par = cp[i]
if pres[i] != pres[par] and level[pres[i]] <= level[par]:
print(-1)
exit()
pres = list(set(pres))
pres = sorted(pres, key = lambda i : level[i], reverse = True)
print(len(pres))
for pi in pres:
print(pi + 1)
``` | instruction | 0 | 12,113 | 14 | 24,226 |
No | output | 1 | 12,113 | 14 | 24,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image> | instruction | 0 | 12,146 | 14 | 24,292 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
n, m = [int(x) for x in input().split()]
l = []
for i in range(m):
x, y = [int(x) for x in input().split()]
if x>y: x,y = y,x
l.append((x, y))
l.sort(key=lambda x: x[0])
labels = {}
rels_count = {}
class_count = {}
for x, y in l:
if x not in labels:
labels[x] = len(rels_count)
rels_count[labels[x]] = 0
class_count[labels[x]] = 1
if y not in labels:
class_count[labels[x]] += 1
labels[y] = labels[x]
rels_count[labels[x]]+=1
flag = True
for i in range(len(rels_count)):
l_n = class_count[i]
l_m = rels_count[i]
if l_n*(l_n-1) != 2*l_m:
flag = False
break
if flag:
print("YES")
else:
print("NO")
``` | output | 1 | 12,146 | 14 | 24,293 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image> | instruction | 0 | 12,147 | 14 | 24,294 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from collections import defaultdict,deque
from sys import *
def bfs(graph,vis,node):
q=deque()
q.append(node)
vis[node]=0
cnt=1
while q:
s=q.popleft()
for i in graph[s]:
if vis[i]==1:
vis[i]=0
cnt+=1
if len(graph[s])!=len(graph[i]):
return -1
q.append(i)
return cnt
n,m=map(int,stdin.readline().split())
graph=defaultdict(list)
here=[0]*(n+1)
for i in range(m):
u,v=map(int,stdin.readline().split())
graph[u].append(v)
graph[v].append(u)
here[u]=1
here[v]=1
ver=0
for i in range(n):
if here[i]==0:
continue
ver=bfs(graph,here,i)
if ver==-1:
break
if ver-1!=len(graph[i]):
ver=-1
break
if ver==-1:
stdout.write("NO\n")
else:
stdout.write("YES\n")
``` | output | 1 | 12,147 | 14 | 24,295 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image> | instruction | 0 | 12,148 | 14 | 24,296 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
import math
from decimal import Decimal
from decimal import *
from collections import defaultdict, deque
import heapq
getcontext().prec = 25
abcd='abcdefghijklmnopqrstuvwxyz'
MOD = pow(10, 9) + 7
BUFSIZE = 8192
from bisect import bisect_left, bisect_right
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# n, k = map(int, input().split(" "))
# list(map(int, input().split(" ")))
# for _ in range(int(input())):
def dfs(i):
visited[i]=True
an = True
f = g[i]
for j in g[i]:
if not visited[j]:
visited[j]=True
if g[j]!=g[i]:
an=False
break
return an
n, k = map(int, input().split(" "))
g = [set() for i in range(n+1)]
for i in range(k):
x, y = map(int, input().split(" "))
g[x].add(x)
g[y].add(y)
g[x].add(y)
g[y].add(x)
ans = "YES"
visited = [False]*(n+1)
# print(g)
for i in range(1, n+1):
if not visited[i]:
test = dfs(i)
if not test:
ans="NO"
break
print(ans)
``` | output | 1 | 12,148 | 14 | 24,297 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image> | instruction | 0 | 12,149 | 14 | 24,298 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys
n,m=map(int,input().split())
q={i:set([i]) for i in range(1,n+1)}
v=set()
for i in range(m):
a,b=map(int,input().split())
q[a].add(b)
q[b].add(a)
for k,w in q.items():
if k not in v:
z=[q[i]==w for i in w]
if 0 not in z: v.update(w)
else:
print('NO')
sys.exit()
print('YES')
``` | output | 1 | 12,149 | 14 | 24,299 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image> | instruction | 0 | 12,150 | 14 | 24,300 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
import sys
def main():
n,m = map(int,sys.stdin.readline().split())
l = [[] for i in range(n+1)]
u = [False]*(n+1)
for i in range(m):
a, b = map(int,sys.stdin.readline().split())
l[a].append(b)
l[b].append(a)
for i in range(n):
j = i+1
if u[j]:
continue
u[j] = True
q = []
cl = len(l[j])
cn = 1
for a in l[j]:
q.append(a)
while len(q)!=0 :
cur = q.pop()
if u[cur]:
continue
u[cur] = True
cn+=1
cl+=len(l[cur])
for a in l[cur]:
if u[a]:
continue
q.append(a)
if cl!=cn*(cn-1):
#print(j, cl, cn)
print("NO")
return
print("YES")
main()
``` | output | 1 | 12,150 | 14 | 24,301 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image> | instruction | 0 | 12,151 | 14 | 24,302 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from collections import defaultdict
import sys
input=__import__('sys').stdin.readline
n,m=map(int,input().split())
adj=defaultdict(set)
vis=[False]*(n+1)
for i in range(m):
u,v=map(int,input().split())
adj[u].add(v)
adj[v].add(u)
for x in adj:
adj[x].add(x)
for i in range(1,n+1):
if not vis[i]:
for j in adj[i]:
vis[j]=True
if adj[i]!=adj[j]:
print("NO")
exit()
print("YES")
``` | output | 1 | 12,151 | 14 | 24,303 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image> | instruction | 0 | 12,152 | 14 | 24,304 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin
from collections import deque
#from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def lsi():
x=list(stdin.readline())
x.pop()
return x
def si(): return stdin.readline()
############# CODE STARTS HERE #############
n, m=mi()
a=[{i} for i in range(n+1)]
v=[True]*(n+1)
for _ in range(m):
x, y=mi()
a[x].add(y)
a[y].add(x)
for i in range(1, n+1):
if v[i]:
for j in a[i]:
if a[i]!=a[j]:
print('NO')
exit()
v[j]=False
#print(a)
print('YES')
``` | output | 1 | 12,152 | 14 | 24,305 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image> | instruction | 0 | 12,153 | 14 | 24,306 |
Tags: dfs and similar, dsu, graphs
Correct Solution:
```
from collections import Counter,defaultdict,deque
#alph = 'abcdefghijklmnopqrstuvwxyz'
#from math import factorial as fact
#nl = '\n'
#import sys
#input=sys.stdin.readline
#print=sys.stdout.write
#tt = int(input())
#total=0
#n = int(input())
#n,m,k = [int(x) for x in input().split()]
#n = int(input())
#l,r = [int(x) for x in input().split()]
n,m = [int(x) for x in input().split()]
connections = [[] for i in range(n)]
for i in range(m):
a,b = [int(x)-1 for x in input().split()]
connections[a].append(b)
connections[b].append(a)
globalvisited = [False for i in range(n)]
def DFS(cmap,v):
#visited = [False]*len(cmap)
stack = deque([v])
#order = deque()
vcount = 0
ecount = len(cmap[v])
while len(stack)!=0:
vertex = stack.pop()
if not globalvisited[vertex]:
vcount+=1
#order.append(vertex)
#visited[vertex] = True
globalvisited[vertex] = True
if len(cmap[vertex])!=ecount:
return False
stack.extend(cmap[vertex])
#print(vcount,ecount)
return vcount-1==ecount
for i in range(n):
if not globalvisited[i]:
cur=DFS(connections,i)
if not cur:
print('NO')
exit()
print('YES')
``` | output | 1 | 12,153 | 14 | 24,307 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import defaultdict
from collections import deque
n,m=list(map(int,input().split()))
d=defaultdict(list)
for i in range(m):
x,y=list(map(int,input().split()))
d[x].append(y)
d[y].append(x)
visited=[0]*(n+1)
f=0
for i in d:
if visited[i]==0:
q=deque()
q.append(i)
c=0
t=len(d[i])
visited[i]=1
while q:
j=q.popleft()
if t!=len(d[j]):
f=1
c=c+1
for k in d[j]:
if visited[k]==0:
if c>1:
f=1
break
else:
q.append(k)
visited[k]=1
if f:
break
if f:
break
if f:
print('NO')
else:
print('YES')
``` | instruction | 0 | 12,154 | 14 | 24,308 |
Yes | output | 1 | 12,154 | 14 | 24,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource
# sys.setrecursionlimit(10**6)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)
def IF(c, t, f): return t if c else f
def YES(c): return IF(c, "YES", "NO")
def Yes(c): return IF(c, "Yes", "No")
class UnionFind:
def __init__(self, size):
self.table = [-1 for _ in range(size)]
def find(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self.find(self.table[x])
return self.table[x]
def union(self, x, y):
s1 = self.find(x)
s2 = self.find(y)
if s1 != s2:
if self.table[s1] <= self.table[s2]:
self.table[s1] += self.table[s2]
self.table[s2] = s1
else:
self.table[s2] += self.table[s1]
self.table[s1] = s2
return True
return False
def same(self, x, y):
return self.find(x) == self.find(y)
def subsetall(self):
a = []
for i in range(len(self.table)):
if self.table[i] < 0:
a.append((i, -self.table[i]))
return a
def main():
t = 1
rr = []
for _ in range(t):
n,m = LI()
ab = [LI_() for _ in range(m)]
uf = UnionFind(n)
for a,b in ab:
uf.union(a,b)
t = 0
for i in range(n):
k = -uf.table[i]
if k > 0:
t += k * (k-1) // 2
rr.append(YES(t == m))
return JA(rr, "\n")
print(main())
``` | instruction | 0 | 12,155 | 14 | 24,310 |
Yes | output | 1 | 12,155 | 14 | 24,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
# Problem: A. Bear and Friendship Condition
# Contest: Codeforces - VK Cup 2017 - Round 1
# URL: https://codeforces.com/problemset/problem/771/A
# Memory Limit: 256 MB
# Time Limit: 1000 ms
#
# KAPOOR'S
from sys import stdin, stdout
def INI():
return int(stdin.readline())
def INL():
return [int(_) for _ in stdin.readline().split()]
def INS():
return stdin.readline()
def MOD():
return pow(10,9)+7
def OPS(ans):
stdout.write(str(ans)+"\n")
def OPL(ans):
[stdout.write(str(_)+" ") for _ in ans]
stdout.write("\n")
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(v):
V[v]=True
S.append(v)
global c
c+=1
for _ in X[v]:
if not V[_]:
yield dfs(_)
yield
if __name__=="__main__":
n,m=INL()
X=[[] for _ in range(n+1)]
V=[False for _ in range(n+1)]
C=[0 for _ in range(n+1)]
for _ in range(m):
u,v=INL()
X[u].append(v)
X[v].append(u)
C[u]+=1
C[v]+=1
for _ in range(1,n+1):
S=[]
c=0
if not V[_]:
dfs(_)
for _ in S:
if C[_]!=c-1:
OPS("NO")
break
else:
continue
break
else:
OPS('YES')
``` | instruction | 0 | 12,156 | 14 | 24,312 |
Yes | output | 1 | 12,156 | 14 | 24,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
def li(): return list(map(int,input().split()))
def ls(): return list(map(int,list(input())))
def i(): return int(input())
from collections import defaultdict
graph = defaultdict(list)
n,m = li()
for _ in range(m):
x,y = li()
graph[x].append(y)
graph[y].append(x)
visited= [False]*(n+1)
flag = 1
for i in range(n+1):
if graph[i+1] :
graph[i+1].append(i+1)
graph[i+1].sort()
# print(graph)
for i in range(n):
if visited[i+1] == False:
visited[i+1] = True
for x in graph[i+1]:
if visited[x] == False:
visited[x] = True
# print(graph[x],graph[i+1])
if graph[x] != graph[i+1] :
flag = 0
break
if flag == 1:
print('YES')
else:
print('NO')
``` | instruction | 0 | 12,157 | 14 | 24,314 |
Yes | output | 1 | 12,157 | 14 | 24,315 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
# Problem: A. Bear and Friendship Condition
# Contest: Codeforces - VK Cup 2017 - Round 1
# URL: https://codeforces.com/problemset/problem/771/A
# Memory Limit: 256 MB
# Time Limit: 1000 ms
#
# KAPOOR'S
from sys import stdin, stdout
def INI():
return int(stdin.readline())
def INL():
return [int(_) for _ in stdin.readline().split()]
def INS():
return stdin.readline()
def MOD():
return pow(10,9)+7
def OPS(ans):
stdout.write(str(ans)+"\n")
def OPL(ans):
[stdout.write(str(_)+" ") for _ in ans]
stdout.write("\n")
def dfs(v,p=0):
V[v]=True
# print(v,p)
if p==0:
for _ in X[v]:
if not V[_]:
if not dfs(_,v):
return False
else:
for _ in X[v]:
if not V[_]:
if _ not in X[p]:
return False
if not dfs(_,v):
return False
return True
if __name__=="__main__":
n,m=INL()
X=[set() for _ in range(n+1)]
V=[False for _ in range(n+1)]
for _ in range(m):
u,v=INL()
X[u].add(v)
X[v].add(u)
for _ in range(1,n+1):
if not V[_]:
if not dfs(_):
OPS('NO')
break
else:
OPS('YES')
``` | instruction | 0 | 12,158 | 14 | 24,316 |
No | output | 1 | 12,158 | 14 | 24,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
n,m=map(int,input().split())
a=[[] for i in range(n+1)]
for i in range(m):
c,d=map(int,input().split())
a[c].append(d);a[d].append(c)
for i in range(1,n+1):
a[i].sort(reverse=True)
for i in range(1,n+1):
for j in a[i]:
if len(a[j])>=1:
del a[j][-1]
for k in a[j]:
if a[k][-1]!=i:
exit(print('NO'))
else:
del a[k][-1]
print('YES')
``` | instruction | 0 | 12,159 | 14 | 24,318 |
No | output | 1 | 12,159 | 14 | 24,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
from collections import defaultdict
class Graph:
def __init__(self,n):
self.graph = defaultdict(list)
self.vertices = n
self.visited = [False] * (n+1)
self.one = 0
self.others = []
def addEdge(self,fr,to):
self.graph[fr].append(to)
self.graph[to].append(fr)
def solve(self):
for i in range(1,self.vertices+1):
if(self.visited[i]==False):
self.visited[i]=True
Len = len(self.graph[i])
for j in self.graph[i]:
self.visited[j]=False
if(len(self.graph[j])!=Len):
return "NO"
return "YES"
n,m = map(int,input().split())
G = Graph(n)
for i in range(m):
a,b = map(int,input().split())
G.addEdge(a,b)
print(G.solve())
``` | instruction | 0 | 12,160 | 14 | 24,320 |
No | output | 1 | 12,160 | 14 | 24,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 β€ n β€ 150 000, <image>) β the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 β€ ai, bi β€ n, ai β bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
<image>
Submitted Solution:
```
from collections import defaultdict,deque
from sys import *
def bfs(graph,vis,node):
q=deque()
q.append(node)
vis[node]=0
while q:
s=q.popleft()
for i in graph[s]:
if vis[i]==1:
vis[i]=0
if len(graph[s])!=len(graph[i]):
return -1
q.append(i)
return 0
n,m=map(int,stdin.readline().split())
graph=defaultdict(list)
here=[0]*(n+1)
for i in range(m):
u,v=map(int,stdin.readline().split())
graph[u].append(v)
graph[v].append(u)
here[u]=1
here[v]=1
ver=0
for i in range(n):
if here[i]==0:
continue
ver=bfs(graph,here,i)
if ver==-1:
break
if ver==-1:
stdout.write("NO\n")
else:
stdout.write("YES\n")
``` | instruction | 0 | 12,161 | 14 | 24,322 |
No | output | 1 | 12,161 | 14 | 24,323 |
Provide a correct Python 3 solution for this coding contest problem.
D: Indecision-Indecision-
problem
Ebi-chan has been addicted to gal games lately, and her goal now is to capture two heroines at the same time.
Ebi-chan can use several events to increase her liking from the heroine, but only one heroine can be selected for each event. However, Ebi-chan does not forget to follow the heroine that she did not choose, so the liking from the other heroine can be increased to some extent. However, not all events can be done because events are expensive.
By the way, indecisive Ebi-chan is wondering which heroine to perform each event with (or neither). Ebi-chan thinks that it is meaningless if only one heroine has a high liking, but the other has a low liking, so the ideal choice is to maximize the liking from the heroine who does not have a high liking.
At this time, find the maximum value of the liking from the heroine who does not have the high liking. In other words, as a result of selecting the event and the target heroine, find the maximum value that can be considered as min \\ {A, B \\} when the favorability from the two heroines is A and B, respectively. Here, the total cost of the event you decide to do must not exceed your budget. Also, the initial value of favorability from each heroine is 0.
Input format
N C
a_1 b_1 c_1
...
a_N b_N c_N
The first line gives the number of candidate events N and the budget C, separated by blanks.
Line 1 + i (1 \ leq i \ leq N) contains the increment of favorability a_i of the heroine doing it, the increment of favorability b_i of the other heroine, and the cost c_i for the i-th event. Given with a space delimiter.
Constraint
* 1 \ leq N \ leq 100
* 1 \ leq C \ leq 100
* 1 \ leq b_i <a_i \ leq 100
* 1 \ leq c_i \ leq 100
Output format
Under the ideal selection in the question sentence, output the maximum value of the liking from the heroine who does not have the high liking in one line.
Input example 1
3 4
3 2 2
2 1 1
2 1 1
Output example 1
Five
It's best to have the first two events with one heroine and the last event with the other heroine.
Input example 2
3 3
3 2 2
2 1 1
2 1 1
Output example 2
Four
Example
Input
3 4
3 2 2
2 1 1
2 1 1
Output
5 | instruction | 0 | 12,445 | 14 | 24,890 |
"Correct Solution:
```
N, C = map(int, input().split())
events = []
for i in range(N):
events.append(list(map(int, input().split())))
def solve():
L = 250
dp = [[-10**18]*(L+1) for i in range(C+1)]
for j in range(C+1):
dp[j][0] = 0
for a, b, c in events:
for j in range(C-c, -1, -1):
for k in range(L+1):
if k + (b-a) <= 0:
dp[j+c][a-k-b] = max(dp[j+c][a-k-b], dp[j][k]+k+b)
else:
dp[j+c][k+b-a] = max(dp[j+c][k+b-a], dp[j][k]+a)
if k + (a-b) <= L:
dp[j+c][k+a-b] = max(dp[j+c][k+a-b], dp[j][k]+b)
ans = 0
for j in range(C+1):
ans = max(ans, max(dp[j]))
return ans
print(solve())
``` | output | 1 | 12,445 | 14 | 24,891 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
D: Indecision-Indecision-
problem
Ebi-chan has been addicted to gal games lately, and her goal now is to capture two heroines at the same time.
Ebi-chan can use several events to increase her liking from the heroine, but only one heroine can be selected for each event. However, Ebi-chan does not forget to follow the heroine that she did not choose, so the liking from the other heroine can be increased to some extent. However, not all events can be done because events are expensive.
By the way, indecisive Ebi-chan is wondering which heroine to perform each event with (or neither). Ebi-chan thinks that it is meaningless if only one heroine has a high liking, but the other has a low liking, so the ideal choice is to maximize the liking from the heroine who does not have a high liking.
At this time, find the maximum value of the liking from the heroine who does not have the high liking. In other words, as a result of selecting the event and the target heroine, find the maximum value that can be considered as min \\ {A, B \\} when the favorability from the two heroines is A and B, respectively. Here, the total cost of the event you decide to do must not exceed your budget. Also, the initial value of favorability from each heroine is 0.
Input format
N C
a_1 b_1 c_1
...
a_N b_N c_N
The first line gives the number of candidate events N and the budget C, separated by blanks.
Line 1 + i (1 \ leq i \ leq N) contains the increment of favorability a_i of the heroine doing it, the increment of favorability b_i of the other heroine, and the cost c_i for the i-th event. Given with a space delimiter.
Constraint
* 1 \ leq N \ leq 100
* 1 \ leq C \ leq 100
* 1 \ leq b_i <a_i \ leq 100
* 1 \ leq c_i \ leq 100
Output format
Under the ideal selection in the question sentence, output the maximum value of the liking from the heroine who does not have the high liking in one line.
Input example 1
3 4
3 2 2
2 1 1
2 1 1
Output example 1
Five
It's best to have the first two events with one heroine and the last event with the other heroine.
Input example 2
3 3
3 2 2
2 1 1
2 1 1
Output example 2
Four
Example
Input
3 4
3 2 2
2 1 1
2 1 1
Output
5
Submitted Solution:
```
N, C = map(int, input().split())
events = []
for i in range(N):
events.append(list(map(int, input().split())))
def solve():
L = 250
dp = [[0]*(L+1) for i in range(C+1)]
for j in range(C+1):
for k in range(L+1):
if k != 0:
dp[j][k] = -10**18
for a, b, c in events:
for j in range(C-c, -1, -1):
for k in range(L+1):
if k + (b-a) <= 0:
dp[j+c][-(k+b-a)] = max(dp[j+c][-(k+b-a)], dp[j][k]+k+b)
elif k + (a-b) <= L:
dp[j+c][k+a-b] = max(dp[j+c][k+a-b], dp[j][k] + b)
ans = 0
for j in range(C+1):
ans = max(ans, max(dp[j]))
return ans
print(solve())
``` | instruction | 0 | 12,446 | 14 | 24,892 |
No | output | 1 | 12,446 | 14 | 24,893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
D: Indecision-Indecision-
problem
Ebi-chan has been addicted to gal games lately, and her goal now is to capture two heroines at the same time.
Ebi-chan can use several events to increase her liking from the heroine, but only one heroine can be selected for each event. However, Ebi-chan does not forget to follow the heroine that she did not choose, so the liking from the other heroine can be increased to some extent. However, not all events can be done because events are expensive.
By the way, indecisive Ebi-chan is wondering which heroine to perform each event with (or neither). Ebi-chan thinks that it is meaningless if only one heroine has a high liking, but the other has a low liking, so the ideal choice is to maximize the liking from the heroine who does not have a high liking.
At this time, find the maximum value of the liking from the heroine who does not have the high liking. In other words, as a result of selecting the event and the target heroine, find the maximum value that can be considered as min \\ {A, B \\} when the favorability from the two heroines is A and B, respectively. Here, the total cost of the event you decide to do must not exceed your budget. Also, the initial value of favorability from each heroine is 0.
Input format
N C
a_1 b_1 c_1
...
a_N b_N c_N
The first line gives the number of candidate events N and the budget C, separated by blanks.
Line 1 + i (1 \ leq i \ leq N) contains the increment of favorability a_i of the heroine doing it, the increment of favorability b_i of the other heroine, and the cost c_i for the i-th event. Given with a space delimiter.
Constraint
* 1 \ leq N \ leq 100
* 1 \ leq C \ leq 100
* 1 \ leq b_i <a_i \ leq 100
* 1 \ leq c_i \ leq 100
Output format
Under the ideal selection in the question sentence, output the maximum value of the liking from the heroine who does not have the high liking in one line.
Input example 1
3 4
3 2 2
2 1 1
2 1 1
Output example 1
Five
It's best to have the first two events with one heroine and the last event with the other heroine.
Input example 2
3 3
3 2 2
2 1 1
2 1 1
Output example 2
Four
Example
Input
3 4
3 2 2
2 1 1
2 1 1
Output
5
Submitted Solution:
```
N, C = map(int, input().split())
events = []
for i in range(N):
events.append(list(map(int, input().split())))
dp = [[0]*201 for i in range(C+1)]
for j in range(C+1):
for k in range(-1000, 1001):
if k != 0:
dp[j][k] = -10**18
for a, b, c in events:
for j in range(C-c, -1, -1):
for k in range(-1000, 1001):
if k + (b-a) >= -100:
dp[j+c][k+b-a] = max(dp[j+c][k+b-a], dp[j][k] + a)
if k + (a-b) <= 100:
dp[j+c][k+a-b] = max(dp[j+c][k+a-b], dp[j][k] + b)
ans = 0
for j in range(C+1):
for k in range(-1000, 1001):
ans = max(ans, min(dp[j][k] + k, dp[j][k]))
print(ans)
``` | instruction | 0 | 12,447 | 14 | 24,894 |
No | output | 1 | 12,447 | 14 | 24,895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
D: Indecision-Indecision-
problem
Ebi-chan has been addicted to gal games lately, and her goal now is to capture two heroines at the same time.
Ebi-chan can use several events to increase her liking from the heroine, but only one heroine can be selected for each event. However, Ebi-chan does not forget to follow the heroine that she did not choose, so the liking from the other heroine can be increased to some extent. However, not all events can be done because events are expensive.
By the way, indecisive Ebi-chan is wondering which heroine to perform each event with (or neither). Ebi-chan thinks that it is meaningless if only one heroine has a high liking, but the other has a low liking, so the ideal choice is to maximize the liking from the heroine who does not have a high liking.
At this time, find the maximum value of the liking from the heroine who does not have the high liking. In other words, as a result of selecting the event and the target heroine, find the maximum value that can be considered as min \\ {A, B \\} when the favorability from the two heroines is A and B, respectively. Here, the total cost of the event you decide to do must not exceed your budget. Also, the initial value of favorability from each heroine is 0.
Input format
N C
a_1 b_1 c_1
...
a_N b_N c_N
The first line gives the number of candidate events N and the budget C, separated by blanks.
Line 1 + i (1 \ leq i \ leq N) contains the increment of favorability a_i of the heroine doing it, the increment of favorability b_i of the other heroine, and the cost c_i for the i-th event. Given with a space delimiter.
Constraint
* 1 \ leq N \ leq 100
* 1 \ leq C \ leq 100
* 1 \ leq b_i <a_i \ leq 100
* 1 \ leq c_i \ leq 100
Output format
Under the ideal selection in the question sentence, output the maximum value of the liking from the heroine who does not have the high liking in one line.
Input example 1
3 4
3 2 2
2 1 1
2 1 1
Output example 1
Five
It's best to have the first two events with one heroine and the last event with the other heroine.
Input example 2
3 3
3 2 2
2 1 1
2 1 1
Output example 2
Four
Example
Input
3 4
3 2 2
2 1 1
2 1 1
Output
5
Submitted Solution:
```
N, C = map(int, input().split())
events = []
for i in range(N):
events.append(list(map(int, input().split())))
def solve():
L = 150
dp = [[-10**18]*(L+1) for i in range(C+1)]
for j in range(C+1):
dp[j][0] = 0
for a, b, c in events:
for j in range(C-c, -1, -1):
for k in range(L+1):
if k + (b-a) <= 0:
dp[j+c][a-k-b] = max(dp[j+c][a-k-b], dp[j][k]+k+b)
else:
dp[j+c][k+b-a] = max(dp[j+c][k+b-a], dp[j][k]+a)
if k + (a-b) <= L:
dp[j+c][k+a-b] = max(dp[j+c][k+a-b], dp[j][k]+b)
ans = 0
for j in range(C+1):
ans = max(ans, max(dp[j]))
return ans
print(solve())
``` | instruction | 0 | 12,448 | 14 | 24,896 |
No | output | 1 | 12,448 | 14 | 24,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
D: Indecision-Indecision-
problem
Ebi-chan has been addicted to gal games lately, and her goal now is to capture two heroines at the same time.
Ebi-chan can use several events to increase her liking from the heroine, but only one heroine can be selected for each event. However, Ebi-chan does not forget to follow the heroine that she did not choose, so the liking from the other heroine can be increased to some extent. However, not all events can be done because events are expensive.
By the way, indecisive Ebi-chan is wondering which heroine to perform each event with (or neither). Ebi-chan thinks that it is meaningless if only one heroine has a high liking, but the other has a low liking, so the ideal choice is to maximize the liking from the heroine who does not have a high liking.
At this time, find the maximum value of the liking from the heroine who does not have the high liking. In other words, as a result of selecting the event and the target heroine, find the maximum value that can be considered as min \\ {A, B \\} when the favorability from the two heroines is A and B, respectively. Here, the total cost of the event you decide to do must not exceed your budget. Also, the initial value of favorability from each heroine is 0.
Input format
N C
a_1 b_1 c_1
...
a_N b_N c_N
The first line gives the number of candidate events N and the budget C, separated by blanks.
Line 1 + i (1 \ leq i \ leq N) contains the increment of favorability a_i of the heroine doing it, the increment of favorability b_i of the other heroine, and the cost c_i for the i-th event. Given with a space delimiter.
Constraint
* 1 \ leq N \ leq 100
* 1 \ leq C \ leq 100
* 1 \ leq b_i <a_i \ leq 100
* 1 \ leq c_i \ leq 100
Output format
Under the ideal selection in the question sentence, output the maximum value of the liking from the heroine who does not have the high liking in one line.
Input example 1
3 4
3 2 2
2 1 1
2 1 1
Output example 1
Five
It's best to have the first two events with one heroine and the last event with the other heroine.
Input example 2
3 3
3 2 2
2 1 1
2 1 1
Output example 2
Four
Example
Input
3 4
3 2 2
2 1 1
2 1 1
Output
5
Submitted Solution:
```
N, C = map(int, input().split())
events = []
for i in range(N):
events.append(list(map(int, input().split())))
def solve(t, c):
if c == 0:
return 0
dp = [0]*(c+1)
dp[0] = 0
for event in events:
v = event[t]; d = event[2]
for i in range(c-d-1, -1, -1):
dp[i+d] = max(dp[i+d], dp[i] + v)
return max(dp)
ans = 0
for i in range(C+1):
ans = max(ans, solve(0, i) + solve(1, C-i))
print(ans)
``` | instruction | 0 | 12,449 | 14 | 24,898 |
No | output | 1 | 12,449 | 14 | 24,899 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night.
It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.
Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
Input
The first line of the input contains integer n (1 β€ n β€ 100), where n β the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 β€ ti β€ 1000).
The last line contains integer T (1 β€ T β€ 1000) β the time interval during which the freebie was near the dormitory.
Output
Print a single integer β the largest number of people who will pass exam tomorrow because of the freebie visit.
Examples
Input
6
4 1 7 8 3 8
1
Output
3 | instruction | 0 | 12,793 | 14 | 25,586 |
Tags: binary search, brute force, implementation
Correct Solution:
```
read = lambda: map(int, input().split())
n = int(input())
a = sorted(read())
T = int(input())
ans = 0
j = 0
for i in range(n):
while j < n and a[j] - a[i] <= T:
j += 1
ans = max(ans, j - i)
print(ans)
``` | output | 1 | 12,793 | 14 | 25,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night.
It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.
Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
Input
The first line of the input contains integer n (1 β€ n β€ 100), where n β the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 β€ ti β€ 1000).
The last line contains integer T (1 β€ T β€ 1000) β the time interval during which the freebie was near the dormitory.
Output
Print a single integer β the largest number of people who will pass exam tomorrow because of the freebie visit.
Examples
Input
6
4 1 7 8 3 8
1
Output
3 | instruction | 0 | 12,794 | 14 | 25,588 |
Tags: binary search, brute force, implementation
Correct Solution:
```
n=int(input())
l=list(map(int,input().split()))
t=int(input())
l.sort()
mx=1
i=0
j=0
count=1
while j<n-1:
count=1
i=j+1
while i<n:
if l[i]-l[j]<=t:
count+=1
i+=1
else:
break
if count>mx:
mx=count
j+=1
print(mx)
``` | output | 1 | 12,794 | 14 | 25,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night.
It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.
Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
Input
The first line of the input contains integer n (1 β€ n β€ 100), where n β the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 β€ ti β€ 1000).
The last line contains integer T (1 β€ T β€ 1000) β the time interval during which the freebie was near the dormitory.
Output
Print a single integer β the largest number of people who will pass exam tomorrow because of the freebie visit.
Examples
Input
6
4 1 7 8 3 8
1
Output
3 | instruction | 0 | 12,795 | 14 | 25,590 |
Tags: binary search, brute force, implementation
Correct Solution:
```
n = int(input())
lst = list(map(int,input().split()))
t = int(input())
lst.sort()
res=0
from bisect import bisect
for i,x in enumerate(lst):
j=bisect(lst,x+t)
res=max(res,j-i)
print(res)
``` | output | 1 | 12,795 | 14 | 25,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night.
It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.
Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
Input
The first line of the input contains integer n (1 β€ n β€ 100), where n β the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 β€ ti β€ 1000).
The last line contains integer T (1 β€ T β€ 1000) β the time interval during which the freebie was near the dormitory.
Output
Print a single integer β the largest number of people who will pass exam tomorrow because of the freebie visit.
Examples
Input
6
4 1 7 8 3 8
1
Output
3 | instruction | 0 | 12,796 | 14 | 25,592 |
Tags: binary search, brute force, implementation
Correct Solution:
```
def halyava(lst, t):
count = 1
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if sorted(lst)[j] - sorted(lst)[i] <= t:
count = max(j - i + 1, count)
return count
n = int(input())
b = [int(x) for x in input().split()]
T = int(input())
print(halyava(b, T))
``` | output | 1 | 12,796 | 14 | 25,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night.
It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.
Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
Input
The first line of the input contains integer n (1 β€ n β€ 100), where n β the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 β€ ti β€ 1000).
The last line contains integer T (1 β€ T β€ 1000) β the time interval during which the freebie was near the dormitory.
Output
Print a single integer β the largest number of people who will pass exam tomorrow because of the freebie visit.
Examples
Input
6
4 1 7 8 3 8
1
Output
3 | instruction | 0 | 12,797 | 14 | 25,594 |
Tags: binary search, brute force, implementation
Correct Solution:
```
n=int(input())
l=list(map(int,input().split()))
t=int(input())
l.sort()
a=[]
i=0
j=0
while i<n:
while j<n and l[j]-l[i]<=t:
j+=1
a.append(j-i)
i+=1
print(max(a))
``` | output | 1 | 12,797 | 14 | 25,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night.
It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.
Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
Input
The first line of the input contains integer n (1 β€ n β€ 100), where n β the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 β€ ti β€ 1000).
The last line contains integer T (1 β€ T β€ 1000) β the time interval during which the freebie was near the dormitory.
Output
Print a single integer β the largest number of people who will pass exam tomorrow because of the freebie visit.
Examples
Input
6
4 1 7 8 3 8
1
Output
3 | instruction | 0 | 12,798 | 14 | 25,596 |
Tags: binary search, brute force, implementation
Correct Solution:
```
n = int(input())
v = list(map(int, input().split()))
t = int(input())
v.sort()
ret = 1
lef = 0
rit = 1
while rit < n:
while rit < n and v[rit] - v[lef] <= t:
rit = rit + 1
ret = max(ret, rit - lef)
lef = lef + 1
print(ret)
``` | output | 1 | 12,798 | 14 | 25,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a Γ b chairs β a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 β€ n β€ 10 000, 1 β€ a, b β€ 100) β the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | instruction | 0 | 12,931 | 14 | 25,862 |
Tags: *special, constructive algorithms
Correct Solution:
```
n,a,b=(int(z) for z in input().split())
if a*b<n:
print(-1)
else:
i=1
s=''
if b%2==1:
while i<=n:
if i%b!=0:
s+=str(i)+' '
else:
print(s+str(i))
s=''
i+=1
while i<=a*b:
if i%b!=0:
s+='0 '
else:
print(s+'0')
s=''
i+=1
else:
i=1
r=1
s=''
while i<=n:
if (i%b!=0 and r==1) or ((i-1)%b!=0 and r==-1):
s+=str(i)+' '
i+=r
else:
print(s+str(i))
s=''
i+=b
r*=-1
if i>n>i+r*b:
while (i-1)%b!=0:
if i <=n:
s+=str(i)+' '
else:
s+='0 '
i-=1
print (s+str(i))
s=''
i+=b
while i <=a*b:
if i%b!=0:
s+='0 '
else:
print (s+'0')
s=''
i+=1
``` | output | 1 | 12,931 | 14 | 25,863 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a Γ b chairs β a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 β€ n β€ 10 000, 1 β€ a, b β€ 100) β the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | instruction | 0 | 12,932 | 14 | 25,864 |
Tags: *special, constructive algorithms
Correct Solution:
```
n, a, b = map(int, input().split())
t = 1
if a*b < n:
print(-1)
else:
if b%2:
for i in range(a):
ar = [x+i*b for x in range(1, b+1)]
for j in range(b):
if ar[j] <= n:
print(ar[j], end = ' ')
else:
print(0, end = ' ')
print()
else:
for i in range(a):
if i % 2 == 0:
ar = [x+i*b for x in range(1, b+1)]
else:
ar = [b+i*b] + [x+i*b for x in range(1, b)]
for j in range(b):
if ar[j] <= n:
print(ar[j], end = ' ')
else:
print(0, end = ' ')
print()
``` | output | 1 | 12,932 | 14 | 25,865 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a Γ b chairs β a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 β€ n β€ 10 000, 1 β€ a, b β€ 100) β the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | instruction | 0 | 12,933 | 14 | 25,866 |
Tags: *special, constructive algorithms
Correct Solution:
```
from itertools import combinations, accumulate, groupby, count
from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from os import *
from re 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 , Then you probably don't know him !
--Try & again try
"""
##################################################---START-CODING---###############################################
n, a, b = zzz()
lst = [[0 for i in range(b)]for i in range(a)]
lst[0][0] = 1
cnt1, cnt2 = 3, 2
for i in range(1, b):
if lst[0][i - 1] % 2:
lst[0][i] = cnt2
cnt2 += 2
else:
lst[0][i] = cnt1
cnt1 += 2
for i in range(1, a):
for j in range(b):
if lst[i - 1][j] % 2:
lst[i][j] = cnt2
cnt2 += 2
else:
lst[i][j] = cnt1
cnt1 += 2
if max(cnt1, cnt2) - 2 < n:
exit(print(-1))
for i in range(a):
for j in range(b):
if lst[i][j] > n:
lst[i][j] = 0
for i in lst:
print(*i)
``` | output | 1 | 12,933 | 14 | 25,867 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a Γ b chairs β a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 β€ n β€ 10 000, 1 β€ a, b β€ 100) β the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | instruction | 0 | 12,934 | 14 | 25,868 |
Tags: *special, constructive algorithms
Correct Solution:
```
import itertools
def grouper(n, iterable):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk
(n,a,b)= [int(x) for x in input().split()]
possible = True
t = []
if n > a*b:
possible = False
result = -1
print (result)
if possible:
for x in range (1,a+1):
t.append([])
for i in range (1,b+1):
s = ((x-1)*b + i)
if x > 1:
if s%2 != 0 and t[x-2][i-1]%2 != 0:
s += 1
elif s%2 == 0 and t[x-2][i-1]%2 == 0:
s -= 1
if s > n:
s = 0
t[x-1].append(s)
v = []
for d in range (0, a):
v += t[d]
for chunk in grouper(b, v):
print (" ".join(str(u) for u in chunk))
``` | output | 1 | 12,934 | 14 | 25,869 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a Γ b chairs β a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 β€ n β€ 10 000, 1 β€ a, b β€ 100) β the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | instruction | 0 | 12,935 | 14 | 25,870 |
Tags: *special, constructive algorithms
Correct Solution:
```
A = input().split()
a = [[0] * int(A[2]) for i in range(int(A[1]))]
count = 1
if int(A[1]) * int(A[2]) < int(A[0]):
print(-1)
else:
for i in range(int(A[1])):
if i % 2 == 0:
for j in range(int(A[2])-1, -1, -1):
a[i][j] = count
count += 1
if count > int(A[0]):
break
else:
for j in range(int(A[2])):
a[i][j] = count
count += 1
if count > int(A[0]):
break
if count > int(A[0]):
break
for row in a:
print(' '.join([str(elem) for elem in row]))
``` | output | 1 | 12,935 | 14 | 25,871 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a Γ b chairs β a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 β€ n β€ 10 000, 1 β€ a, b β€ 100) β the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | instruction | 0 | 12,936 | 14 | 25,872 |
Tags: *special, constructive algorithms
Correct Solution:
```
n, a, b = map(int, input().split())
if n > a * b:
print(-1)
else:
c = [[0 for j in range(b)] for i in range(a)]
p = 1
i = 0
j = 0
while p <= n:
if i % 2 == 0:
for j in range(b):
if p > n:
break
c[i][j] = p
p += 1
else:
for j in reversed(range(b)):
if p > n:
break
c[i][j] = p
p += 1
i += 1
for i in range(a):
print(*c[i])
``` | output | 1 | 12,936 | 14 | 25,873 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a Γ b chairs β a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
Input
The first line of the input contains three integers n, a and b (1 β€ n β€ 10 000, 1 β€ a, b β€ 100) β the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
Output
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
Examples
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
Note
In the first sample there are many other possible solutions. For example,
3 2
0 1
and
2 1
3 0
The following assignment
3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats. | instruction | 0 | 12,937 | 14 | 25,874 |
Tags: *special, constructive algorithms
Correct Solution:
```
n, a, b = map(int, input().split())
if (a * b < n):
print(-1)
exit(0)
q = [[0] * 102 for i in range(102)]
i = 0
j = 0
k = n - 1
while (n > 0):
q[i][j] = n
n -= 1
if (j == b - 1 and i % 2 == 0):
i += 1
else:
if (j == 0 and i % 2 == 1):
i += 1
else:
if (i % 2 == 0):
j += 1
else:
j -= 1
for i in range(a):
for j in range(b):
print(q[i][j], end = ' ')
print()
``` | output | 1 | 12,937 | 14 | 25,875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.