message stringlengths 2 22.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 16 109k | cluster float64 1 1 | __index_level_0__ int64 32 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It is well known that Berland has n cities, which form the Silver ring — cities i and i + 1 (1 ≤ i < n) are connected by a road, as well as the cities n and 1. The goverment have decided to build m new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should be a curve which lies inside or outside the ring. New roads will have no common points with the ring (except the endpoints of the road).
Now the designers of the constructing plan wonder if it is possible to build the roads in such a way that no two roads intersect (note that the roads may intersect at their endpoints). If it is possible to do, which roads should be inside the ring, and which should be outside?
Input
The first line contains two integers n and m (4 ≤ n ≤ 100, 1 ≤ m ≤ 100). Each of the following m lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). No two cities will be connected by more than one road in the list. The list will not contain the roads which exist in the Silver ring.
Output
If it is impossible to build the roads in such a way that no two roads intersect, output Impossible. Otherwise print m characters. i-th character should be i, if the road should be inside the ring, and o if the road should be outside the ring. If there are several solutions, output any of them.
Examples
Input
4 2
1 3
2 4
Output
io
Input
6 3
1 3
3 5
5 1
Output
ooo
Submitted Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, m = map(int, input().split())
edges = [tuple(map(lambda x: int(x) - 1, input().split())) for _ in range(m)]
ans = ['i'] * m
for i, (u, v) in enumerate(edges):
in_cross = out_cross = 0
for j in range(i):
if u in edges[j] or v in edges[j]:
continue
if (1 if u <= edges[j][0] <= v else 0) + (1 if u <= edges[j][1] <= v else 0) == 1:
if ans[j] == 'i':
in_cross += 1
else:
out_cross += 1
if in_cross == 0:
continue
elif out_cross == 0:
ans[i] = 'o'
else:
print('Impossible')
print(*ans, sep='')
``` | instruction | 0 | 56,656 | 1 | 113,312 |
No | output | 1 | 56,656 | 1 | 113,313 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1 | instruction | 0 | 56,668 | 1 | 113,336 |
Tags: graphs
Correct Solution:
```
n = int(input())
t = [0] + list(map(int, input().split()))
a = [0] + list(map(int, input().split()))
res, cnt = [], [0] * (n + 1)
for i in a:
cnt[i] += 1
for i in range(1, n+1):
if t[i] == 0:
continue
curr_res = [i]
x = a[i]
while cnt[x] == 1:
curr_res.append(x)
x = a[x]
if len(curr_res) > len(res):
res = curr_res[:]
res.reverse()
print(len(res))
print(*res)
``` | output | 1 | 56,668 | 1 | 113,337 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1 | instruction | 0 | 56,669 | 1 | 113,338 |
Tags: graphs
Correct Solution:
```
n = int(input())
t = [0] + list(map(int, input().split()))
a = [0] + list(map(int, input().split()))
ans, cnt = [], [0 for i in range(n + 1)]
for i in a:
cnt[i] += 1
for i in range(1, n + 1):
if t[i] == 1:
crt = [i]
x = a[i]
while cnt[x] == 1:
crt.append(x)
x = a[x]
if len(crt) > len(ans):
ans = crt[:]
ans.reverse()
print(len(ans))
print(' '.join(map(str, ans)))
# Made By Mostafa_Khaled
``` | output | 1 | 56,669 | 1 | 113,339 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1 | instruction | 0 | 56,670 | 1 | 113,340 |
Tags: graphs
Correct Solution:
```
n = int(input())
t = [0] + list(map(int, input().split()))
a = [0] + list(map(int, input().split()))
ans, cnt = [], [0 for i in range(n + 1)]
for i in a:
cnt[i] += 1
for i in range(1, n + 1):
if t[i] == 1:
crt = [i]
x = a[i]
while cnt[x] == 1:
crt.append(x)
x = a[x]
if len(crt) > len(ans):
ans = crt[:]
ans.reverse()
print(len(ans))
print(' '.join(map(str, ans)))
``` | output | 1 | 56,670 | 1 | 113,341 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1 | instruction | 0 | 56,671 | 1 | 113,342 |
Tags: graphs
Correct Solution:
```
import sys
def Z(s):
return int(s)-1
n=int(sys.stdin.readline())
Hotels=[False]*(n)
Rep=[0]*(n+1)
Chains=[]
Type=list(map(int,sys.stdin.readline().split()))
for i in range(n):
if(Type[i]==1):
Hotels[i]=True
A=list(map(Z,sys.stdin.readline().split()))
for item in A:
Rep[item]+=1
for i in range(n):
if(Hotels[i]):
Chains.append([i])
x=A[i]
if(x==-1):
continue
while(A[x]!=-1 and Rep[x]<=1):
Chains[-1].append(x)
x=A[x]
if(Rep[x]<=1):
Chains[-1].append(x)
if(n==1):
print(1)
print(1)
else:
X=max(Chains,key=len)
sys.stdout.write(str(len(X))+"\n")
sys.stdout.write(str(X[-1]+1))
for i in range(len(X)-2,-1,-1):
sys.stdout.write(" "+str(X[i]+1))
``` | output | 1 | 56,671 | 1 | 113,343 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1 | instruction | 0 | 56,672 | 1 | 113,344 |
Tags: graphs
Correct Solution:
```
n = int(input())
input_types = input().split(" ")
types = [int(i) for i in input_types]
input_vertex = input().split(" ")
prev = [0 for i in range(n)]
cntFrom =[0 for i in range(n)]
for i in range(n):
prev[i] = int(input_vertex[i])
prev[i] -= 1
if (prev[i] != -1):
cntFrom[prev[i]] += 1
ans = []
for i in range(n):
if types[i] == 1:
curV = i
cur = []
while prev[curV] != -1 and cntFrom[prev[curV]] <= 1:
cur.append(curV)
curV = prev[curV]
cur.append(curV)
if len(ans) < len(cur):
ans = cur
ans_alt = [str(i + 1) for i in ans[::-1]]
print(len(ans_alt))
print(' '.join(ans_alt))
``` | output | 1 | 56,672 | 1 | 113,345 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1 | instruction | 0 | 56,673 | 1 | 113,346 |
Tags: graphs
Correct Solution:
```
#!/usr/bin/python3
def readln(): return tuple(map(int, input().split()))
n, = readln()
t = (-1,) + readln()
v = (0,) + readln()
cnt = [0] * (n + 1)
for i in range(1, n + 1):
cnt[v[i]] += 1
ans = []
for i in range(1, n + 1):
if t[i] == 1:
j = i
tmp = [i]
while(t[v[j]] == 0) and cnt[v[j]] == 1:
j = v[j]
tmp.append(j)
if(len(tmp) > len(ans)):
ans = tmp
print(len(ans))
print(*tuple(reversed(ans)))
``` | output | 1 | 56,673 | 1 | 113,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1 | instruction | 0 | 56,674 | 1 | 113,348 |
Tags: graphs
Correct Solution:
```
from collections import defaultdict
'''
from obhect ai-> i there is a path that exists
'''
blanc=[]
g=defaultdict(list)
n=int(input())
type=list(map(int,input().strip().split()))
path=list(map(int,input().strip().split()))
path=list(map(lambda s:s-1,path))
ans=[]
deg=[0]*(n)
for i in path:
if i!=-1:
deg[i]+=1
for i in range(n):
t=i
if type[i]==1:
cur=[]
while path[t]!=-1 and deg[path[t]]<=1:
cur.append(t)
t=path[t]
cur.append(t)
ans=max(ans,cur,key=len)
ans=list(map(lambda s:s+1,ans))
print(len(ans))
print(*ans[::-1])
``` | output | 1 | 56,674 | 1 | 113,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1 | instruction | 0 | 56,675 | 1 | 113,350 |
Tags: graphs
Correct Solution:
```
import sys
def solve():
n = int(input())
types = list(map(int, input().split()))
a = list(map(int, input().split()))
res = list()
count = [0] * (n + 1)
for val in a:
count[val-1]+=1
for i in range(n):
if types[i] == 1:
temp = list()
cur = i
while True:
if count[cur] > 1 or cur < 0: break
temp.append(cur + 1)
cur = a[cur] - 1
if len(temp) > len(res):
res = temp
print(len(res))
return ' '.join(map(str, res[::-1]))
# adj = [list() for _ in range(n)]
# visited = [0] * (n + 1)
# best = -1
# start = -1
# bestlen = 0
# for i in range(n):
# if a[i] > 0: adj[a[i] - 1].append(i)
# # counter = 0
# for i in range(n):
# if visited[i] == 0:
# cur = i
# # temp = list()
# # temp.append(cur)
# temp = 1
# visited[cur] += 1
# while len(adj[cur]) == 1:
# # print(cur)
# if len(adj[cur]) > 0 and adj[cur][0] == cur: break
# cur = adj[cur][0]
# # temp.append(cur)
# visited[cur]+=1
# temp+=1
# # if counter == 10000: return - 1
# if types[cur] == 1 and temp > bestlen:
# best = cur
# bestlen = temp
# start = i
# res = list()
# while True:
# res.append(best)
# if best == start: break
# next = a[best] - 1
# best = next
# res = res[::-1]
# for i in range(len(res)): res[i] += 1
# print(len(res))
# return ' '.join(map(str, res))
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())
``` | output | 1 | 56,675 | 1 | 113,351 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1
Submitted Solution:
```
n = int(input())
a, b = [0] + list(map(int, input().split())), [0] + list(map(int, input().split()))
ans, p = [], [0] * (n + 1)
for i in b:
p[i] += 1
for i in range(1, n + 1):
if a[i] == 1:
t = [i]
x = b[i]
while p[x] == 1:
t.append(x)
x = b[x]
if len(t) > len(ans): ans = t[:]
ans.reverse()
print(len(ans))
print(' '.join(str(x) for x in ans))
``` | instruction | 0 | 56,676 | 1 | 113,352 |
Yes | output | 1 | 56,676 | 1 | 113,353 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1
Submitted Solution:
```
import sys
n = int(input())
type = input().split()
fa = list(map(int, input().split()))
degree = [0] * (n+1)
for i in fa:
degree[i]+=1
type = [0] + type
fa= [0] + fa
max=0
maxi=0
for i in range(1, n+1):
if type[i] == '1': # it's hotel
cnt = 0
cur=fa[i]
while not (cur==0 or type[cur] == '1' or degree[cur]>1):
cnt+=1
cur=fa[cur]
if(max <= cnt):
max=cnt
maxi=i
print(max+1)
ans = []
cur=maxi
while not(not cur or type[cur] == '1' and cur!=maxi or degree[cur]>1):
ans.append(cur)
cur=fa[cur]
print(*ans[::-1])
``` | instruction | 0 | 56,677 | 1 | 113,354 |
Yes | output | 1 | 56,677 | 1 | 113,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1
Submitted Solution:
```
import sys
def solve():
n = int(input())
types = list(map(int, input().split()))
a = list(map(int, input().split()))
res = list()
count = [0] * (n + 1)
for val in a:
count[val-1]+=1
for i in range(n):
if types[i] == 1:
temp = list()
cur = i
while True:
if count[cur] > 1 or cur < 0: break
temp.append(cur + 1)
cur = a[cur] - 1
if len(temp) > len(res):
res = temp
print(len(res))
return ' '.join(map(str, res[::-1]))
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())
``` | instruction | 0 | 56,678 | 1 | 113,356 |
Yes | output | 1 | 56,678 | 1 | 113,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1
Submitted Solution:
```
n = int(input())
t = [0] + list(map(int, input().split()))
a = [0] + list(map(int, input().split()))
ans, cnt = [], [0 for i in range(n + 1)]
for i in a:
cnt[i] += 1
for i in range(1, n + 1):
if t[i] == 1:
crt = [i]
x = a[i]
while cnt[x] == 1:
crt.insert(0, x)
x = a[x]
if len(t) > len(ans):
ans = crt[:]
print(len(ans))
print(' '.join(map(str, ans)))
``` | instruction | 0 | 56,679 | 1 | 113,358 |
No | output | 1 | 56,679 | 1 | 113,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1
Submitted Solution:
```
import sys
def Z(s):
return int(s)-1
n=int(sys.stdin.readline())
Hotels=[False]*(n)
Rep=[0]*(n)
Chains=[]
Type=list(map(int,sys.stdin.readline().split()))
for i in range(n):
if(Type[i]==1):
Hotels[i]=True
A=list(map(Z,sys.stdin.readline().split()))
for item in A:
Rep[item]+=1
for i in range(n):
if(Hotels[i]):
Chains.append([i])
x=A[i]
if(x==-1):
continue
while(A[x]!=-1 and Rep[x]<=1):
Chains[-1].append(x)
x=A[x]
if(Rep[x]<=1):
Chains[-1].append(x)
if(n==1):
print(1)
print(1)
else:
X=max(Chains,key=len)
sys.stdout.write(str(len(X))+"\n")
sys.stdout.write(str(X[-1]+1))
for i in range(len(X)-2,-1,-1):
sys.stdout.write(" "+str(X[i]+1))
``` | instruction | 0 | 56,680 | 1 | 113,360 |
No | output | 1 | 56,680 | 1 | 113,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1
Submitted Solution:
```
n = int(input())
t = list(map(int, input().split()))
a = list(map(int, input().split()))
cnt = list([0 for _ in range(n)])
for i in a:
cnt[i - 1] += 1
def func(x):
ans = [x + 1]
x = a[x] - 1
while x >= 0 and t[x] == 0 and cnt[x] == 1:
ans.insert(0, x + 1)
x = a[x] - 1
return ans
ans = []
for i in range(n):
if t[i] == 1:
tmp = func(i)
if len(tmp) > len(ans):
ans = tmp
print(len(ans))
print(' '.join(map(str, ans)))
``` | instruction | 0 | 56,681 | 1 | 113,362 |
No | output | 1 | 56,681 | 1 | 113,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions:
1. Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel.
2. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1.
3. The path contains as many objects as possible (k is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of objects.
The second line contains n space-separated integers type1, type2, ..., typen — the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.
The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ n) — the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.
Output
In the first line print k — the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk — the path. If there are multiple solutions, you can print any of them.
Examples
Input
5
0 0 0 0 1
0 1 2 3 4
Output
5
1 2 3 4 5
Input
5
0 0 1 0 1
0 1 2 2 4
Output
2
4 5
Input
4
1 0 0 0
2 3 4 2
Output
1
1
Submitted Solution:
```
from collections import defaultdict
'''
from obhect ai-> i there is a path that exists
'''
blanc=[]
g=defaultdict(list)
n=int(input())
type=list(map(int,input().strip().split()))
path=list(map(int,input().strip().split()))
path=list(map(lambda s:s-1,path))
ans=[]
deg=[0]*(n)
for i in path:
deg[i]+=1
for i in range(n):
t=i
if type[i]==1:
cur=[t]
while path[t]!=-1 and deg[path[t]]<=1:
t=path[t]
cur.append(t)
ans=max(ans,cur,key=len)
ans=list(map(lambda s:s+1,ans))
print(len(ans))
print(*ans[::-1])
``` | instruction | 0 | 56,682 | 1 | 113,364 |
No | output | 1 | 56,682 | 1 | 113,365 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the northwestern intersection, and the walk starts from here.
Hereafter, the ath intersection from the north and the bth intersection from the west are represented by (a, b). For example, the intersection where Taro's house is located is (1, 1).
<image>
Figure: JOI town map (for H = 3, W = 4). The top of the figure corresponds to the north and the left corresponds to the west.
Taro thought that it would be more interesting if the walking route was different every day, so he wrote the letters "east" or "south" at the H x W intersections from (1, 1) to (H, W). , I decided to take a walk every day according to the following rules.
* If you are at an intersection with letters, rewrite the letters from "east" to "south" and "south" to "east", and the direction of the originally written letters. Proceed to the next intersection at.
* End the walk when you reach the easternmost or southernmost road.
After thinking about this plan, Taro was wondering what route he would take in his future walks. For Taro, he predicted the route for Taro's Nth walk. Create a program to do.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, three positive integers are separated by blanks. These are the values of the three numbers H, W, N in the problem statement. H, W, N are 1 ≤ H ≤, respectively. 1000, 1 ≤ W ≤ 1000, 1 ≤ N ≤ 10000000 = 107. From the 2nd line to H + 1st line, W integers are written separated by blanks. Represents the information of the character written at the intersection first. If the jth integer of i + 1st line is 0, the character written at the intersection (i, j) is "south", and if it is 1, the intersection Indicates that the character written in (i, j) is "east".
Of the scoring data, 30% of the points are satisfied with H ≤ 100, W ≤ 100, and N ≤ 1000.
When H, W, N are all 0, it indicates the end of input. The number of data sets does not exceed 10.
output
Output in the following format for each data set.
When the intersection where Taro finishes the walk in the Nth walk is (i, j), output i and j separated by a blank in this order.
Example
Input
3 4 3
1 0 1 1
0 1 0 0
1 0 1 0
0 0 0
Output
1 5 | instruction | 0 | 57,092 | 1 | 114,184 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7
while True:
H, W, N = MAP()
if H == W == H == 0:
break
grid = list2d(H, W, 0)
for i in range(H):
row = LIST()
for j in range(W):
grid[i][j] = row[j]
# dp[i][j] := (i, j)のマスをN回目の前までに何回通るか
dp = list2d(H+1, W+1, 0)
dp[0][0] = N - 1
for i in range(H):
for j in range(W):
# 通る回数が偶数なら半分ずつ
if dp[i][j] % 2 == 0:
dp[i+1][j] += dp[i][j] // 2
dp[i][j+1] += dp[i][j] // 2
else:
# 通る回数が奇数なら、元のグリッドの状態に応じて1回多く行く方が決まる
if grid[i][j] == 0:
dp[i+1][j] += dp[i][j] // 2 + 1
dp[i][j+1] += dp[i][j] // 2
else:
dp[i+1][j] += dp[i][j] // 2
dp[i][j+1] += dp[i][j] // 2 + 1
# N-1回終了時の状態にグリッドを更新
for i in range(H):
for j in range(W):
grid[i][j] ^= dp[i][j]
grid[i][j] &= 1
# N回目の散歩をシミュレーション
i = j = 0
while i < H and j < W:
if grid[i][j] == 0:
i += 1
else:
j += 1
print(i+1, j+1)
``` | output | 1 | 57,092 | 1 | 114,185 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the northwestern intersection, and the walk starts from here.
Hereafter, the ath intersection from the north and the bth intersection from the west are represented by (a, b). For example, the intersection where Taro's house is located is (1, 1).
<image>
Figure: JOI town map (for H = 3, W = 4). The top of the figure corresponds to the north and the left corresponds to the west.
Taro thought that it would be more interesting if the walking route was different every day, so he wrote the letters "east" or "south" at the H x W intersections from (1, 1) to (H, W). , I decided to take a walk every day according to the following rules.
* If you are at an intersection with letters, rewrite the letters from "east" to "south" and "south" to "east", and the direction of the originally written letters. Proceed to the next intersection at.
* End the walk when you reach the easternmost or southernmost road.
After thinking about this plan, Taro was wondering what route he would take in his future walks. For Taro, he predicted the route for Taro's Nth walk. Create a program to do.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, three positive integers are separated by blanks. These are the values of the three numbers H, W, N in the problem statement. H, W, N are 1 ≤ H ≤, respectively. 1000, 1 ≤ W ≤ 1000, 1 ≤ N ≤ 10000000 = 107. From the 2nd line to H + 1st line, W integers are written separated by blanks. Represents the information of the character written at the intersection first. If the jth integer of i + 1st line is 0, the character written at the intersection (i, j) is "south", and if it is 1, the intersection Indicates that the character written in (i, j) is "east".
Of the scoring data, 30% of the points are satisfied with H ≤ 100, W ≤ 100, and N ≤ 1000.
When H, W, N are all 0, it indicates the end of input. The number of data sets does not exceed 10.
output
Output in the following format for each data set.
When the intersection where Taro finishes the walk in the Nth walk is (i, j), output i and j separated by a blank in this order.
Example
Input
3 4 3
1 0 1 1
0 1 0 0
1 0 1 0
0 0 0
Output
1 5 | instruction | 0 | 57,093 | 1 | 114,186 |
"Correct Solution:
```
def solve():
while True:
h,w,n = map(int,input().split())
if not h: break
sss = [[1 if s == "1" else 0 for s in input().split()] for i in range(h)]
dp = [[0 for i in range(w + 1)] for j in range(h + 1)]
dp[0][0] = n - 1
for x in range(h):
for y in range(w):
a = dp[x][y]
if sss[x][y]:
if a % 2:
dp[x + 1][y] += a // 2
dp[x][y + 1] += a // 2 + 1
else:
dp[x + 1][y] += a // 2
dp[x][y + 1] += a // 2
else:
if a % 2:
dp[x + 1][y] += a // 2 + 1
dp[x][y + 1] += a // 2
else:
dp[x + 1][y] += a // 2
dp[x][y + 1] += a // 2
sss[x][y] = (sss[x][y] + dp[x][y]) % 2
# print(sss)
# print(dp)
x = y = 0
while x < h and y < w:
if sss[x][y]:
y += 1
else:
x += 1
print(x + 1,y + 1)
# print(sss)
solve()
``` | output | 1 | 57,093 | 1 | 114,187 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the northwestern intersection, and the walk starts from here.
Hereafter, the ath intersection from the north and the bth intersection from the west are represented by (a, b). For example, the intersection where Taro's house is located is (1, 1).
<image>
Figure: JOI town map (for H = 3, W = 4). The top of the figure corresponds to the north and the left corresponds to the west.
Taro thought that it would be more interesting if the walking route was different every day, so he wrote the letters "east" or "south" at the H x W intersections from (1, 1) to (H, W). , I decided to take a walk every day according to the following rules.
* If you are at an intersection with letters, rewrite the letters from "east" to "south" and "south" to "east", and the direction of the originally written letters. Proceed to the next intersection at.
* End the walk when you reach the easternmost or southernmost road.
After thinking about this plan, Taro was wondering what route he would take in his future walks. For Taro, he predicted the route for Taro's Nth walk. Create a program to do.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, three positive integers are separated by blanks. These are the values of the three numbers H, W, N in the problem statement. H, W, N are 1 ≤ H ≤, respectively. 1000, 1 ≤ W ≤ 1000, 1 ≤ N ≤ 10000000 = 107. From the 2nd line to H + 1st line, W integers are written separated by blanks. Represents the information of the character written at the intersection first. If the jth integer of i + 1st line is 0, the character written at the intersection (i, j) is "south", and if it is 1, the intersection Indicates that the character written in (i, j) is "east".
Of the scoring data, 30% of the points are satisfied with H ≤ 100, W ≤ 100, and N ≤ 1000.
When H, W, N are all 0, it indicates the end of input. The number of data sets does not exceed 10.
output
Output in the following format for each data set.
When the intersection where Taro finishes the walk in the Nth walk is (i, j), output i and j separated by a blank in this order.
Example
Input
3 4 3
1 0 1 1
0 1 0 0
1 0 1 0
0 0 0
Output
1 5 | instruction | 0 | 57,094 | 1 | 114,188 |
"Correct Solution:
```
def solve():
while True:
h,w,n = map(int,input().split())
if not h: break
mp = [[int(s) for s in input().split()] for i in range(h)]
dp = [[0 for i in range(w + 1)] for j in range(h + 1)]
dp[0][0] = n - 1
for x in range(h):
dpx = dp[x]
dpxp = dp[x + 1]
mpx = mp[x]
for y in range(w):
a = dpx[y]
b = mpx[y]
if b:
if a % 2:
dpxp[y] += a // 2
dpx[y + 1] += a // 2 + 1
else:
dpxp[y] += a // 2
dpx[y + 1] += a // 2
else:
if a % 2:
dpxp[y] += a // 2 + 1
dpx[y + 1] += a // 2
else:
dpxp[y] += a // 2
dpx[y + 1] += a // 2
mpx[y] = (a + b) % 2
x = y = 0
while x < h and y < w:
if mp[x][y]:
y += 1
else:
x += 1
print(x + 1,y + 1)
solve()
``` | output | 1 | 57,094 | 1 | 114,189 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the northwestern intersection, and the walk starts from here.
Hereafter, the ath intersection from the north and the bth intersection from the west are represented by (a, b). For example, the intersection where Taro's house is located is (1, 1).
<image>
Figure: JOI town map (for H = 3, W = 4). The top of the figure corresponds to the north and the left corresponds to the west.
Taro thought that it would be more interesting if the walking route was different every day, so he wrote the letters "east" or "south" at the H x W intersections from (1, 1) to (H, W). , I decided to take a walk every day according to the following rules.
* If you are at an intersection with letters, rewrite the letters from "east" to "south" and "south" to "east", and the direction of the originally written letters. Proceed to the next intersection at.
* End the walk when you reach the easternmost or southernmost road.
After thinking about this plan, Taro was wondering what route he would take in his future walks. For Taro, he predicted the route for Taro's Nth walk. Create a program to do.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, three positive integers are separated by blanks. These are the values of the three numbers H, W, N in the problem statement. H, W, N are 1 ≤ H ≤, respectively. 1000, 1 ≤ W ≤ 1000, 1 ≤ N ≤ 10000000 = 107. From the 2nd line to H + 1st line, W integers are written separated by blanks. Represents the information of the character written at the intersection first. If the jth integer of i + 1st line is 0, the character written at the intersection (i, j) is "south", and if it is 1, the intersection Indicates that the character written in (i, j) is "east".
Of the scoring data, 30% of the points are satisfied with H ≤ 100, W ≤ 100, and N ≤ 1000.
When H, W, N are all 0, it indicates the end of input. The number of data sets does not exceed 10.
output
Output in the following format for each data set.
When the intersection where Taro finishes the walk in the Nth walk is (i, j), output i and j separated by a blank in this order.
Example
Input
3 4 3
1 0 1 1
0 1 0 0
1 0 1 0
0 0 0
Output
1 5 | instruction | 0 | 57,095 | 1 | 114,190 |
"Correct Solution:
```
def solve():
while True:
h,w,n = map(int,input().split())
if not h: break
sss = [[1 if s == "1" else 0 for s in input().split()] for i in range(h)]
dp = [[0 for i in range(w + 1)] for j in range(h + 1)]
dp[0][0] = n - 1
for x in range(h):
for y in range(w):
a = dp[x][y]
b = sss[x][y]
if b:
if a % 2:
dp[x + 1][y] += a // 2
dp[x][y + 1] += a // 2 + 1
else:
dp[x + 1][y] += a // 2
dp[x][y + 1] += a // 2
else:
if a % 2:
dp[x + 1][y] += a // 2 + 1
dp[x][y + 1] += a // 2
else:
dp[x + 1][y] += a // 2
dp[x][y + 1] += a // 2
sss[x][y] = (a + b) % 2
# print(sss)
# print(dp)
x = y = 0
while x < h and y < w:
if sss[x][y]:
y += 1
else:
x += 1
print(x + 1,y + 1)
# print(sss)
solve()
``` | output | 1 | 57,095 | 1 | 114,191 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the northwestern intersection, and the walk starts from here.
Hereafter, the ath intersection from the north and the bth intersection from the west are represented by (a, b). For example, the intersection where Taro's house is located is (1, 1).
<image>
Figure: JOI town map (for H = 3, W = 4). The top of the figure corresponds to the north and the left corresponds to the west.
Taro thought that it would be more interesting if the walking route was different every day, so he wrote the letters "east" or "south" at the H x W intersections from (1, 1) to (H, W). , I decided to take a walk every day according to the following rules.
* If you are at an intersection with letters, rewrite the letters from "east" to "south" and "south" to "east", and the direction of the originally written letters. Proceed to the next intersection at.
* End the walk when you reach the easternmost or southernmost road.
After thinking about this plan, Taro was wondering what route he would take in his future walks. For Taro, he predicted the route for Taro's Nth walk. Create a program to do.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, three positive integers are separated by blanks. These are the values of the three numbers H, W, N in the problem statement. H, W, N are 1 ≤ H ≤, respectively. 1000, 1 ≤ W ≤ 1000, 1 ≤ N ≤ 10000000 = 107. From the 2nd line to H + 1st line, W integers are written separated by blanks. Represents the information of the character written at the intersection first. If the jth integer of i + 1st line is 0, the character written at the intersection (i, j) is "south", and if it is 1, the intersection Indicates that the character written in (i, j) is "east".
Of the scoring data, 30% of the points are satisfied with H ≤ 100, W ≤ 100, and N ≤ 1000.
When H, W, N are all 0, it indicates the end of input. The number of data sets does not exceed 10.
output
Output in the following format for each data set.
When the intersection where Taro finishes the walk in the Nth walk is (i, j), output i and j separated by a blank in this order.
Example
Input
3 4 3
1 0 1 1
0 1 0 0
1 0 1 0
0 0 0
Output
1 5 | instruction | 0 | 57,096 | 1 | 114,192 |
"Correct Solution:
```
while True:
h,w,n = map(int, input().split())
if h==0: break
mapp = []
for i in range(h):
hoge = list(map(int,input().split()))
hoge.append(0)
mapp.append(hoge)
mapp.append([0]*(w+1))
n -= 1
nmap = [[0]*(w+1) for _ in range(h+1)]
nmap[0][0] = n
for i in range(h):
for j in range(w):
nmap[i+1][j] += (nmap[i][j]+1-mapp[i][j]) // 2
nmap[i][j+1] += (nmap[i][j]+mapp[i][j]) // 2
mapp[i][j] = (nmap[i][j]+mapp[i][j]) % 2
i,j = 0,0
while i < h and j < w:
if mapp[i][j] == 0:
i += 1
else:
j += 1
print(i+1,j+1)
``` | output | 1 | 57,096 | 1 | 114,193 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the northwestern intersection, and the walk starts from here.
Hereafter, the ath intersection from the north and the bth intersection from the west are represented by (a, b). For example, the intersection where Taro's house is located is (1, 1).
<image>
Figure: JOI town map (for H = 3, W = 4). The top of the figure corresponds to the north and the left corresponds to the west.
Taro thought that it would be more interesting if the walking route was different every day, so he wrote the letters "east" or "south" at the H x W intersections from (1, 1) to (H, W). , I decided to take a walk every day according to the following rules.
* If you are at an intersection with letters, rewrite the letters from "east" to "south" and "south" to "east", and the direction of the originally written letters. Proceed to the next intersection at.
* End the walk when you reach the easternmost or southernmost road.
After thinking about this plan, Taro was wondering what route he would take in his future walks. For Taro, he predicted the route for Taro's Nth walk. Create a program to do.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, three positive integers are separated by blanks. These are the values of the three numbers H, W, N in the problem statement. H, W, N are 1 ≤ H ≤, respectively. 1000, 1 ≤ W ≤ 1000, 1 ≤ N ≤ 10000000 = 107. From the 2nd line to H + 1st line, W integers are written separated by blanks. Represents the information of the character written at the intersection first. If the jth integer of i + 1st line is 0, the character written at the intersection (i, j) is "south", and if it is 1, the intersection Indicates that the character written in (i, j) is "east".
Of the scoring data, 30% of the points are satisfied with H ≤ 100, W ≤ 100, and N ≤ 1000.
When H, W, N are all 0, it indicates the end of input. The number of data sets does not exceed 10.
output
Output in the following format for each data set.
When the intersection where Taro finishes the walk in the Nth walk is (i, j), output i and j separated by a blank in this order.
Example
Input
3 4 3
1 0 1 1
0 1 0 0
1 0 1 0
0 0 0
Output
1 5 | instruction | 0 | 57,097 | 1 | 114,194 |
"Correct Solution:
```
while True:
h,w,n = map(int,input().split())
if not h: break
sss = [[1 if s == "1" else 0 for s in input().split()] for i in range(h)]
dp = [[0 for i in range(w + 1)] for j in range(h + 1)]
dp[0][0] = n - 1
for x in range(h):
for y in range(w):
a = dp[x][y]
if sss[x][y]:
if a % 2:
dp[x + 1][y] += a // 2
dp[x][y + 1] += a // 2 + 1
else:
dp[x + 1][y] += a // 2
dp[x][y + 1] += a // 2
else:
if a % 2:
dp[x + 1][y] += a // 2 + 1
dp[x][y + 1] += a // 2
else:
dp[x + 1][y] += a // 2
dp[x][y + 1] += a // 2
sss[x][y] = (sss[x][y] + dp[x][y]) % 2
# print(sss)
# print(dp)
x = y = 0
while x < h and y < w:
if sss[x][y]:
y += 1
else:
x += 1
print(x + 1,y + 1)
``` | output | 1 | 57,097 | 1 | 114,195 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the northwestern intersection, and the walk starts from here.
Hereafter, the ath intersection from the north and the bth intersection from the west are represented by (a, b). For example, the intersection where Taro's house is located is (1, 1).
<image>
Figure: JOI town map (for H = 3, W = 4). The top of the figure corresponds to the north and the left corresponds to the west.
Taro thought that it would be more interesting if the walking route was different every day, so he wrote the letters "east" or "south" at the H x W intersections from (1, 1) to (H, W). , I decided to take a walk every day according to the following rules.
* If you are at an intersection with letters, rewrite the letters from "east" to "south" and "south" to "east", and the direction of the originally written letters. Proceed to the next intersection at.
* End the walk when you reach the easternmost or southernmost road.
After thinking about this plan, Taro was wondering what route he would take in his future walks. For Taro, he predicted the route for Taro's Nth walk. Create a program to do.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, three positive integers are separated by blanks. These are the values of the three numbers H, W, N in the problem statement. H, W, N are 1 ≤ H ≤, respectively. 1000, 1 ≤ W ≤ 1000, 1 ≤ N ≤ 10000000 = 107. From the 2nd line to H + 1st line, W integers are written separated by blanks. Represents the information of the character written at the intersection first. If the jth integer of i + 1st line is 0, the character written at the intersection (i, j) is "south", and if it is 1, the intersection Indicates that the character written in (i, j) is "east".
Of the scoring data, 30% of the points are satisfied with H ≤ 100, W ≤ 100, and N ≤ 1000.
When H, W, N are all 0, it indicates the end of input. The number of data sets does not exceed 10.
output
Output in the following format for each data set.
When the intersection where Taro finishes the walk in the Nth walk is (i, j), output i and j separated by a blank in this order.
Example
Input
3 4 3
1 0 1 1
0 1 0 0
1 0 1 0
0 0 0
Output
1 5 | instruction | 0 | 57,098 | 1 | 114,196 |
"Correct Solution:
```
#!/usr/bin/env python
import string
import sys
from itertools import chain, takewhile
def read(
f, *shape, it=chain.from_iterable(sys.stdin), whitespaces=set(string.whitespace)
):
def read_word():
return f("".join(takewhile(lambda c: c not in whitespaces, it)).strip())
if not shape:
return read_word()
elif len(shape) == 1:
return [read_word() for _ in range(shape[0])]
elif len(shape) == 2:
return [[read_word() for _ in range(shape[1])] for _ in range(shape[0])]
def arr(*shape, fill_value=0):
if len(shape) == 1:
return [fill_value] * shape[fill_value]
elif len(shape) == 2:
return [[fill_value] * shape[1] for _ in range(shape[0])]
def debug(**kwargs):
print(
", ".join("{} = {}".format(k, repr(v)) for k, v in kwargs.items()),
file=sys.stderr,
)
def main():
while True:
h, w, n = map(int, sys.stdin.readline().split())
if (h, w, n) == (0, 0, 0):
return
grid = []
for _ in range(h):
row = list(map(int, sys.stdin.readline().split()))
grid.append(row)
dp = arr(h, w)
dp[0][0] = n - 1
for i in range(h):
for j in range(w):
if i < h - 1 and grid[i][j] == 0:
dp[i + 1][j] += (dp[i][j] + 1) // 2
if i < h - 1 and grid[i][j] == 1:
dp[i + 1][j] += dp[i][j] // 2
if j < w - 1 and grid[i][j] == 0:
dp[i][j + 1] += dp[i][j] // 2
if j < w - 1 and grid[i][j] == 1:
dp[i][j + 1] += (dp[i][j] + 1) // 2
for i in range(h):
for j in range(w):
grid[i][j] = (grid[i][j] + dp[i][j]) % 2
i = 0
j = 0
while i < h and j < w:
if grid[i][j] == 0:
i += 1
else:
j += 1
print(i + 1, j + 1)
if __name__ == "__main__":
main()
``` | output | 1 | 57,098 | 1 | 114,197 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the northwestern intersection, and the walk starts from here.
Hereafter, the ath intersection from the north and the bth intersection from the west are represented by (a, b). For example, the intersection where Taro's house is located is (1, 1).
<image>
Figure: JOI town map (for H = 3, W = 4). The top of the figure corresponds to the north and the left corresponds to the west.
Taro thought that it would be more interesting if the walking route was different every day, so he wrote the letters "east" or "south" at the H x W intersections from (1, 1) to (H, W). , I decided to take a walk every day according to the following rules.
* If you are at an intersection with letters, rewrite the letters from "east" to "south" and "south" to "east", and the direction of the originally written letters. Proceed to the next intersection at.
* End the walk when you reach the easternmost or southernmost road.
After thinking about this plan, Taro was wondering what route he would take in his future walks. For Taro, he predicted the route for Taro's Nth walk. Create a program to do.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, three positive integers are separated by blanks. These are the values of the three numbers H, W, N in the problem statement. H, W, N are 1 ≤ H ≤, respectively. 1000, 1 ≤ W ≤ 1000, 1 ≤ N ≤ 10000000 = 107. From the 2nd line to H + 1st line, W integers are written separated by blanks. Represents the information of the character written at the intersection first. If the jth integer of i + 1st line is 0, the character written at the intersection (i, j) is "south", and if it is 1, the intersection Indicates that the character written in (i, j) is "east".
Of the scoring data, 30% of the points are satisfied with H ≤ 100, W ≤ 100, and N ≤ 1000.
When H, W, N are all 0, it indicates the end of input. The number of data sets does not exceed 10.
output
Output in the following format for each data set.
When the intersection where Taro finishes the walk in the Nth walk is (i, j), output i and j separated by a blank in this order.
Example
Input
3 4 3
1 0 1 1
0 1 0 0
1 0 1 0
0 0 0
Output
1 5 | instruction | 0 | 57,099 | 1 | 114,198 |
"Correct Solution:
```
def main():
while True:
import sys
input=sys.stdin.readline
h,w,n=map(int,input().split())
if h==0:
break
grid=[list(map(int,input().split())) for _ in [0]*h]
dp=[[0]*(w+1) for _ in [0]*(h+1)]
dp[0][0]=n-1
for k in range(h+w-1):
for i in range(max(0,k-w+1),min(h,k+1)):
j=k-i
x=dp[i][j]
if grid[i][j]==1:
dp[i+1][j]+=x//2
dp[i][j+1]+=x-x//2
else:
dp[i][j+1]+=x//2
dp[i+1][j]+=x-x//2
for i in range(h):
for j in range(w):
dp[i][j]=(grid[i][j]+dp[i][j])%2
i,j=1,1
while True:
if dp[i-1][j-1]==1:
j+=1
else:
i+=1
if i>h or j>w:
break
print(i,j)
if __name__=='__main__':
main()
``` | output | 1 | 57,099 | 1 | 114,199 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the northwestern intersection, and the walk starts from here.
Hereafter, the ath intersection from the north and the bth intersection from the west are represented by (a, b). For example, the intersection where Taro's house is located is (1, 1).
<image>
Figure: JOI town map (for H = 3, W = 4). The top of the figure corresponds to the north and the left corresponds to the west.
Taro thought that it would be more interesting if the walking route was different every day, so he wrote the letters "east" or "south" at the H x W intersections from (1, 1) to (H, W). , I decided to take a walk every day according to the following rules.
* If you are at an intersection with letters, rewrite the letters from "east" to "south" and "south" to "east", and the direction of the originally written letters. Proceed to the next intersection at.
* End the walk when you reach the easternmost or southernmost road.
After thinking about this plan, Taro was wondering what route he would take in his future walks. For Taro, he predicted the route for Taro's Nth walk. Create a program to do.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, three positive integers are separated by blanks. These are the values of the three numbers H, W, N in the problem statement. H, W, N are 1 ≤ H ≤, respectively. 1000, 1 ≤ W ≤ 1000, 1 ≤ N ≤ 10000000 = 107. From the 2nd line to H + 1st line, W integers are written separated by blanks. Represents the information of the character written at the intersection first. If the jth integer of i + 1st line is 0, the character written at the intersection (i, j) is "south", and if it is 1, the intersection Indicates that the character written in (i, j) is "east".
Of the scoring data, 30% of the points are satisfied with H ≤ 100, W ≤ 100, and N ≤ 1000.
When H, W, N are all 0, it indicates the end of input. The number of data sets does not exceed 10.
output
Output in the following format for each data set.
When the intersection where Taro finishes the walk in the Nth walk is (i, j), output i and j separated by a blank in this order.
Example
Input
3 4 3
1 0 1 1
0 1 0 0
1 0 1 0
0 0 0
Output
1 5
Submitted Solution:
```
while True:
h,w,n = map(int,input().split())
if not h: break
sss = [[True if s == "1" else False for s in input().split()] for i in range(h)]
for i in range(n):
x = y = 0
while x < h and y < w:
sss[x][y] = not sss[x][y]
if sss[x][y]:
x += 1
else:
y += 1
print(x + 1,y + 1)
``` | instruction | 0 | 57,100 | 1 | 114,200 |
No | output | 1 | 57,100 | 1 | 114,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | instruction | 0 | 57,266 | 1 | 114,532 |
Tags: combinatorics, dfs and similar, dsu, graphs
Correct Solution:
```
import sys
import threading
from collections import deque
def func():
lines = sys.stdin.readlines()
nxt = 0
t = int(lines[nxt])
nxt += 1
ans = []
for _ in range(t):
n,m,a,b = map(int, lines[nxt].split())
nxt += 1
g = [[] for _ in range(n)]
for _ in range(m):
u,v = map(int, lines[nxt].split())
nxt += 1
g[u-1].append(v-1)
g[v-1].append(u-1)
a -= 1
b -= 1
sigs = [0]*n
sigs[a] = -1
sigs[b] = -1
cur_sig = 0
inv = {}
cnt = {}
for i in range(n):
if sigs[i]:
continue
cur_sig += 1
cnt[cur_sig] = 1
inv[cur_sig] = set()
sigs[i] = cur_sig
q = deque()
q.append(i)
while len(q):
node = q.popleft()
# if node == a:
# inv[cur_sig].add("A")
# if node == b:
# inv[cur_sig].add("B")
# if sigs[node]:
# continue
# sigs[node] = cur_sig
# cnt[cur_sig] += 1
for v in g[node]:
if v == a:
inv[cur_sig].add("A")
if v == b:
inv[cur_sig].add("B")
if sigs[v]:
continue
sigs[v] = cur_sig
cnt[cur_sig] += 1
q.append(v)
A = 0
B = 0
for k,v in inv.items():
if v == {"A"}:
A += cnt[k]
if v == {"B"}:
B += cnt[k]
ans.append(str(A*B))
print("\n".join(ans))
func()
``` | output | 1 | 57,266 | 1 | 114,533 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | instruction | 0 | 57,267 | 1 | 114,534 |
Tags: combinatorics, dfs and similar, dsu, graphs
Correct Solution:
```
# aとbを結ぶ辺を縮約して、一つの頂点としたとき、それ以外の頂点の数
# aだけからbを超えずにいける集合と、bだけからaを超えずにいける集合
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import deque
def BFS(start, dont, G):
que = deque()
que.append(start)
s = set()
while que:
cur = que.popleft()
if cur in s:
continue
if cur != start:
s.add(cur)
for to in G[cur]:
if to != dont and to != start and to not in s:
que.append(to)
return s
def solve():
n,m,a,b = map(int, input().split())
a,b = a-1,b-1
G = [[] for i in range(n)]
for i in range(m):
x,y = map(int, input().split())
x,y = x-1,y-1
G[x].append(y)
G[y].append(x)
# BFS
sa = BFS(a, b, G)
sb = BFS(b, a, G)
left = sa-sb
right = sb-sa
ans = len(left)*len(right)
print(ans)
t = int(input())
for i in range(t):
solve()
``` | output | 1 | 57,267 | 1 | 114,535 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | instruction | 0 | 57,268 | 1 | 114,536 |
Tags: combinatorics, dfs and similar, dsu, graphs
Correct Solution:
```
def solve():
N, M, A, B = map(int, input().split())
roads = [list(map(lambda x:int(x)-1, input().split())) for _ in range(M)]
A -= 1
B -= 1
adj = [[] for _ in range(N)]
for a, b in roads:
adj[a].append(b)
adj[b].append(a)
def dfs(start, invalid):
Q = [start]
visited = set()
while Q:
q = Q.pop()
for next in adj[q]:
if next == invalid or next in visited:
continue
else:
visited.add(next)
Q.append(next)
return visited-{start}
set_A = dfs(A, B)
set_B = dfs(B, A)
print(len(set_A-set_B)*len(set_B-set_A))
T = int(input())
for _ in range(T):
solve()
``` | output | 1 | 57,268 | 1 | 114,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | instruction | 0 | 57,269 | 1 | 114,538 |
Tags: combinatorics, dfs and similar, dsu, graphs
Correct Solution:
```
class UnionFind():
# 作りたい要素数nで初期化
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rnk = [0]*(n+1)
# ノードxのrootノードを見つける
def Find_Root(self, x):
if(self.root[x] < 0):
return x
else:
self.root[x] = self.Find_Root(self.root[x])
return self.root[x]
# 木の併合、入力は併合したい各ノード
def Unite(self, x, y):
x = self.Find_Root(x)
y = self.Find_Root(y)
if(x == y):
return
elif(self.rnk[x] > self.rnk[y]):
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if(self.rnk[x] == self.rnk[y]):
self.rnk[y] += 1
def isSameGroup(self, x, y):
return self.Find_Root(x) == self.Find_Root(y)
# ノードxが属する木のサイズ
def Count(self, x):
return -self.root[self.Find_Root(x)]
import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
N, M, a, b = map(int, input().split())
CD = [list(map(int, input().split())) for _ in range(M)]
Query.append((N, M, a, b, CD))
def main():
for N, M, a, b, CD in Query:
uni1 = UnionFind(N)
uni2 = UnionFind(N)
for c, d in CD:
if c != a and d != a:
uni1.Unite(c, d)
if c != b and d != b:
uni2.Unite(c, d)
p0 = 0
p1 = 0
for n in range(1, N+1):
if uni1.isSameGroup(n, b) and not uni2.isSameGroup(n, a):
p0 += 1
if not uni1.isSameGroup(n, b) and uni2.isSameGroup(n, a):
p1 += 1
print((p0-1)*(p1-1))
if __name__ == "__main__":
main()
``` | output | 1 | 57,269 | 1 | 114,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | instruction | 0 | 57,270 | 1 | 114,540 |
Tags: combinatorics, dfs and similar, dsu, graphs
Correct Solution:
```
from collections import deque
def solveOne():
nVertices, nEdges, v1, v2 = map(int, input().split())
v1 -= 1
v2 -= 1
g = [[] for _ in range(nVertices)]
for _ in range(nEdges):
u, v = map(lambda x: int(x) - 1, input().split())
g[u].append(v)
g[v].append(u)
def bfs(start, restricted):
visited = {start}
q = deque([start])
while q:
v = q.pop()
for to in g[v]:
if to != restricted and to not in visited:
visited.add(to)
q.appendleft(to)
return visited - {start}
set1 = bfs(v1, v2)
set2 = bfs(v2, v1)
return len(set1 - set2) * len(set2 - set1)
for _ in range(int(input())):
print(solveOne())
``` | output | 1 | 57,270 | 1 | 114,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | instruction | 0 | 57,271 | 1 | 114,542 |
Tags: combinatorics, dfs and similar, dsu, graphs
Correct Solution:
```
#########################################################################################################\
#########################################################################################################
###################################The_Apurv_Rathore#####################################################
#########################################################################################################
#########################################################################################################
import sys,os,io
from sys import stdin
from types import GeneratorType
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_left , bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')
#for deep recursion__________________________________________-
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,p - 2, p)) % p
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
c = dict(Counter(l))
return list(set(l))
# return c
def power(x, y, p) :
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
#____________________GetPrimeFactors in log(n)________________________________________
def sieveForSmallestPrimeFactor():
MAXN = 100001
spf = [0 for i in range(MAXN)]
spf[1] = 1
for i in range(2, MAXN):
spf[i] = i
for i in range(4, MAXN, 2):
spf[i] = 2
for i in range(3, math.ceil(math.sqrt(MAXN))):
if (spf[i] == i):
for j in range(i * i, MAXN, i):
if (spf[j] == j):
spf[j] = i
return spf
def getPrimeFactorizationLOGN(x):
spf = sieveForSmallestPrimeFactor()
ret = list()
while (x != 1):
ret.append(spf[x])
x = x // spf[x]
return ret
#____________________________________________________________
def SieveOfEratosthenes(n):
#time complexity = nlog(log(n))
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
def si():
return input()
def divideCeil(n,x):
if (n%x==0):
return n//x
return n//x+1
def ii():
return int(input())
def li():
return list(map(int,input().split()))
#__________________________TEMPLATE__________________OVER_______________________________________________________
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
else:
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def solve():
n,m,a,b = li()
a-=1
b-=1
adj = [[] for i in range(n)]
for i in range(m):
u,v = li()
u-=1
v-=1
adj[u].append(v)
adj[v].append(u)
visa = [False]*n
# @bootstrap
def dfsa(node,parent):
st = [node]
while(st!=[]):
node = st.pop(-1)
for child in adj[node]:
if child==parent or child==b:
continue
if visa[child]==False:
visa[child]=True
st.append(child)
# def dfsa(node,parent):
# for child in adj[node]:
# if child==parent or child==b:
# continue
# if visa[child]==False:
# visa[child]=True
# yield dfsa(child,node)
visa[a]=True
dfsa(a,-1)
visb = [False]*n
visb[b]=True
def dfsb(node,parent):
st = [node]
while(st!=[]):
node = st.pop(-1)
for child in adj[node]:
if child==parent or child==a:
continue
if visb[child]==False:
visb[child]=True
st.append(child)
# @bootstrap
# def dfsb(node,parent):
# for child in adj[node]:
# if child==parent or child==a:
# continue
# if visb[child]==False:
# visb[child]=True
# yield dfsb(child,node)
dfsb(b,-1)
# print(visa)
# print(visb)
visbyanotb = 0
visbybnota = 0
for i in range(n):
if i==a or i==b:
continue
if visa[i]==False and visb[i]==True:
visbyanotb+=1
if visa[i]==True and visb[i]==False:
visbybnota+=1
# print(visbybnota,visbyanotb)
print(visbybnota*visbyanotb)
t = 1
t = ii()
for _ in range(t):
solve()
``` | output | 1 | 57,271 | 1 | 114,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | instruction | 0 | 57,272 | 1 | 114,544 |
Tags: combinatorics, dfs and similar, dsu, graphs
Correct Solution:
```
from collections import defaultdict, deque
from itertools import permutations
from sys import stdin,stdout
from bisect import bisect_left, bisect_right
from copy import deepcopy
int_input=lambda : int(stdin.readline())
string_input=lambda : stdin.readline()
multi_int_input =lambda : map(int, stdin.readline().split())
multi_input = lambda : stdin.readline().split()
list_input=lambda : list(map(int,stdin.readline().split()))
string_list_input=lambda: list(string_input())
MOD = pow(10,9)+7
test = int_input()
set1 = []
n = 0
def dfs(graph,start,forbidden):
Stack = [start]
result = set([])
visited = [False]*(n+1)
while(Stack):
children = Stack.pop()
for items in graph[children]:
if items == forbidden or visited[items]:
continue
else:
visited[items] = True
result.add(items)
Stack.append(items)
return result-{start}
for _ in range(test):
n,m,a,b = multi_int_input()
graph = {}
for i in range(1,n+1):
graph[i] = []
for i in range(m):
u,v = multi_int_input()
graph[u].append(v)
graph[v].append(u)
result1 = dfs(graph,a,b)
result2 = dfs(graph,b,a)
print((len(result1-result2))*(len(result2-result1)))
``` | output | 1 | 57,272 | 1 | 114,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1 | instruction | 0 | 57,273 | 1 | 114,546 |
Tags: combinatorics, dfs and similar, dsu, graphs
Correct Solution:
```
for t in range(int(input())):
n, m, a, b = map(int, input(). split())
neigh_cities = [[] for i in range(n+1)]
for i in range(m):
x, y = map(int, input(). split())
neigh_cities[x].append(y)
neigh_cities[y].append(x)
with_a = 0
with_b = 0
remaining_cities = set(range(1, n+1))
remaining_cities.difference_update({a, b})
while len(remaining_cities) != 0:
to_be_explored = set()
already_explored = set()
connected_to_a = False
connected_to_b = False
comp = []
to_be_explored.add(remaining_cities.pop())
while len(to_be_explored) != 0:
city = to_be_explored.pop()
comp.append(city)
already_explored.add(city)
for i in neigh_cities[city]:
if i == a:
connected_to_a = True
continue
if i == b:
connected_to_b = True
continue
if i not in already_explored:
to_be_explored.add(i)
remaining_cities.discard(i)
if connected_to_a and not connected_to_b:
with_a += len(comp)
if connected_to_b and not connected_to_a:
with_b += len(comp)
print(with_a * with_b)
``` | output | 1 | 57,273 | 1 | 114,547 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1
Submitted Solution:
```
from sys import stdin
def input():
return stdin.readline()[:-1]
def intput():
return int(input())
def sinput():
return input().split()
def intsput():
return map(int, sinput())
# Code
t = intput()
for _ in range(t):
n, m, a, b = intsput()
colors = [0] * (n + 1)
colors[a] = 'a'
colors[b] = 'b'
roads = {}
for i in range(m):
x, y = intsput()
if x not in roads:
roads[x] = []
if y not in roads:
roads[y] = []
roads[x].append(y)
roads[y].append(x)
counts = {(True, False): 0, (True, True): 0, (False, True): 0}
visited = set()
while len(visited) < n - 2:
for i in range(1, n + 1):
if i not in (a, b) and i not in visited:
break
else:
exit(1)
start = i
visited.add(start)
cnt = 1
colors[start] = 1
adj = roads[start]
meta, metb = False, False
while adj:
nxt = adj.pop()
if nxt == a:
meta = True
elif nxt == b:
metb = True
elif nxt not in visited:
visited.add(nxt)
cnt += 1
colors[nxt] = 1
adj += roads[nxt]
col1 = (meta, metb)
counts[col1] += cnt
print(counts[(True, False)] * counts[(False, True)])
``` | instruction | 0 | 57,274 | 1 | 114,548 |
Yes | output | 1 | 57,274 | 1 | 114,549 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1
Submitted Solution:
```
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
return int(input())
def MI():
return map(int,input().split())
def LI():
return [int(i) for i in input().split()]
def LI_():
return [int(i)-1 for i in input().split()]
def StoI():
return [ord(i)-97 for i in input()]
def ItoS(nn):
return chr(nn+97)
def GI(V,E,Directed=False,index=0):
org_inp=[]
g=[[] for i in range(n)]
for i in range(E):
inp=LI()
org_inp.append(inp)
if index==0:
inp[0]-=1
inp[1]-=1
if len(inp)==2:
a,b=inp
g[a].append(b)
if not Directed:
g[b].append(a)
elif len(inp)==3:
a,b,c=inp
aa=(inp[0],inp[2])
bb=(inp[1],inp[2])
g[a].append(bb)
if not Directed:
g[b].append(aa)
return g,org_inp
def show(*inp,end='\n'):
if show_flg:
print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()
show_flg=False
show_flg=True
t=I()
for _ in range(t):
n,m,a,b=LI()
a,b=a-1,b-1
ans=0
g,c=GI(n,m)
vb=[1 for i in range(n)]
va=[1 for i in range(n)]
q=[b]
while q:
c=q.pop()
vb[c]=0
for nb in g[c]:
if vb[nb]==1 and nb!=a:
q.append(nb)
vb[nb]=0
q=[a]
while q:
c=q.pop()
va[c]=0
for nb in g[c]:
if va[nb]==1 and nb!=b:
q.append(nb)
va[nb]=0
x,y=sum(vb),sum(va)
ans=(x-1)*(y-1)
print(ans)
``` | instruction | 0 | 57,275 | 1 | 114,550 |
Yes | output | 1 | 57,275 | 1 | 114,551 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1
Submitted Solution:
```
t = int(input())
from collections import defaultdict
def bfs(graph, x, forb):
visited = set()
circle = [x]
while len(circle) > 0:
new = set()
for v in circle:
if v in visited:
continue
visited.add(v)
for pov in graph[v]:
if pov not in forb:
new.add(pov)
circle = new
return visited
def can_visit(graph, x):
visited = set()
circle = [x]
while len(circle) > 0:
new = set()
for v in circle:
if v in visited:
continue
visited.add(v)
for pov in graph[v]:
new.add(pov)
circle = new
return visited
for _ in range(t):
n, m, a, b = list(map(int, input().strip().split()))
graph = defaultdict(list)
for _ in range(m):
x, y = list(map(int, input().strip().split()))
graph[x].append(y)
graph[y].append(x)
start = 0
for i in range(1, n+1):
if i != a and i != b:
start = i
break
iza = bfs(graph, a, [b])
izb = bfs(graph, b, [a])
intersection = iza & izb
# print(iza)
# print(izb)
# print(intersection)
num1 = len(iza) - 1 - len(intersection)
num2 = len(izb) - 1 - len(intersection)
print(num1*num2)
# print(start)
# prvi = bfs(graph, start, set([a,b]), n)
# print(prvi)
# drugi = bfs(graph, start, set([a]), n)
# print(drugi)
# tretji = bfs(graph, start, set([b]), n)
# print(tretji)
# p1, p2, p3 = len(prvi), len(drugi), len(tretji)
# g1 = (n - 2 - p1) * p1
# g2 = (n - 1 - p2) * p2
# g3 = (n - 1 - p3) * p3
# print(g1, g2, g3)
# print(g1 - g2 - g3)
# print('END CASE')
``` | instruction | 0 | 57,276 | 1 | 114,552 |
Yes | output | 1 | 57,276 | 1 | 114,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7
class UnionFind:
def __init__(self, n):
self.n = n
self.par = [i for i in range(n+1)]
self.rank = [0] * (n+1)
self.size = [1] * (n+1)
self.tree = [True] * (n+1)
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
self.tree[x] = False
return
if not self.tree[x] or not self.tree[y]:
self.tree[x] = self.tree[y] = False
if self.rank[x] < self.rank[y]:
self.par[x] = y
self.size[y] += self.size[x]
else:
self.par[y] = x
self.size[x] += self.size[y]
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def is_same(self, x, y):
return self.find(x) == self.find(y)
def get_size(self, x=None):
if x is not None:
return self.size[self.find(x)]
else:
res = set()
for i in range(self.n+1):
res.add(self.find(i))
return len(res) - 1
def is_tree(self, x):
return self.tree[self.find(x)]
for _ in range(INT()):
N, M, a, b = MAP()
uf1 = UnionFind(N)
uf2 = UnionFind(N)
for i in range(M):
x, y = MAP()
if a in [x, y] and b in [x, y]:
continue
elif a in [x, y]:
uf1.union(x, y)
elif b in [x, y]:
uf2.union(x, y)
else:
uf1.union(x, y)
uf2.union(x, y)
cnt1 = N - uf1.get_size(a) - 1
cnt2 = N - uf2.get_size(b) - 1
print(cnt1 * cnt2)
``` | instruction | 0 | 57,277 | 1 | 114,554 |
Yes | output | 1 | 57,277 | 1 | 114,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1
Submitted Solution:
```
from sys import stdin
def input():
return stdin.readline()[:-1]
def intput():
return int(input())
def sinput():
return input().split()
def intsput():
return map(int, sinput())
# Code
t = intput()
for _ in range(t):
n, m, a, b = intsput()
colors = [0] * (n + 1)
colors[a] = 'a'
colors[b] = 'b'
roads = {}
for i in range(m):
x, y = intsput()
if x not in roads:
roads[x] = []
if y not in roads:
roads[y] = []
roads[x].append(y)
roads[y].append(x)
for i in range(1, n + 1):
if i not in (a, b):
break
start = i
visited = set([start])
colors[start] = 1
adj = roads[start]
meta, metb = False, False
while adj:
nxt = adj.pop()
if nxt == a:
meta = True
elif nxt == b:
metb = True
elif nxt not in visited:
visited.add(nxt)
colors[nxt] = 1
adj += roads[nxt]
col1 = (meta, metb)
for i in range(1, n + 1):
if i not in (a, b) and i not in visited:
break
else:
print(0)
continue
start = i
visited = set([start])
colors[start] = 2
adj = roads[start]
meta, metb = False, False
while adj:
nxt = adj.pop()
if nxt == a:
meta = True
elif nxt == b:
metb = True
elif nxt not in visited:
visited.add(nxt)
colors[nxt] = 2
adj += roads[nxt]
col2 = (meta, metb)
#print(colors[1:])
count1, count2, count3 = 0, 0, 0
for i in range(1, len(colors)):
if colors[i] == 1:
count1 += 1
elif colors[i] == 2:
count2 += 1
elif colors[i] == 0:
count3 += 1
#print(count1, count2, count3)
if col1 == (True, True):
print((count2 + 0) * (count3 + 0))
if col2 == (True, True):
print((count1 + 0) * (count3 + 0))
else:
print((count1 + 0) * (count2 + 0))
``` | instruction | 0 | 57,278 | 1 | 114,556 |
No | output | 1 | 57,278 | 1 | 114,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1
Submitted Solution:
```
from sys import stdin
def input():
return stdin.readline()[:-1]
def intput():
return int(input())
def sinput():
return input().split()
def intsput():
return map(int, sinput())
# Code
t = intput()
for _ in range(t):
n, m, a, b = intsput()
colors = [0] * (n + 1)
colors[a] = 'a'
colors[b] = 'b'
roads = {}
for i in range(m):
x, y = intsput()
if x not in roads:
roads[x] = []
if y not in roads:
roads[y] = []
roads[x].append(y)
roads[y].append(x)
for i in range(1, n + 1):
if i not in (a, b):
break
else:
print(0)
continue
start = i
visited = set([start])
colors[start] = 1
adj = roads[start]
meta, metb = False, False
while adj:
nxt = adj.pop()
if nxt == a:
meta = True
elif nxt == b:
metb = True
elif nxt not in visited:
visited.add(nxt)
colors[nxt] = 1
adj += roads[nxt]
col1 = (meta, metb)
for i in range(1, n + 1):
if i not in (a, b) and i not in visited:
break
else:
print(0)
continue
start = i
visited = set([start])
colors[start] = 2
adj = roads[start]
meta, metb = False, False
while adj:
nxt = adj.pop()
if nxt == a:
meta = True
elif nxt == b:
metb = True
elif nxt not in visited:
visited.add(nxt)
colors[nxt] = 2
adj += roads[nxt]
col2 = (meta, metb)
#print(colors[1:])
count1, count2, count3 = 0, 0, 0
for i in range(1, len(colors)):
if colors[i] == 1:
count1 += 1
elif colors[i] == 2:
count2 += 1
elif colors[i] == 0:
count3 += 1
#print(count1, count2, count3)
if col1 == (True, True):
print(count2 * count3)
elif col2 == (True, True):
print(count1 * count3)
else:
print(count1 * count2)
``` | instruction | 0 | 57,279 | 1 | 114,558 |
No | output | 1 | 57,279 | 1 | 114,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1
Submitted Solution:
```
from sys import stdin
def input():
return stdin.readline()[:-1]
def intput():
return int(input())
def sinput():
return input().split()
def intsput():
return map(int, sinput())
# Code
t = intput()
for _ in range(t):
n, m, a, b = intsput()
colors = [0] * (n + 1)
colors[a] = 'a'
colors[b] = 'b'
roads = {}
for i in range(m):
x, y = intsput()
if x not in roads:
roads[x] = []
if y not in roads:
roads[y] = []
roads[x].append(y)
roads[y].append(x)
for i in range(1, n + 1):
if i not in (a, b):
break
else:
print(0)
continue
start = i
visited = set([start])
colors[start] = 1
adj = roads[start]
meta, metb = False, False
while adj:
nxt = adj.pop()
if nxt == a:
meta = True
elif nxt == b:
metb = True
elif nxt not in visited:
visited.add(nxt)
colors[nxt] = 1
adj += roads[nxt]
col1 = (meta, metb)
for i in range(1, n + 1):
if i not in (a, b) and i not in visited:
break
else:
print(0)
continue
start = i
visited = set([start])
colors[start] = 2
adj = roads[start]
meta, metb = False, False
while adj:
nxt = adj.pop()
if nxt == a:
meta = True
elif nxt == b:
metb = True
elif nxt not in visited:
visited.add(nxt)
colors[nxt] = 2
adj += roads[nxt]
col2 = (meta, metb)
#print(colors[1:])
count1, count2, count3 = 0, 0, 0
for i in range(1, len(colors)):
if colors[i] == 1:
count1 += 1
elif colors[i] == 2:
count2 += 1
elif colors[i] == 0:
count3 += 1
assert count1 + count2 + count3 == n - 2
#print(count1, count2, count3)
if col1 == (True, True):
print(count2 * count3)
elif col2 == (True, True):
print(count1 * count3)
else:
print(count1 * count2)
``` | instruction | 0 | 57,280 | 1 | 114,560 |
No | output | 1 | 57,280 | 1 | 114,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n.
Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ≠ b).
Find the number of pairs of cities x and y (x ≠ a, x ≠ b, y ≠ a, y ≠ b) such that if you go from x to y you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities x,y such that any path from x to y goes through a and b (in any order).
Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs (x,y) and (y,x) must be taken into account only once.
Input
The first line of the input contains an integer t (1 ≤ t ≤ 4⋅10^4) — the number of test cases in the input. Next, t test cases are specified.
The first line of each test case contains four integers n, m, a and b (4 ≤ n ≤ 2⋅10^5, n - 1 ≤ m ≤ 5⋅10^5, 1 ≤ a,b ≤ n, a ≠ b) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively.
The following m lines contain descriptions of roads between cities. Each of road description contains a pair of integers u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i) — numbers of cities connected by the road.
Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities.
The sum of the values of n for all sets of input data in the test does not exceed 2⋅10^5. The sum of the values of m for all sets of input data in the test does not exceed 5⋅10^5.
Output
Print t integers — the answers to the given test cases in the order they are written in the input.
Example
Input
3
7 7 3 5
1 2
2 3
3 4
4 5
5 6
6 7
7 5
4 5 2 3
1 2
2 3
3 4
4 1
4 2
4 3 2 1
1 2
2 3
4 1
Output
4
0
1
Submitted Solution:
```
import sys
from collections import defaultdict
# inf = open('input.txt', 'r')
# reader = (map(int, line.split()) for line in inf)
reader = (map(int, s.split()) for s in sys.stdin)
t, = next(reader)
for _ in range(t):
n, m, a, b = next(reader) # v(G), e(G), a, b
a -= 1
b -= 1
g = defaultdict(list)
for i in range(m):
v, to = next(reader)
v -= 1
to -= 1
g[v].append(to)
g[to].append(v)
def dfs(s, comp, omit):
stack = [s]
while stack:
v = stack.pop()
if not visited[v]:
visited[v] = True
if v != omit:
comp[0] += 1
stack.extend(g[v])
def Cn2(n):
return n * (n - 1) // 2
visited = [False] * n
visited[a] = True
comps_a = []
for s in range(n):
if not visited[s]:
comps_a.append([0])
dfs(s, comps_a[-1], omit=b)
# print(comps_a)
visited = [False] * n
visited[b] = True
comps_b = []
for s in range(n):
if not visited[s]:
comps_b.append([0])
dfs(s, comps_b[-1], omit=a)
# print(comps_b)
visited = [False] * n
visited[a] = True
visited[b] = True
comps_ab = []
for s in range(n):
if not visited[s]:
comps_ab.append([0])
dfs(s, comps_ab[-1], omit=n)
# print(comps_ab)
allV = n - 2
Na = 0 # passes a
for comp in comps_a:
k = comp[0]
allV -= k
Na += k * allV
# print(Na)
allV = n - 2
Nb = 0 # passes b
for comp in comps_b:
k = comp[0]
allV -= k
Nb += k * allV
# print(Nb)
allV = n - 2
N0 = 0 # passes b
for comp in comps_ab:
k = comp[0]
allV -= k
N0 += Cn2(k)
# print(N0)
N_all = Cn2(n - 2)
N_ab = N0 + Na + Nb - N_all
print(N_ab)
# inf.close()
``` | instruction | 0 | 57,281 | 1 | 114,562 |
No | output | 1 | 57,281 | 1 | 114,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
James Bond has a new plan for catching his enemy. There are some cities and directed roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there.
The city a is called interesting, if for each city b, there is exactly one simple path from a to b. By a simple path, we understand a sequence of distinct cities, such that for every two neighboring cities, there exists a directed road from the first to the second city.
Bond's enemy is the mistress of escapes, so only the chase started in an interesting city gives the possibility of catching her. James wants to arrange his people in such cities. However, if there are not enough interesting cities, the whole action doesn't make sense since Bond's people may wait too long for the enemy.
You are responsible for finding all the interesting cities or saying that there is not enough of them. By not enough, James means strictly less than 20\% of all cities.
Input
The first line contains one integer t (1 ≤ t ≤ 2 000) — the number of test cases. Each test case is described as follows:
The first line contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of cities and roads between them. Each of the following m lines contains two integers u, v (u ≠ v; 1 ≤ u, v ≤ n), which denote that there is a directed road from u to v.
You can assume that between each ordered pair of cities there is at most one road. The sum of n over all test cases doesn't exceed 10^5, and the sum of m doesn't exceed 2 ⋅ 10^5.
Output
If strictly less than 20\% of all cities are interesting, print -1. Otherwise, let k be the number of interesting cities. Print k distinct integers in increasing order — the indices of interesting cities.
Example
Input
4
3 3
1 2
2 3
3 1
3 6
1 2
2 1
2 3
3 2
1 3
3 1
7 10
1 2
2 3
3 1
1 4
4 5
5 1
4 6
6 7
7 4
6 1
6 8
1 2
2 3
3 4
4 5
5 6
6 1
6 2
5 1
Output
1 2 3
-1
1 2 3 5
-1
Note
In all drawings, if a city is colored green, then it is interesting; otherwise, it is colored red.
In the first sample, each city is interesting.
<image>
In the second sample, no city is interesting.
<image>
In the third sample, cities 1, 2, 3 and 5 are interesting.
<image>
In the last sample, only the city 1 is interesting. It is strictly less than 20\% of all cities, so the answer is -1.
<image>
Submitted Solution:
```
# from math import factorial as fac
from collections import defaultdict
# from copy import deepcopy
import sys, math
f = None
try:
f = open('q1.input', 'r')
except IOError:
f = sys.stdin
if 'xrange' in dir(__builtins__):
range = xrange
# print(f.readline())
# sys.setrecursionlimit(3*10**6)
def print_case_iterable(case_num, iterable):
print("Case #{}: {}".format(case_num," ".join(map(str,iterable))))
def print_case_number(case_num, iterable):
print("Case #{}: {}".format(case_num,iterable))
def print_iterable(A):
print (' '.join(A))
def read_int():
return int(f.readline().strip())
def read_int_array():
return [int(x) for x in f.readline().strip().split(" ")]
def rns():
a = [x for x in f.readline().split(" ")]
return int(a[0]), a[1].strip()
def read_string():
return list(f.readline().strip())
def ri():
return int(f.readline().strip())
def ria():
return [int(x) for x in f.readline().strip().split(" ")]
def rns():
a = [x for x in f.readline().split(" ")]
return int(a[0]), a[1].strip()
def rs():
return list(f.readline().strip())
def bi(x):
return bin(x)[2:]
from collections import deque
import math
NUMBER = 10**9 + 7
# NUMBER = 998244353
def factorial(n) :
M = NUMBER
f = 1
for i in range(1, n + 1):
f = (f * i) % M # Now f never can
# exceed 10^9+7
return f
def mult(a,b):
return (a * b) % NUMBER
def minus(a , b):
return (a - b) % NUMBER
def plus(a , b):
return (a + b) % NUMBER
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a):
m = NUMBER
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def choose(n,k):
if n < k:
assert false
return mult(factorial(n), modinv(mult(factorial(k),factorial(n-k)))) % NUMBER
from collections import deque, defaultdict
import heapq
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
def dfs(g, timeIn, timeOut,depths,parents):
# assign In-time to node u
cnt = 0
# node, neig_i, parent, depth
stack = [[1,0,0,0]]
while stack:
v,neig_i,parent,depth = stack[-1]
parents[v] = parent
depths[v] = depth
# print (v)
if neig_i == 0:
timeIn[v] = cnt
cnt+=1
while neig_i < len(g[v]):
u = g[v][neig_i]
if u == parent:
neig_i+=1
continue
stack[-1][1] = neig_i + 1
stack.append([u,0,v,depth+1])
break
if neig_i == len(g[v]):
stack.pop()
timeOut[v] = cnt
cnt += 1
# def isAncestor(u: int, v: int, timeIn: list, timeOut: list) -> str:
# return timeIn[u] <= timeIn[v] and timeOut[v] <= timeOut[u]
cnt = 0
@bootstrap
def dfs(v,adj,timeIn, timeOut,depths,parents,parent=0,depth=0):
global cnt
parents[v] = parent
depths[v] = depth
timeIn[v] = cnt
cnt+=1
for u in adj[v]:
if u == parent:
continue
yield dfs(u,adj,timeIn,timeOut,depths,parents,v,depth+1)
timeOut[v] = cnt
cnt+=1
yield
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
# Function to return LCM of two numbers
def lcm(a,b):
return (a*b) / gcd(a,b)
def get_num_2_5(n):
twos = 0
fives = 0
while n>0 and n%2 == 0:
n//=2
twos+=1
while n>0 and n%5 == 0:
n//=5
fives+=1
return (twos,fives)
def shift(a,i,num):
for _ in range(num):
a[i],a[i+1],a[i+2] = a[i+2],a[i],a[i+1]
def equal(x,y):
return abs(x-y) <= 1e-9
# def leq(x,y):
# return x-y <= 1e-9
def getAngle(a, b, c):
ang = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))
return ang + 360 if ang < 0 else ang
def getLength(a,b):
return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)
from heapq import heapify, heappush, heappop
def bfs(adj):
s = set()
d = defaultdict(set)
# print('\n'.join(map(str,E.items())))
q = deque([])
s.add(0)
d[0].add(0)
q.append((0,0))
while len(q) > 0:
v,depth = q.popleft()
for u in adj[v]:
if u not in s:
s.add(u)
d[depth+1].add(u)
q.append((u,depth+1))
# print(q)
return d
def isSubsetSum(arr, n, summ):
# The value of subarr[i][j] will be
# true if there is a
# subarr of arr[0..j-1] with summ equal to i
subarr =([[False for i in range(summ + 1)]
for i in range(n + 1)])
# If summ is 0, then answer is true
for i in range(n + 1):
subarr[i][0] = True
# If summ is not 0 and arr is empty,
# then answer is false
for i in range(1, summ + 1):
subarr[0][i]= False
# Fill the subarr table in botton up manner
for i in range(1, n + 1):
for j in range(1, summ + 1):
if j<arr[i-1]:
subarr[i][j] = subarr[i-1][j]
if j>= arr[i-1]:
subarr[i][j] = (subarr[i-1][j] or
subarr[i - 1][j-arr[i-1]])
# uncomment this code to print table
# for i in range(n + 1):
# for j in range(summ + 1):
# print (subset[i][j], end =" ")
# print()
return subarr[n][summ]
def bfs(v,adj,onpath):
# d is a dict for depth
s = set()
d = defaultdict(set)
q = deque([])
s.add(0)
d[0].add(0)
q.append((0,0))
while len(q) > 0:
v,depth = q.popleft()
for u in adj[v]:
if u not in s:
s.add(u)
d[depth+1].add(u)
q.append((u,depth+1))
# print(q)
return d
@bootstrap
def dfs(v,adj,n,vis,d,depth,good,back_adj):
# print(v)
vis[v]=1
high = []
depth[v] = d
for u in adj[v]:
if vis[u] == 2:
yield False
if vis[u] == 1:
high = sorted(high+[depth[u]])[:2]
back_adj[v].append(u)
continue
l = yield dfs(u,adj,n,vis,d+1,depth,good,back_adj)
if l == False:
yield False
high = sorted(high+l)[:2]
if len(high) < 2 or max(high) >= d:
# if v == 0:
# print(high)
good[v] = True
vis[v] = 2
yield high
def solution(adj,n,m):
good = [False]*n
vis = [0]*n
depth = [-1]*n
back_adj = [list() for i in range(n)]
l = dfs(0,adj,n,vis,0,depth,good, back_adj)
if l == False or good.count(True) < 0.2*(n):
return -1
for i in range(n):
depth[i] = (depth[i],i)
depth.sort()
for d,i in depth:
for u in back_adj[i]:
if not good[u]:
good[i] = False
break
good = [str(i+1) for i in range(n) if good[i]]
return ' '.join(good)
def main():
T = 1
T = ri()
for i in range(T):
# n = ri()
n,m= ria()
# a = ria()
# s = rs()
adj = [list() for _ in range(n)]
for j in range(m):
a,b = ria()
a-=1;b-=1
adj[a].append(b)
if i == 0:
print('3 2')
continue
x = solution(adj,n,m)
# continue
if 'xrange' not in dir(__builtins__):
print(x) # print("Case #"+str(i+1)+':',x)
else:
print >>output,str(x)
if 'xrange' in dir(__builtins__):
print(output.getvalue())
output.close()
if 'xrange' in dir(__builtins__):
import cStringIO
output = cStringIO.StringIO()
#example usage:
# for l in res:
# print >>output, str(len(l)) + ' ' + ' '.join(l)
if __name__ == '__main__':
main()
``` | instruction | 0 | 57,282 | 1 | 114,564 |
No | output | 1 | 57,282 | 1 | 114,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
James Bond has a new plan for catching his enemy. There are some cities and directed roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there.
The city a is called interesting, if for each city b, there is exactly one simple path from a to b. By a simple path, we understand a sequence of distinct cities, such that for every two neighboring cities, there exists a directed road from the first to the second city.
Bond's enemy is the mistress of escapes, so only the chase started in an interesting city gives the possibility of catching her. James wants to arrange his people in such cities. However, if there are not enough interesting cities, the whole action doesn't make sense since Bond's people may wait too long for the enemy.
You are responsible for finding all the interesting cities or saying that there is not enough of them. By not enough, James means strictly less than 20\% of all cities.
Input
The first line contains one integer t (1 ≤ t ≤ 2 000) — the number of test cases. Each test case is described as follows:
The first line contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of cities and roads between them. Each of the following m lines contains two integers u, v (u ≠ v; 1 ≤ u, v ≤ n), which denote that there is a directed road from u to v.
You can assume that between each ordered pair of cities there is at most one road. The sum of n over all test cases doesn't exceed 10^5, and the sum of m doesn't exceed 2 ⋅ 10^5.
Output
If strictly less than 20\% of all cities are interesting, print -1. Otherwise, let k be the number of interesting cities. Print k distinct integers in increasing order — the indices of interesting cities.
Example
Input
4
3 3
1 2
2 3
3 1
3 6
1 2
2 1
2 3
3 2
1 3
3 1
7 10
1 2
2 3
3 1
1 4
4 5
5 1
4 6
6 7
7 4
6 1
6 8
1 2
2 3
3 4
4 5
5 6
6 1
6 2
5 1
Output
1 2 3
-1
1 2 3 5
-1
Note
In all drawings, if a city is colored green, then it is interesting; otherwise, it is colored red.
In the first sample, each city is interesting.
<image>
In the second sample, no city is interesting.
<image>
In the third sample, cities 1, 2, 3 and 5 are interesting.
<image>
In the last sample, only the city 1 is interesting. It is strictly less than 20\% of all cities, so the answer is -1.
<image>
Submitted Solution:
```
# from math import factorial as fac
from collections import defaultdict
# from copy import deepcopy
import sys, math
f = None
try:
f = open('q1.input', 'r')
except IOError:
f = sys.stdin
if 'xrange' in dir(__builtins__):
range = xrange
# print(f.readline())
# sys.setrecursionlimit(3*10**6)
def print_case_iterable(case_num, iterable):
print("Case #{}: {}".format(case_num," ".join(map(str,iterable))))
def print_case_number(case_num, iterable):
print("Case #{}: {}".format(case_num,iterable))
def print_iterable(A):
print (' '.join(A))
def read_int():
return int(f.readline().strip())
def read_int_array():
return [int(x) for x in f.readline().strip().split(" ")]
def rns():
a = [x for x in f.readline().split(" ")]
return int(a[0]), a[1].strip()
def read_string():
return list(f.readline().strip())
def ri():
return int(f.readline().strip())
def ria():
return [int(x) for x in f.readline().strip().split(" ")]
def rns():
a = [x for x in f.readline().split(" ")]
return int(a[0]), a[1].strip()
def rs():
return list(f.readline().strip())
def bi(x):
return bin(x)[2:]
from collections import deque
import math
NUMBER = 10**9 + 7
# NUMBER = 998244353
def factorial(n) :
M = NUMBER
f = 1
for i in range(1, n + 1):
f = (f * i) % M # Now f never can
# exceed 10^9+7
return f
def mult(a,b):
return (a * b) % NUMBER
def minus(a , b):
return (a - b) % NUMBER
def plus(a , b):
return (a + b) % NUMBER
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a):
m = NUMBER
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def choose(n,k):
if n < k:
assert false
return mult(factorial(n), modinv(mult(factorial(k),factorial(n-k)))) % NUMBER
from collections import deque, defaultdict
import heapq
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
def dfs(g, timeIn, timeOut,depths,parents):
# assign In-time to node u
cnt = 0
# node, neig_i, parent, depth
stack = [[1,0,0,0]]
while stack:
v,neig_i,parent,depth = stack[-1]
parents[v] = parent
depths[v] = depth
# print (v)
if neig_i == 0:
timeIn[v] = cnt
cnt+=1
while neig_i < len(g[v]):
u = g[v][neig_i]
if u == parent:
neig_i+=1
continue
stack[-1][1] = neig_i + 1
stack.append([u,0,v,depth+1])
break
if neig_i == len(g[v]):
stack.pop()
timeOut[v] = cnt
cnt += 1
# def isAncestor(u: int, v: int, timeIn: list, timeOut: list) -> str:
# return timeIn[u] <= timeIn[v] and timeOut[v] <= timeOut[u]
cnt = 0
@bootstrap
def dfs(v,adj,timeIn, timeOut,depths,parents,parent=0,depth=0):
global cnt
parents[v] = parent
depths[v] = depth
timeIn[v] = cnt
cnt+=1
for u in adj[v]:
if u == parent:
continue
yield dfs(u,adj,timeIn,timeOut,depths,parents,v,depth+1)
timeOut[v] = cnt
cnt+=1
yield
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
# Function to return LCM of two numbers
def lcm(a,b):
return (a*b) / gcd(a,b)
def get_num_2_5(n):
twos = 0
fives = 0
while n>0 and n%2 == 0:
n//=2
twos+=1
while n>0 and n%5 == 0:
n//=5
fives+=1
return (twos,fives)
def shift(a,i,num):
for _ in range(num):
a[i],a[i+1],a[i+2] = a[i+2],a[i],a[i+1]
def equal(x,y):
return abs(x-y) <= 1e-9
# def leq(x,y):
# return x-y <= 1e-9
def getAngle(a, b, c):
ang = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))
return ang + 360 if ang < 0 else ang
def getLength(a,b):
return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)
from heapq import heapify, heappush, heappop
def bfs(adj):
s = set()
d = defaultdict(set)
# print('\n'.join(map(str,E.items())))
q = deque([])
s.add(0)
d[0].add(0)
q.append((0,0))
while len(q) > 0:
v,depth = q.popleft()
for u in adj[v]:
if u not in s:
s.add(u)
d[depth+1].add(u)
q.append((u,depth+1))
# print(q)
return d
def isSubsetSum(arr, n, summ):
# The value of subarr[i][j] will be
# true if there is a
# subarr of arr[0..j-1] with summ equal to i
subarr =([[False for i in range(summ + 1)]
for i in range(n + 1)])
# If summ is 0, then answer is true
for i in range(n + 1):
subarr[i][0] = True
# If summ is not 0 and arr is empty,
# then answer is false
for i in range(1, summ + 1):
subarr[0][i]= False
# Fill the subarr table in botton up manner
for i in range(1, n + 1):
for j in range(1, summ + 1):
if j<arr[i-1]:
subarr[i][j] = subarr[i-1][j]
if j>= arr[i-1]:
subarr[i][j] = (subarr[i-1][j] or
subarr[i - 1][j-arr[i-1]])
# uncomment this code to print table
# for i in range(n + 1):
# for j in range(summ + 1):
# print (subset[i][j], end =" ")
# print()
return subarr[n][summ]
def bfs(v,adj,onpath):
# d is a dict for depth
s = set()
d = defaultdict(set)
q = deque([])
s.add(0)
d[0].add(0)
q.append((0,0))
while len(q) > 0:
v,depth = q.popleft()
for u in adj[v]:
if u not in s:
s.add(u)
d[depth+1].add(u)
q.append((u,depth+1))
# print(q)
return d
@bootstrap
def dfs(v,adj,n,vis,d,depth,good,back_adj):
# print(v)
vis[v]=1
high = []
depth[v] = d
for u in adj[v]:
if vis[u] == 2:
yield False
if vis[u] == 1:
high = sorted(high+[depth[u]])[:2]
back_adj[v].append(u)
continue
l = yield dfs(u,adj,n,vis,d+1,depth,good,back_adj)
if l == False:
yield False
high = sorted(high+l)[:2]
if len(high) < 2 or max(high) >= d:
# if v == 0:
# print(high)
good[v] = True
vis[v] = 2
yield high
def solution(adj,n,m):
good = [False]*n
vis = [0]*n
depth = [-1]*n
back_adj = [list() for i in range(n)]
l = dfs(0,adj,n,vis,0,depth,good, back_adj)
if l == False or good.count(True) < 0.2*(n):
return -1
for i in range(n):
depth[i] = (depth[i],i)
depth.sort()
for d,i in depth:
for u in back_adj[i]:
if not good[u]:
good[i] = False
break
good = [str(i+1) for i in range(n) if good[i]]
return ' '.join(good)
def main():
T = 1
T = ri()
for i in range(T):
# n = ri()
n,m= ria()
# a = ria()
# s = rs()
adj = [list() for _ in range(n)]
for j in range(m):
a,b = ria()
a-=1;b-=1
adj[a].append(b)
if i == 10:
print('3 2')
continue
x = solution(adj,n,m)
# continue
if 'xrange' not in dir(__builtins__):
print(x) # print("Case #"+str(i+1)+':',x)
else:
print >>output,str(x)
if 'xrange' in dir(__builtins__):
print(output.getvalue())
output.close()
if 'xrange' in dir(__builtins__):
import cStringIO
output = cStringIO.StringIO()
#example usage:
# for l in res:
# print >>output, str(len(l)) + ' ' + ' '.join(l)
if __name__ == '__main__':
main()
``` | instruction | 0 | 57,283 | 1 | 114,566 |
No | output | 1 | 57,283 | 1 | 114,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
James Bond has a new plan for catching his enemy. There are some cities and directed roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there.
The city a is called interesting, if for each city b, there is exactly one simple path from a to b. By a simple path, we understand a sequence of distinct cities, such that for every two neighboring cities, there exists a directed road from the first to the second city.
Bond's enemy is the mistress of escapes, so only the chase started in an interesting city gives the possibility of catching her. James wants to arrange his people in such cities. However, if there are not enough interesting cities, the whole action doesn't make sense since Bond's people may wait too long for the enemy.
You are responsible for finding all the interesting cities or saying that there is not enough of them. By not enough, James means strictly less than 20\% of all cities.
Input
The first line contains one integer t (1 ≤ t ≤ 2 000) — the number of test cases. Each test case is described as follows:
The first line contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of cities and roads between them. Each of the following m lines contains two integers u, v (u ≠ v; 1 ≤ u, v ≤ n), which denote that there is a directed road from u to v.
You can assume that between each ordered pair of cities there is at most one road. The sum of n over all test cases doesn't exceed 10^5, and the sum of m doesn't exceed 2 ⋅ 10^5.
Output
If strictly less than 20\% of all cities are interesting, print -1. Otherwise, let k be the number of interesting cities. Print k distinct integers in increasing order — the indices of interesting cities.
Example
Input
4
3 3
1 2
2 3
3 1
3 6
1 2
2 1
2 3
3 2
1 3
3 1
7 10
1 2
2 3
3 1
1 4
4 5
5 1
4 6
6 7
7 4
6 1
6 8
1 2
2 3
3 4
4 5
5 6
6 1
6 2
5 1
Output
1 2 3
-1
1 2 3 5
-1
Note
In all drawings, if a city is colored green, then it is interesting; otherwise, it is colored red.
In the first sample, each city is interesting.
<image>
In the second sample, no city is interesting.
<image>
In the third sample, cities 1, 2, 3 and 5 are interesting.
<image>
In the last sample, only the city 1 is interesting. It is strictly less than 20\% of all cities, so the answer is -1.
<image>
Submitted Solution:
```
# from math import factorial as fac
from collections import defaultdict
# from copy import deepcopy
import sys, math
f = None
try:
f = open('q1.input', 'r')
except IOError:
f = sys.stdin
if 'xrange' in dir(__builtins__):
range = xrange
# print(f.readline())
# sys.setrecursionlimit(3*10**6)
def print_case_iterable(case_num, iterable):
print("Case #{}: {}".format(case_num," ".join(map(str,iterable))))
def print_case_number(case_num, iterable):
print("Case #{}: {}".format(case_num,iterable))
def print_iterable(A):
print (' '.join(A))
def read_int():
return int(f.readline().strip())
def read_int_array():
return [int(x) for x in f.readline().strip().split(" ")]
def rns():
a = [x for x in f.readline().split(" ")]
return int(a[0]), a[1].strip()
def read_string():
return list(f.readline().strip())
def ri():
return int(f.readline().strip())
def ria():
return [int(x) for x in f.readline().strip().split(" ")]
def rns():
a = [x for x in f.readline().split(" ")]
return int(a[0]), a[1].strip()
def rs():
return list(f.readline().strip())
def bi(x):
return bin(x)[2:]
from collections import deque
import math
NUMBER = 10**9 + 7
# NUMBER = 998244353
def factorial(n) :
M = NUMBER
f = 1
for i in range(1, n + 1):
f = (f * i) % M # Now f never can
# exceed 10^9+7
return f
def mult(a,b):
return (a * b) % NUMBER
def minus(a , b):
return (a - b) % NUMBER
def plus(a , b):
return (a + b) % NUMBER
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a):
m = NUMBER
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def choose(n,k):
if n < k:
assert false
return mult(factorial(n), modinv(mult(factorial(k),factorial(n-k)))) % NUMBER
from collections import deque, defaultdict
import heapq
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
def dfs(g, timeIn, timeOut,depths,parents):
# assign In-time to node u
cnt = 0
# node, neig_i, parent, depth
stack = [[1,0,0,0]]
while stack:
v,neig_i,parent,depth = stack[-1]
parents[v] = parent
depths[v] = depth
# print (v)
if neig_i == 0:
timeIn[v] = cnt
cnt+=1
while neig_i < len(g[v]):
u = g[v][neig_i]
if u == parent:
neig_i+=1
continue
stack[-1][1] = neig_i + 1
stack.append([u,0,v,depth+1])
break
if neig_i == len(g[v]):
stack.pop()
timeOut[v] = cnt
cnt += 1
# def isAncestor(u: int, v: int, timeIn: list, timeOut: list) -> str:
# return timeIn[u] <= timeIn[v] and timeOut[v] <= timeOut[u]
cnt = 0
@bootstrap
def dfs(v,adj,timeIn, timeOut,depths,parents,parent=0,depth=0):
global cnt
parents[v] = parent
depths[v] = depth
timeIn[v] = cnt
cnt+=1
for u in adj[v]:
if u == parent:
continue
yield dfs(u,adj,timeIn,timeOut,depths,parents,v,depth+1)
timeOut[v] = cnt
cnt+=1
yield
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
# Function to return LCM of two numbers
def lcm(a,b):
return (a*b) / gcd(a,b)
def get_num_2_5(n):
twos = 0
fives = 0
while n>0 and n%2 == 0:
n//=2
twos+=1
while n>0 and n%5 == 0:
n//=5
fives+=1
return (twos,fives)
def shift(a,i,num):
for _ in range(num):
a[i],a[i+1],a[i+2] = a[i+2],a[i],a[i+1]
def equal(x,y):
return abs(x-y) <= 1e-9
# def leq(x,y):
# return x-y <= 1e-9
def getAngle(a, b, c):
ang = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))
return ang + 360 if ang < 0 else ang
def getLength(a,b):
return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)
from heapq import heapify, heappush, heappop
def bfs(adj):
s = set()
d = defaultdict(set)
# print('\n'.join(map(str,E.items())))
q = deque([])
s.add(0)
d[0].add(0)
q.append((0,0))
while len(q) > 0:
v,depth = q.popleft()
for u in adj[v]:
if u not in s:
s.add(u)
d[depth+1].add(u)
q.append((u,depth+1))
# print(q)
return d
def isSubsetSum(arr, n, summ):
# The value of subarr[i][j] will be
# true if there is a
# subarr of arr[0..j-1] with summ equal to i
subarr =([[False for i in range(summ + 1)]
for i in range(n + 1)])
# If summ is 0, then answer is true
for i in range(n + 1):
subarr[i][0] = True
# If summ is not 0 and arr is empty,
# then answer is false
for i in range(1, summ + 1):
subarr[0][i]= False
# Fill the subarr table in botton up manner
for i in range(1, n + 1):
for j in range(1, summ + 1):
if j<arr[i-1]:
subarr[i][j] = subarr[i-1][j]
if j>= arr[i-1]:
subarr[i][j] = (subarr[i-1][j] or
subarr[i - 1][j-arr[i-1]])
# uncomment this code to print table
# for i in range(n + 1):
# for j in range(summ + 1):
# print (subset[i][j], end =" ")
# print()
return subarr[n][summ]
def bfs(v,adj,onpath):
# d is a dict for depth
s = set()
d = defaultdict(set)
q = deque([])
s.add(0)
d[0].add(0)
q.append((0,0))
while len(q) > 0:
v,depth = q.popleft()
for u in adj[v]:
if u not in s:
s.add(u)
d[depth+1].add(u)
q.append((u,depth+1))
# print(q)
return d
@bootstrap
def dfs(v,adj,n,vis,d,depth,good,back_adj):
# print(v)
vis[v]=1
high = []
depth[v] = d
for u in adj[v]:
if vis[u] == 2:
yield False
if vis[u] == 1:
high = sorted(high+[depth[u]])[:2]
back_adj[v].append(u)
continue
l = yield dfs(u,adj,n,vis,d+1,depth,good,back_adj)
if l == False:
yield False
high = sorted(high+l)[:2]
if len(high) < 2 or max(high) >= d:
# if v == 0:
# print(high)
good[v] = True
vis[v] = 2
yield high
def solution(adj,n,m):
good = [False]*n
vis = [0]*n
depth = [-1]*n
back_adj = [list() for i in range(n)]
l = dfs(0,adj,n,vis,0,depth,good, back_adj)
if l == False or good.count(True) < 0.2*(n):
return -1
for i in range(n):
depth[i] = (depth[i],i)
depth.sort()
for d,i in depth:
for u in back_adj[i]:
if not good[u]:
good[i] = False
break
good = [str(i+1) for i in range(n) if good[i]]
return ' '.join(good)
def main():
T = 1
T = ri()
for i in range(T):
# n = ri()
n,m= ria()
# a = ria()
# s = rs()
adj = [list() for _ in range(n)]
for j in range(m):
a,b = ria()
a-=1;b-=1
adj[a].append(b)
if i == 11:
print('3 2')
continue
x = solution(adj,n,m)
# continue
if 'xrange' not in dir(__builtins__):
print(x) # print("Case #"+str(i+1)+':',x)
else:
print >>output,str(x)
if 'xrange' in dir(__builtins__):
print(output.getvalue())
output.close()
if 'xrange' in dir(__builtins__):
import cStringIO
output = cStringIO.StringIO()
#example usage:
# for l in res:
# print >>output, str(len(l)) + ' ' + ' '.join(l)
if __name__ == '__main__':
main()
``` | instruction | 0 | 57,284 | 1 | 114,568 |
No | output | 1 | 57,284 | 1 | 114,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
James Bond has a new plan for catching his enemy. There are some cities and directed roads between them, such that it is possible to travel between any two cities using these roads. When the enemy appears in some city, Bond knows her next destination but has no idea which path she will choose to move there.
The city a is called interesting, if for each city b, there is exactly one simple path from a to b. By a simple path, we understand a sequence of distinct cities, such that for every two neighboring cities, there exists a directed road from the first to the second city.
Bond's enemy is the mistress of escapes, so only the chase started in an interesting city gives the possibility of catching her. James wants to arrange his people in such cities. However, if there are not enough interesting cities, the whole action doesn't make sense since Bond's people may wait too long for the enemy.
You are responsible for finding all the interesting cities or saying that there is not enough of them. By not enough, James means strictly less than 20\% of all cities.
Input
The first line contains one integer t (1 ≤ t ≤ 2 000) — the number of test cases. Each test case is described as follows:
The first line contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of cities and roads between them. Each of the following m lines contains two integers u, v (u ≠ v; 1 ≤ u, v ≤ n), which denote that there is a directed road from u to v.
You can assume that between each ordered pair of cities there is at most one road. The sum of n over all test cases doesn't exceed 10^5, and the sum of m doesn't exceed 2 ⋅ 10^5.
Output
If strictly less than 20\% of all cities are interesting, print -1. Otherwise, let k be the number of interesting cities. Print k distinct integers in increasing order — the indices of interesting cities.
Example
Input
4
3 3
1 2
2 3
3 1
3 6
1 2
2 1
2 3
3 2
1 3
3 1
7 10
1 2
2 3
3 1
1 4
4 5
5 1
4 6
6 7
7 4
6 1
6 8
1 2
2 3
3 4
4 5
5 6
6 1
6 2
5 1
Output
1 2 3
-1
1 2 3 5
-1
Note
In all drawings, if a city is colored green, then it is interesting; otherwise, it is colored red.
In the first sample, each city is interesting.
<image>
In the second sample, no city is interesting.
<image>
In the third sample, cities 1, 2, 3 and 5 are interesting.
<image>
In the last sample, only the city 1 is interesting. It is strictly less than 20\% of all cities, so the answer is -1.
<image>
Submitted Solution:
```
# from math import factorial as fac
from collections import defaultdict
# from copy import deepcopy
import sys, math
f = None
try:
f = open('q1.input', 'r')
except IOError:
f = sys.stdin
if 'xrange' in dir(__builtins__):
range = xrange
# print(f.readline())
# sys.setrecursionlimit(3*10**6)
def print_case_iterable(case_num, iterable):
print("Case #{}: {}".format(case_num," ".join(map(str,iterable))))
def print_case_number(case_num, iterable):
print("Case #{}: {}".format(case_num,iterable))
def print_iterable(A):
print (' '.join(A))
def read_int():
return int(f.readline().strip())
def read_int_array():
return [int(x) for x in f.readline().strip().split(" ")]
def rns():
a = [x for x in f.readline().split(" ")]
return int(a[0]), a[1].strip()
def read_string():
return list(f.readline().strip())
def ri():
return int(f.readline().strip())
def ria():
return [int(x) for x in f.readline().strip().split(" ")]
def rns():
a = [x for x in f.readline().split(" ")]
return int(a[0]), a[1].strip()
def rs():
return list(f.readline().strip())
def bi(x):
return bin(x)[2:]
from collections import deque
import math
NUMBER = 10**9 + 7
# NUMBER = 998244353
def factorial(n) :
M = NUMBER
f = 1
for i in range(1, n + 1):
f = (f * i) % M # Now f never can
# exceed 10^9+7
return f
def mult(a,b):
return (a * b) % NUMBER
def minus(a , b):
return (a - b) % NUMBER
def plus(a , b):
return (a + b) % NUMBER
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a):
m = NUMBER
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def choose(n,k):
if n < k:
assert false
return mult(factorial(n), modinv(mult(factorial(k),factorial(n-k)))) % NUMBER
from collections import deque, defaultdict
import heapq
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
def dfs(g, timeIn, timeOut,depths,parents):
# assign In-time to node u
cnt = 0
# node, neig_i, parent, depth
stack = [[1,0,0,0]]
while stack:
v,neig_i,parent,depth = stack[-1]
parents[v] = parent
depths[v] = depth
# print (v)
if neig_i == 0:
timeIn[v] = cnt
cnt+=1
while neig_i < len(g[v]):
u = g[v][neig_i]
if u == parent:
neig_i+=1
continue
stack[-1][1] = neig_i + 1
stack.append([u,0,v,depth+1])
break
if neig_i == len(g[v]):
stack.pop()
timeOut[v] = cnt
cnt += 1
# def isAncestor(u: int, v: int, timeIn: list, timeOut: list) -> str:
# return timeIn[u] <= timeIn[v] and timeOut[v] <= timeOut[u]
cnt = 0
@bootstrap
def dfs(v,adj,timeIn, timeOut,depths,parents,parent=0,depth=0):
global cnt
parents[v] = parent
depths[v] = depth
timeIn[v] = cnt
cnt+=1
for u in adj[v]:
if u == parent:
continue
yield dfs(u,adj,timeIn,timeOut,depths,parents,v,depth+1)
timeOut[v] = cnt
cnt+=1
yield
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
# Function to return LCM of two numbers
def lcm(a,b):
return (a*b) / gcd(a,b)
def get_num_2_5(n):
twos = 0
fives = 0
while n>0 and n%2 == 0:
n//=2
twos+=1
while n>0 and n%5 == 0:
n//=5
fives+=1
return (twos,fives)
def shift(a,i,num):
for _ in range(num):
a[i],a[i+1],a[i+2] = a[i+2],a[i],a[i+1]
def equal(x,y):
return abs(x-y) <= 1e-9
# def leq(x,y):
# return x-y <= 1e-9
def getAngle(a, b, c):
ang = math.degrees(math.atan2(c[1]-b[1], c[0]-b[0]) - math.atan2(a[1]-b[1], a[0]-b[0]))
return ang + 360 if ang < 0 else ang
def getLength(a,b):
return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)
from heapq import heapify, heappush, heappop
def bfs(adj):
s = set()
d = defaultdict(set)
# print('\n'.join(map(str,E.items())))
q = deque([])
s.add(0)
d[0].add(0)
q.append((0,0))
while len(q) > 0:
v,depth = q.popleft()
for u in adj[v]:
if u not in s:
s.add(u)
d[depth+1].add(u)
q.append((u,depth+1))
# print(q)
return d
def isSubsetSum(arr, n, summ):
# The value of subarr[i][j] will be
# true if there is a
# subarr of arr[0..j-1] with summ equal to i
subarr =([[False for i in range(summ + 1)]
for i in range(n + 1)])
# If summ is 0, then answer is true
for i in range(n + 1):
subarr[i][0] = True
# If summ is not 0 and arr is empty,
# then answer is false
for i in range(1, summ + 1):
subarr[0][i]= False
# Fill the subarr table in botton up manner
for i in range(1, n + 1):
for j in range(1, summ + 1):
if j<arr[i-1]:
subarr[i][j] = subarr[i-1][j]
if j>= arr[i-1]:
subarr[i][j] = (subarr[i-1][j] or
subarr[i - 1][j-arr[i-1]])
# uncomment this code to print table
# for i in range(n + 1):
# for j in range(summ + 1):
# print (subset[i][j], end =" ")
# print()
return subarr[n][summ]
def bfs(v,adj,onpath):
# d is a dict for depth
s = set()
d = defaultdict(set)
q = deque([])
s.add(0)
d[0].add(0)
q.append((0,0))
while len(q) > 0:
v,depth = q.popleft()
for u in adj[v]:
if u not in s:
s.add(u)
d[depth+1].add(u)
q.append((u,depth+1))
# print(q)
return d
@bootstrap
def dfs(v,adj,n,vis,d,depth,good,back_adj):
# print(v)
vis[v]=1
high = []
depth[v] = d
for u in adj[v]:
if vis[u] == 2:
yield False
if vis[u] == 1:
high = sorted(high+[depth[u]])[:2]
back_adj[v].append(u)
continue
l = yield dfs(u,adj,n,vis,d+1,depth,good,back_adj)
if l == False:
yield False
high = sorted(high+l)[:2]
if len(high) < 2 or max(high) >= d:
# if v == 0:
# print(high)
good[v] = True
vis[v] = 2
yield high
def solution(adj,n,m):
good = [False]*n
vis = [0]*n
depth = [-1]*n
back_adj = [list() for i in range(n)]
l = dfs(0,adj,n,vis,0,depth,good, back_adj)
if l == False or good.count(True) < 0.2*(n):
return -1
for i in range(n):
depth[i] = (depth[i],i)
depth.sort()
for d,i in depth:
for u in back_adj[i]:
if not good[u]:
good[i] = False
break
good = [str(i+1) for i in range(n) if good[i]]
return ' '.join(good)
def main():
T = 1
T = ri()
for i in range(T):
# n = ri()
n,m= ria()
# a = ria()
# s = rs()
adj = [list() for _ in range(n)]
for j in range(m):
a,b = ria()
a-=1;b-=1
adj[a].append(b)
x = solution(adj,n,m)
# continue
if 'xrange' not in dir(__builtins__):
print(x) # print("Case #"+str(i+1)+':',x)
else:
print >>output,str(x)
if 'xrange' in dir(__builtins__):
print(output.getvalue())
output.close()
if 'xrange' in dir(__builtins__):
import cStringIO
output = cStringIO.StringIO()
#example usage:
# for l in res:
# print >>output, str(len(l)) + ' ' + ' '.join(l)
if __name__ == '__main__':
main()
``` | instruction | 0 | 57,285 | 1 | 114,570 |
No | output | 1 | 57,285 | 1 | 114,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:
* There is no road between a and b.
* There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for <image>.
On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for <image>.
Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.
Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.
Input
The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively.
The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).
Output
Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d.
Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.
Examples
Input
7 11
2 4 7 3
Output
2 7 1 3 6 5 4
7 1 5 4 6 2 3
Input
1000 999
10 20 30 40
Output
-1
Note
In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.
<image> | instruction | 0 | 57,603 | 1 | 115,206 |
Tags: constructive algorithms, graphs
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, k = map(int, input().split())
a, b, c, d = map(int, input().split())
x = [a, b, c, d]
if k < n + 1 or n == 4:
print("-1")
exit(0)
l = [_ for _ in range(1, n + 1)]
for i in x: l.remove(i)
print("{} {}".format(a, c), end = ' ')
for x in l: print(x, end = ' ')
print("{} {}\n{} {}".format(d, b, c, a), end = ' ')
for x in l: print(x, end = ' ')
print("{} {}".format(b, d))
``` | output | 1 | 57,603 | 1 | 115,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:
* There is no road between a and b.
* There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for <image>.
On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for <image>.
Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.
Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.
Input
The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively.
The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).
Output
Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d.
Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.
Examples
Input
7 11
2 4 7 3
Output
2 7 1 3 6 5 4
7 1 5 4 6 2 3
Input
1000 999
10 20 30 40
Output
-1
Note
In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.
<image> | instruction | 0 | 57,604 | 1 | 115,208 |
Tags: constructive algorithms, graphs
Correct Solution:
```
import sys
print = sys.stdout.write
n, k = map(int, input().split())
a, b, c, d = map(int, input().split())
if n == 4 or k < n+1:
print("-1\n")
exit()
print(f"{a} {c} ")
for i in range(1, n+1):
if i not in (a, b, c, d):
print(f"{i} ")
print(f"{d} {b}\n")
print(f"{c} {a} ")
for i in range(1, n+1):
if i not in (a, b, c, d):
print(f"{i} ")
print(f"{b} {d}\n")
``` | output | 1 | 57,604 | 1 | 115,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:
* There is no road between a and b.
* There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for <image>.
On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for <image>.
Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.
Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.
Input
The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively.
The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).
Output
Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d.
Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.
Examples
Input
7 11
2 4 7 3
Output
2 7 1 3 6 5 4
7 1 5 4 6 2 3
Input
1000 999
10 20 30 40
Output
-1
Note
In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.
<image> | instruction | 0 | 57,605 | 1 | 115,210 |
Tags: constructive algorithms, graphs
Correct Solution:
```
def main():
(n, k) = (int(x) for x in input().split())
(a, b, c, d) = (int(x) for x in input().split())
(path1, path2) = solver(n, k, a, b, c, d)
if path1 == None:
print(-1)
else:
for x in path1:
print(x, end = ' ')
print()
for x in path2:
print(x, end = ' ')
def solver(n, k, a, b, c, d):
if k <= n or n == 4:
return (None, None)
else:
path1 = [a, c] + \
[i for i in range(1, n + 1) if i not in (a, b, c, d)] + \
[d, b]
path2 = [c, a] + \
[i for i in range(1, n + 1) if i not in (a, b, c, d)] + \
[b, d]
return (path1, path2)
main()
#print(solver(7, 11, 2, 4, 7, 3))
# def reorder(path, n, a, b, c, d):
# for i in range(len(path)):
# if path[i] == a:
# path[i] = 1
# elif path[i] == b:
# path[i] = n
# elif path[i] == c:
# path[i] = 2
# elif path[i] == d:
# path[i] = 3
# elif path[i] == 1:
# path[i] = a
# elif path[i] == n:
# path[i] = b
# elif path[i] == 2:
# path[i] = c
# elif path[i] == 3:
# path[i] = d
``` | output | 1 | 57,605 | 1 | 115,211 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:
* There is no road between a and b.
* There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for <image>.
On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for <image>.
Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.
Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.
Input
The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively.
The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).
Output
Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d.
Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.
Examples
Input
7 11
2 4 7 3
Output
2 7 1 3 6 5 4
7 1 5 4 6 2 3
Input
1000 999
10 20 30 40
Output
-1
Note
In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.
<image> | instruction | 0 | 57,606 | 1 | 115,212 |
Tags: constructive algorithms, graphs
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, k = map(int, input().split())
a, b, c, d = map(int, input().split())
if k < n + 1 or n == 4:
print("-1")
exit(0)
l = [_ for _ in range(1, n + 1)]
l.remove(a)
l.remove(b)
l.remove(c)
l.remove(d)
print(a, end = ' ')
print(c, end = ' ')
for x in l:
print(x, end = ' ')
print(d, end = ' ')
print(b, end = ' ')
print("")
print(c, end = ' ')
print(a, end = ' ')
for x in l:
print(x, end = ' ')
print(b, end = ' ')
print(d, end = ' ')
``` | output | 1 | 57,606 | 1 | 115,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:
* There is no road between a and b.
* There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for <image>.
On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for <image>.
Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.
Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.
Input
The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively.
The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).
Output
Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d.
Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.
Examples
Input
7 11
2 4 7 3
Output
2 7 1 3 6 5 4
7 1 5 4 6 2 3
Input
1000 999
10 20 30 40
Output
-1
Note
In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.
<image> | instruction | 0 | 57,607 | 1 | 115,214 |
Tags: constructive algorithms, graphs
Correct Solution:
```
n, k = input().split(' ')
n = int(n)
k = int(k)
a,b,c,d = input().split(' ')
a,b,c,d = int(a),int(b),int(c),int(d)
if k <= n:
print(-1)
exit()
if n == 4:
print(-1)
exit()
city = list(range(1,n+1))
road = [a,c]
for i in range(len(city)):
if city[i] not in (a,b,c,d): road.append(city[i])
road += [d,b]
t = ''
print(' '.join("{0}".format(t) for t in road))
road = [c,a] + road[2:n-2] + [b,d]
print(' '.join("{0}".format(t) for t in road))
``` | output | 1 | 57,607 | 1 | 115,215 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.