message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). | instruction | 0 | 91,995 | 13 | 183,990 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
n, k = map(int, input().split())
t, q = [[] for i in range(n + 1)], [1]
for j in range(n - 1):
a, b = map(int, input().split())
t[a].append(b)
t[b].append(a)
for x in q:
for y in t[x]: t[y].remove(x)
q.extend(t[x])
q.reverse()
a, s = {}, 0
for x in q:
a[x] = [1]
u = len(a[x])
for y in t[x]:
v = len(a[y])
for d in range(max(0, k - u), v): s += a[y][d] * a[x][k - d - 1]
if v >= u:
for d in range(u - 1): a[x][d + 1] += a[y][d]
a[x] += a[y][u - 1: ]
u = v + 1
else:
for d in range(0, v): a[x][d + 1] += a[y][d]
if u > k: a[x].pop()
print(s)
``` | output | 1 | 91,995 | 13 | 183,991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). | instruction | 0 | 91,996 | 13 | 183,992 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
n,k=map(int,input().split())
g=[[] for i in range(n)]
for _ in range(n-1):
a,b=map(int,input().split())
g[a-1].append(b-1)
g[b-1].append(a-1)
q=[0]
for x in q:
for y in g[x]:
g[y].remove(x)
q.extend(g[x])
q.reverse()
d,cnt={},0
for x in q:
d[x]=[1]
l_x=len(d[x])
for to in g[x]:
l_to=len(d[to])
for i in range(max(0,k-l_x),l_to):cnt+=d[to][i]*d[x][k-i-1]
if l_to>=l_x:
for i in range(l_x-1):d[x][i+1]+=d[to][i]
d[x]+=d[to][l_x-1:]
l_x=l_to+1
else:
for i in range(l_to):d[x][i+1]+=d[to][i]
if l_x>k:
d[x].pop()
print(cnt)
``` | output | 1 | 91,996 | 13 | 183,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). | instruction | 0 | 91,997 | 13 | 183,994 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from collections import defaultdict,Counter
from copy import deepcopy
def solve(k,path,path1,lst):
st = [1]
while len(st):
if not len(path[st[-1]]):
x = st.pop()
if len(st):
for i in range(k):
lst[st[-1]][i+1] += lst[x][i]
continue
i = path[st[-1]].pop()
path[i].remove(st[-1])
st.append(i)
ans = lst[1][k]
st = [1]
while len(st):
if not len(path1[st[-1]]):
st.pop()
continue
i = path1[st[-1]].pop()
path1[i].remove(st[-1])
for j in range(k-1,0,-1):
lst[i][j+1] += lst[st[-1]][j]-lst[i][j-1]
lst[st[-1]][k] -= lst[i][k-1]
lst[i][1] += lst[st[-1]][0]
ans += lst[i][k]
st.append(i)
print(ans//2)
def main():
n,k = map(int,input().split())
path = defaultdict(set)
for _ in range(n-1):
u,v = map(int,input().split())
path[u].add(v)
path[v].add(u)
path1 = deepcopy(path)
lst = [[1]+[0]*k for _ in range(n+1)]
solve(k,path,path1,lst)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | output | 1 | 91,997 | 13 | 183,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). | instruction | 0 | 91,998 | 13 | 183,996 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
def main():
n,k=map(int,input().split())
tree=[[] for _ in range(n+1)]
for _ in range(n-1):
a,b=map(int,input().split())
tree[a].append(b)
tree[b].append(a)
dp=[[0 for _ in range(k+1)] for _ in range(n+1)]
# using dfs
stack=[(1,0)]
# root at 1
idx=[0]*(n+1)
dp[1][0]=1
ans=0
while stack:
x,p=stack[-1]
y=idx[x]
if y==len(tree[x]):
if x==1:
break
stack.pop()
# shifting all distances by 1 for parent
for i in range(k,0,-1):
dp[x][i]=dp[x][i-1]
dp[x][0]=0
for i in range(k):
ans+=dp[p][i]*dp[x][k-i]
dp[p][i]+=dp[x][i]
else:
z=tree[x][y]
if z!=p:
stack.append((z,x))
dp[z][0]=1
idx[x]+=1
print(ans)
#----------------------------------------------------------------------------------------
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
``` | output | 1 | 91,998 | 13 | 183,997 |
Provide tags and a correct Python 2 solution for this coding contest problem.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4). | instruction | 0 | 91,999 | 13 | 183,998 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
for i in arr:
stdout.write(str(i)+' ')
stdout.write('\n')
range = xrange # not for python 3.0+
n,k=in_arr()
d=[[] for i in range(n+1)]
for i in range(n-1):
u,v=in_arr()
d[u].append(v)
d[v].append(u)
dp=[[0 for i in range(k+1)] for i in range(n+1)]
q=[1]
pos=0
vis=[0]*(n+1)
vis[1]=1
while pos<n:
x=q[pos]
pos+=1
for i in d[x]:
if not vis[i]:
vis[i]=1
q.append(i)
ans=0
ans1=0
while q:
x=q.pop()
vis[x]=0
temp=[]
dp[x][0]=1
for i in d[x]:
if not vis[i]:
temp.append(i)
for j in range(k):
dp[x][j+1]+=dp[i][j]
#print x,temp
for i in temp:
for j in range(1,k):
#print j,(dp[x][k-j]-dp[i][k-j-1]),dp[i][j-1]
ans1+=(dp[x][k-j]-dp[i][k-j-1])*dp[i][j-1]
ans+=dp[x][k]
print ans+(ans1/2)
``` | output | 1 | 91,999 | 13 | 183,999 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).
Submitted Solution:
```
###pyrival template for fast IO
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##make the tree
n,k=[int(x) for x in input().split()]
if n==1:
print(0)
else:
tree={1:[]}
for i in range(n-1):
a,b=[int(x) for x in input().split()]
if a not in tree:
tree[a]=[b]
else:
tree[a].append(b)
if b not in tree:
tree[b]=[a]
else:
tree[b].append(a)
def dfs(graph,n,currnode):
visited=[False for x in range(n+1)]
stack=[currnode]
index=[0 for x in range(n+1)]
parent=[0 for x in range(n+1)]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
for i in range(index[currnode],len(graph[currnode])):
neighbour=graph[currnode][i]
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
parent[neighbour]=currnode
index[currnode]+=1
break
else:
for i in range(k+2):
d[parent[currnode]][i+1]+=d[currnode][i]
stack.pop()
ans[1]=d[1][k]
return
d=[[0 for x in range(k+3)] for x in range(n+1)]
for i in range(1,n+1):
d[i][0]=1
ans=[0 for x in range(n+1)]
dfs(tree,n,1)
def dfs1(graph,n,currnode):
visited=[False for x in range(n+1)]
stack=[currnode]
index=[0 for x in range(n+1)]
parent=[0 for x in range(n+1)]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
for i in range(index[currnode],len(graph[currnode])):
neighbour=graph[currnode][i]
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
parent[neighbour]=currnode
index[currnode]+=1
for i in range(k+2):
d[currnode][i+1]-=d[neighbour][i]
for i in range(k+2):
d[neighbour][i+1]+=d[currnode][i]
ans[neighbour]=d[neighbour][k]
break
else:
for i in range(k+2):
d[currnode][i+1]-=d[parent[currnode]][i]
for i in range(k+2):
d[parent[currnode]][i+1]+=d[currnode][i]
stack.pop()
return
dfs1(tree,n,1)
print(sum(ans[1:])//2)
``` | instruction | 0 | 92,000 | 13 | 184,000 |
Yes | output | 1 | 92,000 | 13 | 184,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).
Submitted Solution:
```
p, q, s = [[] for i in range(50001)], [[] for i in range(50001)], 0
n, k = map(int, input().split())
for i in range(n - 1):
a, b = map(int, input().split())
p[a].append(b)
p[b].append(a)
def f(a, c):
global s, k, p, q
for b in p[a]:
if b == c: continue
f(b, a)
l = len(q[a]) + len(q[b]) - k
s += sum(q[a][j] * q[b][l - j] for j in range(max(0, l - len(q[b]) + 1), min(len(q[a]), l + 1)))
if len(q[a]) < len(q[b]): q[a], q[b] = q[b], q[a]
for j in range(len(q[b])): q[a][- j] += q[b][- j]
q[a].append(1)
if k < len(q[a]): s += q[a][- k - 1]
f(1, 0)
print(s)
``` | instruction | 0 | 92,001 | 13 | 184,002 |
No | output | 1 | 92,001 | 13 | 184,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).
Submitted Solution:
```
l=[0]*50000000
print(len(l))
``` | instruction | 0 | 92,002 | 13 | 184,004 |
No | output | 1 | 92,002 | 13 | 184,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).
Submitted Solution:
```
try :
l=[0]*100000000
print(len(l))
except Exception as e :
print(e)
``` | instruction | 0 | 92,003 | 13 | 184,006 |
No | output | 1 | 92,003 | 13 | 184,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.
Input
The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices.
Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.
Output
Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
5 2
1 2
2 3
3 4
2 5
Output
4
Input
5 3
1 2
2 3
3 4
4 5
Output
2
Note
In the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).
Submitted Solution:
```
def dot(a,b):
c = []
for i in range(0,len(a)):
temp=[]
for j in range(0,len(b[0])):
s = 0
for k in range(0,len(a[0])):
s += a[i][k]*b[k][j]
temp.append(s)
c.append(temp)
return c
x=input()
N=int(x.split(" ")[0])
length=int(x.split(" ")[1])
z=[]
for i in range(N):
z.append([])
for j in range(N):
z[i].append(0)
for i in range(N-1):
x=input()
a=int(x.split(" ")[0])
b=int(x.split(" ")[1])
z[a-1][b-1]=1
z[b-1][a-1]=1
zz=dot(z,z)
for i in range(length-1):
zz=dot(z,zz)
ans=0
for i in range(N):
for j in range(i):
if zz[i][j]==1:
ans+=1
print(ans*2)
``` | instruction | 0 | 92,004 | 13 | 184,008 |
No | output | 1 | 92,004 | 13 | 184,009 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No | instruction | 0 | 92,465 | 13 | 184,930 |
"Correct Solution:
```
import sys,time
sys.setrecursionlimit(10**7)
start_time = time.time()
N,M = map(int,input().split())
S = input()
src = [tuple(map(lambda x:int(x)-1,sys.stdin.readline().split())) for i in range(M)]
outdeg = [set() for i in range(2*N)]
for x,y in src:
if S[x] == S[y]:
#A0->A1, B0->B1
outdeg[x].add(y+N)
outdeg[y].add(x+N)
else:
#A1->B0, B1->A0
outdeg[x+N].add(y)
outdeg[y+N].add(x)
mem = [0] * (2*N)
def visit(v):
if time.time() - start_time > 1.8:
# gori~~~
print('No')
exit()
if mem[v] == 1:
print('Yes')
exit()
if mem[v] == 0:
mem[v] = 1
for to in outdeg[v]:
visit(to)
mem[v] = 2
for i in range(2*N):
visit(i)
print('No')
``` | output | 1 | 92,465 | 13 | 184,931 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No | instruction | 0 | 92,466 | 13 | 184,932 |
"Correct Solution:
```
def examC():
N,M = LI()
S = SI()
V = [[] for _ in range(N)]
ok = [1]*N
acnt = [0]*N; bcnt = [0]*N
for _ in range(M):
a, b = LI()
V[a-1].append(b-1)
V[b-1].append(a-1)
if S[a-1]=="A":
acnt[b-1] +=1
else:
bcnt[b-1] +=1
if S[b-1]=="A":
acnt[a-1] +=1
else:
bcnt[a-1] +=1
NGque = deque()
for i in range(N):
if acnt[i]==0 or bcnt[i]==0:
ok[i]=0
NGque.append(i)
# print(ok,acnt,bcnt)
# print(NGque)
while(NGque):
cur = NGque.pop()
for i in V[cur]:
if ok[i]==1:
if S[cur] == "A":
acnt[i] -= 1
else:
bcnt[i] -= 1
if acnt[i] == 0 or bcnt[i] == 0:
ok[i] = 0
NGque.append(i)
if max(ok)==1:
ans = "Yes"
else:
ans = "No"
print(ans)
import sys,copy,bisect,itertools,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
mod = 10**9 + 7
inf = float('inf')
examC()
``` | output | 1 | 92,466 | 13 | 184,933 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No | instruction | 0 | 92,467 | 13 | 184,934 |
"Correct Solution:
```
n, m = map(int, input().split())
s = input()
g = [[] for _ in range(n)]
for _ in range(m):
a, b = map(int, input().split())
g[a-1].append(b-1)
g[b-1].append(a-1)
count = [[0, 0] for _ in range(n)]
bad = []
for i in range(n):
for v in g[i]:
if s[v] == 'A':
count[i][0] += 1
else:
count[i][1] += 1
if count[i][0]*count[i][1] == 0:
bad.append(i)
visited = [False]*n
while bad:
v = bad.pop()
if visited[v]:
continue
visited[v] = True
for w in g[v]:
if not visited[w]:
if s[v] == 'A':
count[w][0] -= 1
else:
count[w][1] -= 1
if count[w][0]*count[w][1] == 0:
bad.append(w)
for i in range(n):
if count[i][0]*count[i][1] > 0:
print('Yes')
exit()
print('No')
``` | output | 1 | 92,467 | 13 | 184,935 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No | instruction | 0 | 92,468 | 13 | 184,936 |
"Correct Solution:
```
from collections import deque
N, M = map(int, input().split())
S = input()
# 頂点iがラベルA・Bの頂点といくつ隣接しているか
connect_label = [[0, 0] for i in range(N)]
# 削除する予定の頂点を管理するキュー
queue = deque()
# 削除済みの頂点を管理する集合
deleted_set = set()
# 各頂点の連結情報
G = [[] for i in range(N)]
# 辺の情報を入力
for i in range(M):
a, b = map(int, input().split())
a, b = a-1, b-1
G[a].append(b)
G[b].append(a)
connect_label[a][1 - (S[b] == "A")] += 1
connect_label[b][1 - (S[a] == "A")] += 1
# AまたはBのみとしか連結してないものをキューに追加
for i in range(N):
if 0 in connect_label[i]:
queue.append(i)
# キューが空になるまで削除を繰り返す
while queue:
n = queue.pop()
# すでに削除していれば何もしない
if n in deleted_set:
continue
# 連結していた頂点について情報を書き換える
for v in G[n]:
connect_label[v][1 - (S[n] == "A")] -= 1
# 未削除で、AまたはBのみとしか連結しなくなったものはキューに追加
if (v not in deleted_set) and (0 in connect_label[v]):
queue.appendleft(v)
deleted_set.add(n)
# 全て削除していたらNo, そうでなければYes
print("Yes" if len(deleted_set) != N else "No")
``` | output | 1 | 92,468 | 13 | 184,937 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No | instruction | 0 | 92,469 | 13 | 184,938 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
S = input().rstrip()
AB = []
AA = []
BB = []
for _ in range(M):
a, b = map(int, input().split())
if S[a-1] == "A" and S[b-1] == "B":
AB.append((a-1, b-1))
elif S[a-1] == "B" and S[b-1] == "A":
AB.append((b-1, a-1))
elif S[a-1] == "A":
AA.append((a-1, b-1))
else:
BB.append((a-1, b-1))
graph = [set() for _ in range(2*N)]
to_A = [False]*N
to_B = [False]*N
for a, b in AB:
graph[a].add(b)
graph[b+N].add(a+N)
to_B[a] = True
to_A[b] = True
for a, b in AA:
if to_B[a] or to_B[b]:
graph[b+N].add(a)
graph[a+N].add(b)
for a, b in BB:
if to_A[a] or to_A[b]:
graph[a].add(b+N)
graph[b].add(a+N)
Color = [-1]*(2*N)
loop = False
for n in range(2*N):
if Color[n] != -1:
continue
stack = [n]
Color[n] = n
while stack:
p = stack[-1]
update = False
for np in graph[p]:
if Color[np] == -1:
update = True
Color[np] = n
stack.append(np)
break
elif len(stack) > 1:
if np != stack[-2] and Color[np] == n:
loop = True
break
if not update:
stack.pop()
Color[p] = 10**14
if loop:
break
if loop:
break
print("Yes" if loop else "No")
``` | output | 1 | 92,469 | 13 | 184,939 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No | instruction | 0 | 92,470 | 13 | 184,940 |
"Correct Solution:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
GC027 C
"""
n,m = map(int,input().split())
s = list(input())
ali = [0 for i in range(n)]
bli = [0 for i in range(n)]
from collections import defaultdict
graphAB = defaultdict(list)
for i in range(m):
u,v=map(int,input().split())
graphAB[u].append(v)
graphAB[v].append(u)
def incrementAB(node,adj):
if s[adj-1] == 'A':
ali[node-1]+=1
if s[adj-1] == 'B':
bli[node-1]+=1
def decrementAB(node,adj):
if s[adj-1] == 'A':
ali[node-1]-=1
if s[adj-1] == 'B':
bli[node-1]-=1
def adjAB(node):
if ali[node-1]!=0 and bli[node-1]!=0:
return(True)
else:
return(False)
graphvers = set(graphAB.keys())
visitset = set()
for i in range(1,n+1):
if not i in graphvers:
s[i-1] = 'C'
else:
for j in graphAB[i]:
incrementAB(i,j)
if not adjAB(i):
visitset.add(i)
while bool(visitset):
#print(graphAB)
#print(graphABopp)
#print(abli)
i = visitset.pop()
gen = (j for j in graphAB[i] if s[j-1]!='C')
for j in gen:
decrementAB(j,i)
if not adjAB(j):
visitset.add(j)
s[i-1] = 'C'
#print(graphAB)
#print(graphABopp)
sset= set(s)
sset.add('C')
sset.remove('C')
if bool(sset):
print('Yes')
else:
print('No')
``` | output | 1 | 92,470 | 13 | 184,941 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No | instruction | 0 | 92,471 | 13 | 184,942 |
"Correct Solution:
```
N,M=map(int,input().split())
S="0"+input()
E=[[] for i in range(N+1)]
AOUT=[0]*(N+1)
BOUT=[0]*(N+1)
for i in range(M):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
if S[x]=="A":
AOUT[y]+=1
else:
BOUT[y]+=1
if S[y]=="A":
AOUT[x]+=1
else:
BOUT[x]+=1
from collections import deque
Q=deque()
USE=[0]*(N+1)
for i in range(N+1):
if AOUT[i]==0 or BOUT[i]==0:
Q.append(i)
USE[i]=1
while Q:
x=Q.pop()
for to in E[x]:
if USE[to]==0:
if S[x]=="A":
AOUT[to]-=1
else:
BOUT[to]-=1
if AOUT[to]==0 or BOUT[to]==0:
Q.append(to)
USE[to]=1
if 0 in USE:
print("Yes")
else:
print("No")
``` | output | 1 | 92,471 | 13 | 184,943 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No | instruction | 0 | 92,472 | 13 | 184,944 |
"Correct Solution:
```
from collections import deque
n, m = map(int, input().split())
s = input()
info = [list(map(int, input().split())) for i in range(m)]
graph = [[] for i in range(n)]
for i in range(m):
a, b = info[i]
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
v_num = [0] * n
for i in range(n):
if s[i] == "B":
v_num[i] = 1
q = deque([])
used = [False] * n
v_cnt = [[0, 0] for i in range(n)]
for i in range(n):
for j in graph[i]:
v_cnt[j][v_num[i]] += 1
for i in range(n):
if v_cnt[i][0] * v_cnt[i][1] == 0:
q.append(i)
used[i] = True
while q:
pos = q.pop()
for next_pos in graph[pos]:
if used[next_pos]:
continue
v_cnt[next_pos][v_num[pos]] -= 1
if v_cnt[next_pos][v_num[pos]] == 0:
q.append(next_pos)
used[next_pos] = True
for i in range(n):
if not used[i]:
print("Yes")
exit()
print("No")
``` | output | 1 | 92,472 | 13 | 184,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No
Submitted Solution:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
GC027 C
"""
n,m = map(int,input().split())
s = list(input())
edges = [tuple(map(int,input().split())) for i in range(m)]
ali = [0 for i in range(n)]
bli = [0 for i in range(n)]
def addEdge(graph,u,v):
graph[u].append(v)
from collections import defaultdict
graphAB = defaultdict(list)
def incrementAB(node,adj):
if s[adj-1] == 'A':
ali[node-1]+=1
if s[adj-1] == 'B':
bli[node-1]+=1
def decrementAB(node,adj):
if s[adj-1] == 'A':
ali[node-1]-=1
if s[adj-1] == 'B':
bli[node-1]-=1
for i,j in edges:
addEdge(graphAB,i,j)
addEdge(graphAB,j,i)
def adjAB(node):
if ali[node-1]!=0 and bli[node-1]!=0:
return(True)
else:
return(False)
graphvers = set(graphAB.keys())
visitset = set()
for i in range(1,n+1):
if not i in graphvers:
s[i-1] = 'C'
else:
for j in graphAB[i]:
incrementAB(i,j)
if not adjAB(i):
visitset.add(i)
while bool(visitset):
#print(graphAB)
#print(graphABopp)
#print(abli)
i = visitset.pop()
for j in graphAB[i]:
if s[j-1] != 'C':
decrementAB(j,i)
if not adjAB(j):
visitset.add(j)
s[i-1] = 'C'
#print(graphAB)
#print(graphABopp)
sset= set(s)
sset.add('C')
sset.remove('C')
if bool(sset):
print('Yes')
else:
print('No')
``` | instruction | 0 | 92,473 | 13 | 184,946 |
Yes | output | 1 | 92,473 | 13 | 184,947 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No
Submitted Solution:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
GC027 C
"""
n,m = map(int,input().split())
s = bytearray(input(),'utf-8')
ali = [0 for i in range(n)]
bli = [0 for i in range(n)]
from collections import defaultdict
graphAB = defaultdict(list)
for i in range(m):
u,v=map(int,input().split())
graphAB[u].append(v)
graphAB[v].append(u)
def incrementAB(node,adj):
if s[adj-1] == 65:
ali[node-1]+=1
if s[adj-1] == 66:
bli[node-1]+=1
def decrementAB(node,adj):
if s[adj-1] == 65:
ali[node-1]-=1
if s[adj-1] == 66:
bli[node-1]-=1
graphvers = set(graphAB.keys())
visitset = set()
for i in range(1,n+1):
if not i in graphvers:
s[i-1] = 67
else:
for j in graphAB[i]:
incrementAB(i,j)
if not (ali[i-1] and bli[i-1]):
visitset.add(i)
while bool(visitset):
#print(graphAB)
#print(graphABopp)
#print(abli)
i = visitset.pop()
for j in filter(lambda x: s[x-1]!=67,graphAB[i]):
decrementAB(j,i)
if not (ali[j-1] and bli[j-1]):
visitset.add(j)
s[i-1] = 67
#print(graphAB)
#print(graphABopp)
sset= set(s)
sset.add(67)
sset.remove(67)
if bool(sset):
print('Yes')
else:
print('No')
``` | instruction | 0 | 92,474 | 13 | 184,948 |
Yes | output | 1 | 92,474 | 13 | 184,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No
Submitted Solution:
```
import queue
import sys
input = sys.stdin.readline
def toab(s, ab, node):
toa, tob = False, False
for k in ab:
if k not in node:
continue
if s[k - 1] == 'A':
toa = True
if tob:
return True
elif s[k - 1] == 'B':
tob = True
if toa:
return True
return False
ab = {}
node = {}
N, M = map(int, input().split())
s = input()
for i in range(M):
a, b = map(int, input().split())
if a not in ab:
ab[a] = {}
ab[a][b] = True
if b not in ab:
ab[b] = {}
ab[b][a] = True
node[a] = True
node[b] = True
for i in range(N + 1):
if i not in node:
continue
q = queue.Queue()
q.put(i)
while not q.empty():
j = q.get()
if j in node and not toab(s, ab[j], node):
node.pop(j)
for k in ab[j]:
if k in node:
q.put(k)
if not node:
print('No')
else:
print('Yes')
``` | instruction | 0 | 92,475 | 13 | 184,950 |
Yes | output | 1 | 92,475 | 13 | 184,951 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No
Submitted Solution:
```
# C
from collections import deque
N, M = map(int, input().split())
s = list(input())
s_ = []
for c in s:
s_.append(c)
# Graph
G = dict()
for i in range(1, N+1):
G[i] = dict()
for _ in range(M):
a, b = map(int, input().split())
G[a][b] = 1
G[b][a] = 1
# clean up
queue = deque()
go = True
As = [0]*N
Bs = [0]*N
for i in range(1, N+1):
if s[i-1] != "C":
a = 0
b = 0
for k in G[i].keys():
v = s_[k-1]
if v == "A":
a += 1
elif v == "B":
b += 1
As[i-1] = a
Bs[i-1] = b
if a*b == 0:
queue.append(i)
s[i-1] = "C"
while len(queue) > 0:
j = queue.popleft()
for i in G[j].keys():
if s[i-1] != "C":
if s_[j-1] == "A":
As[i-1] -= 1
else:
Bs[i-1] -= 1
if As[i-1] * Bs[i-1] == 0:
queue.append(i)
s[i-1] = "C"
if "A" in s and "B" in s:
print("Yes")
else:
print("No")
``` | instruction | 0 | 92,476 | 13 | 184,952 |
Yes | output | 1 | 92,476 | 13 | 184,953 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**7)
N,M = map(int,input().split())
S = input()
src = [tuple(map(lambda x:int(x)-1,input().split())) for i in range(M)]
aa = [set() for i in range(N)]
bb = [set() for i in range(N)]
ab = [set() for i in range(N)]
ba = [set() for i in range(N)]
for x,y in src:
if S[x] != S[y]:
if S[x] == 'A':
ab[x].add(y)
ba[y].add(x)
else:
ba[x].add(y)
ab[y].add(x)
elif S[x] == 'A':
aa[x].add(y)
aa[y].add(x)
else:
bb[x].add(y)
bb[y].add(x)
skip = [False] * N
def remove(i):
if skip[i]: return
if S[i] == 'A':
if aa[i]: return
for b in ab[i]:
remove(b)
if i in ba[b]:
ba[b].remove(i)
ab[i] = set()
else:
if bb[i]: return
for a in ba[i]:
remove(a)
if i in ab[a]:
ab[a].remove(i)
ba[i] = set()
skip[i] = True
for i in range(N):
remove(i)
mem = [[None]*N for i in range(4)]
def rec(v, depth):
if mem[depth][v] is not None:
return mem[depth][v]
ret = False
if depth == 0:
for to in ab[v]:
if rec(to, depth+1):
ret = True
break
elif depth == 1:
for to in bb[v]:
if rec(to, depth+1):
ret = True
break
elif depth == 2:
for to in ba[v]:
if rec(to, depth+1):
ret = True
break
else:
for to in aa[v]:
if ab[to]:
ret = True
mem[depth][v] = ret
return ret
for i in range(N):
if rec(i, 0):
print('Yes')
exit()
print('No')
``` | instruction | 0 | 92,477 | 13 | 184,954 |
No | output | 1 | 92,477 | 13 | 184,955 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No
Submitted Solution:
```
#####segfunc#####
def segfunc(x, y):
if x[0]>y[0]:
return y
elif x[0]<y[0]:
return x
elif x[1]>y[1]:
return y
else:
return x
#################
#####ide_ele#####
ide_ele = [float("inf"),-1]
#################
class SegTree:
"""
init(init_val, ide_ele): 配列init_valで初期化 O(N)
update(k, x): k番目の値をxに更新 O(logN)
query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
"""
def __init__(self, init_val, segfunc, ide_ele):
"""
init_val: 配列の初期値
segfunc: 区間にしたい操作
ide_ele: 単位元
n: 要素数
num: n以上の最小の2のべき乗
tree: セグメント木(1-index)
"""
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
# 配列の値を葉にセット
for i in range(n):
self.tree[self.num + i] = init_val[i]
# 構築していく
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
"""
k番目の値をxに更新
k: index(0-index)
x: update value
"""
k += self.num
self.tree[k][0] += x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
"""
[l, r)のsegfuncしたものを得る
l: index(0-index)
r: index(0-index)
"""
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
import sys
input=sys.stdin.readline
N,M=map(int,input().split())
s=input()
dic={"A":[[0,i] for i in range(N)],"B":[[0,i] for i in range(N)]}
edge=[[] for i in range(N)]
for i in range(M):
a,b=map(int,input().split())
a-=1;b-=1
edge[a].append(b)
edge[b].append(a)
dic[s[a]][b][0]+=1
dic[s[b]][a][0]+=1
dic={moji:SegTree(dic[moji],segfunc,ide_ele) for moji in dic}
ban=set([])
while True:
a,index=dic["A"].query(0,N)
b,index2=dic["B"].query(0,N)
if a==0:
ban.add(index)
dic["A"].update(index,float("inf"))
dic["B"].update(index,float("inf"))
for v in edge[index]:
dic[s[index]].update(v,-1)
elif b==0:
ban.add(index2)
dic["A"].update(index2,float("inf"))
dic["B"].update(index2,float("inf"))
for v in edge[index2]:
dic[s[index2]].update(v,-1)
else:
break
check=set([i for i in range(N)])
if ban==check:
print("No")
else:
print("Yes")
``` | instruction | 0 | 92,478 | 13 | 184,956 |
No | output | 1 | 92,478 | 13 | 184,957 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No
Submitted Solution:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
GC027 C
"""
n,m = map(int,input().split())
s = list(input())
edges = [tuple(map(int,input().split())) for i in range(m)]
abli = [[0,0] for i in range(n)]
def addEdge(graph,u,v):
graph[u].add(v)
def deleteNode(graph,node):
graph.pop(node,None)
from collections import defaultdict
graphAB = defaultdict(set)
graphABopp = defaultdict(set)
def incrementAB(node,adj):
if s[adj-1] == 'A':
abli[node-1][0]+=1
if s[adj-1] == 'B':
abli[node-1][1]+=1
def decrementAB(node,adj):
if s[adj-1] == 'A':
abli[node-1][0]-=1
if s[adj-1] == 'B':
abli[node-1][1]-=1
edgeset = set()
for i,j in edges:
ii = min(i,j)
jj = max(i,j)
edgeset.add((ii,jj))
for i,j in edgeset:
addEdge(graphAB,i,j)
addEdge(graphABopp,j,i)
incrementAB(i,j)
if j!=i:
incrementAB(j,i)
def adjAB(node):
if abli[node-1][0]!=0 and abli[node-1][1]!=0:
return(True)
else:
return(False)
#def adjAB(node):
# Aflag = 'A' in map(lambda x:s[x-1],graphAB[node])
# Aflag = Aflag or 'A' in map(lambda x:s[x-1],graphABopp[node])
# Bflag = 'B' in map(lambda x:s[x-1],graphAB[node])
# Bflag = Bflag or 'B' in map(lambda x:s[x-1],graphABopp[node])
# if Aflag and Bflag:
# return(True)
# else:
# return(False)
visitset = set([i for i in set(graphAB.keys())|set(graphABopp.keys()) if not adjAB(i)])
#print(visitset)
while bool(visitset):
#print(graphAB)
#print(graphABopp)
#print(abli)
i = visitset.pop()
for j in graphAB[i]:
if not adjAB(j):
graphABopp[j].remove(i)
decrementAB(j,i)
else:
graphABopp[j].remove(i)
decrementAB(j,i)
if not adjAB(j):
visitset.add(j)
#print(visitset,'add')
for j in graphABopp[i]:
if not adjAB(j):
graphAB[j].remove(i)
decrementAB(j,i)
else:
graphAB[j].remove(i)
decrementAB(j,i)
if not adjAB(j):
visitset.add(j)
#print(visitset,'add')
graphAB.pop(i,None)
graphABopp.pop(i,None)
#print(graphAB)
#print(graphABopp)
if graphAB == {} and graphABopp == {}:
print('No')
else:
print('Yes')
``` | instruction | 0 | 92,479 | 13 | 184,958 |
No | output | 1 | 92,479 | 13 | 184,959 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. In addition, each vertex has a label, `A` or `B`. The label of Vertex i is s_i. Edge i bidirectionally connects vertex a_i and b_i.
The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times. Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.
For example, in a graph where Vertex 1 has the label `A` and Vertex 2 has the label `B`, if Nusook travels along the path 1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2, the resulting string is `ABABB`.
Determine if Nusook can make all strings consisting of `A` and `B`.
Constraints
* 2 \leq N \leq 2 \times 10^{5}
* 1 \leq M \leq 2 \times 10^{5}
* |s| = N
* s_i is `A` or `B`.
* 1 \leq a_i, b_i \leq N
* The given graph may NOT be simple or connected.
Input
Input is given from Standard Input in the following format:
N M
s
a_1 b_1
:
a_{M} b_{M}
Output
If Nusook can make all strings consisting of `A` and `B`, print `Yes`; otherwise, print `No`.
Examples
Input
2 3
AB
1 1
1 2
2 2
Output
Yes
Input
4 3
ABAB
1 2
2 3
3 1
Output
No
Input
13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9
Output
Yes
Input
13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11
Output
No
Submitted Solution:
```
from collections import deque
N,M=map(int,input().split())
s=input()
H=[[] for i in range(N)]
G=[[] for i in range(2*N)]
for i in range(M):
a,b=map(int,input().split())
a-=1
b-=1
H[a].append(b)
H[b].append(a)
if s[a]=="A":
if s[b]=="A":
G[a].append(N+b)
G[b].append(N+a)
else:
G[a+N].append(b+N)
G[b].append(a)
else:
if s[b]=="A":
G[a].append(b)
G[N+b].append(N+a)
else:
G[N+a].append(b)
G[N+b].append(a)
K=[0 for i in range(2*N)]
for i in range(2*N):
for p in G[i]:
K[p]+=1
q=deque(i for i in range(2*N) if K[i]==0)
res=[]
while q:
v1=q.popleft()
res.append(v1)
for v2 in G[v1]:
K[v2]-=1
if K[v2]==0:
q.append(v2)
if len(res)==2*N:
print("Yes")
else:
print("No")
``` | instruction | 0 | 92,480 | 13 | 184,960 |
No | output | 1 | 92,480 | 13 | 184,961 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Initially, each edge is painted blue. Takahashi will convert this blue tree into a red tree, by performing the following operation N-1 times:
* Select a simple path that consists of only blue edges, and remove one of those edges.
* Then, span a new red edge between the two endpoints of the selected path.
His objective is to obtain a tree that has a red edge connecting vertices c_i and d_i, for each i.
Determine whether this is achievable.
Constraints
* 2 ≤ N ≤ 10^5
* 1 ≤ a_i,b_i,c_i,d_i ≤ N
* a_i ≠ b_i
* c_i ≠ d_i
* Both input graphs are trees.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 d_1
:
c_{N-1} d_{N-1}
Output
Print `YES` if the objective is achievable; print `NO` otherwise.
Examples
Input
3
1 2
2 3
1 3
3 2
Output
YES
Input
5
1 2
2 3
3 4
4 5
3 4
2 4
1 4
1 5
Output
YES
Input
6
1 2
3 5
4 6
1 6
5 1
5 3
1 4
2 6
4 3
5 6
Output
NO | instruction | 0 | 92,499 | 13 | 184,998 |
"Correct Solution:
```
import queue
n,q=int(input()),queue.Queue()
s=[set() for i in range(n+1)]
for i in range(2*n-2):
u,v=map(int,input().split())
if v in s[u]:
q.put((u,v))
else:
s[u].add(v)
s[v].add(u)
f=[i for i in range(n+1)]
def find(x):
if f[x]==x:
return x
else:
f[x]=find(f[x])
return f[x]
while not q.empty():
u,v=map(find,q.get())
if u==v:
continue
if len(s[u])<len(s[v]):
u,v=v,u
s[u].remove(v)
s[v].remove(u)
for x in s[v]:
s[x].remove(v)
if u in s[x]:
q.put((u,x))
else:
s[u].add(x)
s[x].add(u)
s[v],f[v]=[],u
root=find(1)
for i in range(2,n+1):
if find(i)!=root:
print("NO")
break
else:
print("YES")
``` | output | 1 | 92,499 | 13 | 184,999 |
Provide a correct Python 3 solution for this coding contest problem.
Problem Statement
You are given a connected undirected graph which has even numbers of nodes. A connected graph is a graph in which all nodes are connected directly or indirectly by edges.
Your task is to find a spanning tree whose median value of edges' costs is minimum. A spanning tree of a graph means that a tree which contains all nodes of the graph.
Input
The input consists of multiple datasets.
The format of each dataset is as follows.
n m
s_1 t_1 c_1
...
s_m t_m c_m
The first line contains an even number n (2 \leq n \leq 1,000) and an integer m (n-1 \leq m \leq 10,000). n is the nubmer of nodes and m is the number of edges in the graph.
Then m lines follow, each of which contains s_i (1 \leq s_i \leq n), t_i (1 \leq s_i \leq n, t_i \neq s_i) and c_i (1 \leq c_i \leq 1,000). This means there is an edge between the nodes s_i and t_i and its cost is c_i. There is no more than one edge which connects s_i and t_i.
The input terminates when n=0 and m=0. Your program must not output anything for this case.
Output
Print the median value in a line for each dataset.
Example
Input
2 1
1 2 5
4 6
1 2 1
1 3 2
1 4 3
2 3 4
2 4 5
3 4 6
8 17
1 4 767
3 1 609
8 3 426
6 5 972
8 1 607
6 4 51
5 1 683
3 6 451
3 4 630
8 7 912
3 7 43
4 7 421
3 5 582
8 4 538
5 7 832
1 6 345
8 2 608
0 0
Output
5
2
421 | instruction | 0 | 92,581 | 13 | 185,162 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
class UnionFind:
def __init__(self, size):
self.table = [-1 for _ in range(size)]
def find(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self.find(self.table[x])
return self.table[x]
def union(self, x, y):
s1 = self.find(x)
s2 = self.find(y)
if s1 != s2:
if self.table[s1] <= self.table[s2]:
self.table[s1] += self.table[s2]
self.table[s2] = s1
else:
self.table[s2] += self.table[s1]
self.table[s1] = s2
return True
return False
def subsetall(self):
a = []
for i in range(len(self.table)):
if self.table[i] < 0:
a.append((i, -self.table[i]))
return a
def main():
rr = []
def f(n,m):
a = sorted([LI()[::-1] for _ in range(m)])
uf = UnionFind(n+1)
b = 0
for c,t,s in a:
if uf.union(s,t):
b += 1
if b > (n-1) // 2:
return c
return -1
while True:
n,m = LI()
if n == 0:
break
rr.append(f(n,m))
return '\n'.join(map(str,rr))
print(main())
``` | output | 1 | 92,581 | 13 | 185,163 |
Provide a correct Python 3 solution for this coding contest problem.
Problem Statement
You are given a connected undirected graph which has even numbers of nodes. A connected graph is a graph in which all nodes are connected directly or indirectly by edges.
Your task is to find a spanning tree whose median value of edges' costs is minimum. A spanning tree of a graph means that a tree which contains all nodes of the graph.
Input
The input consists of multiple datasets.
The format of each dataset is as follows.
n m
s_1 t_1 c_1
...
s_m t_m c_m
The first line contains an even number n (2 \leq n \leq 1,000) and an integer m (n-1 \leq m \leq 10,000). n is the nubmer of nodes and m is the number of edges in the graph.
Then m lines follow, each of which contains s_i (1 \leq s_i \leq n), t_i (1 \leq s_i \leq n, t_i \neq s_i) and c_i (1 \leq c_i \leq 1,000). This means there is an edge between the nodes s_i and t_i and its cost is c_i. There is no more than one edge which connects s_i and t_i.
The input terminates when n=0 and m=0. Your program must not output anything for this case.
Output
Print the median value in a line for each dataset.
Example
Input
2 1
1 2 5
4 6
1 2 1
1 3 2
1 4 3
2 3 4
2 4 5
3 4 6
8 17
1 4 767
3 1 609
8 3 426
6 5 972
8 1 607
6 4 51
5 1 683
3 6 451
3 4 630
8 7 912
3 7 43
4 7 421
3 5 582
8 4 538
5 7 832
1 6 345
8 2 608
0 0
Output
5
2
421 | instruction | 0 | 92,582 | 13 | 185,164 |
"Correct Solution:
```
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = I()
return l
def LIR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = LI()
return l
def SR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = S()
return l
def LSR(n):
l = [None for i in range(n)]
for i in range(n):l[i] = LS()
return l
sys.setrecursionlimit(1000000)
mod = 1000000007
#A
def A():
while 1:
n,m = LI()
if n == 0 and m == 0:
break
v = [[] for i in range(n)]
for i in range(m):
a,b = LI()
a -= 1
b -= 1
v[a].append(b)
v[b].append(a)
bfs_map = [1 for i in range(n)]
bfs_map[0] = 0
f = [0 for i in range(n)]
q = deque()
q.append(0)
fl = 1
while q:
if not fl:break
x = q.popleft()
for y in v[x]:
if bfs_map[y]:
bfs_map[y] = 0
f[y] = (1-f[x])
q.append(y)
else:
if f[y] == f[x]:
print(0)
fl = 0
break
if fl:
ans = []
k = sum(f)
if k%2 == 0:
ans.append(k//2)
k = len(f)-sum(f)
if k%2 == 0:
ans.append(k//2)
ans = list(set(ans))
ans.sort()
print(len(ans))
for i in ans:
print(i)
return
#B
def B():
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
def factorize(n):
if n < 4:
return {n:1}
i = 2
d = defaultdict(int)
m = n
while i**2 <= n:
if m%i == 0:
while m%i == 0:
m//=i
d[i] += 1
i += 1
d[m] += 1
return d
p,q = LI()
g = gcd(p,q)
ans = q//g
if ans == 1:
print(1)
else:
d = factorize(ans)
ans = 1
for i in d.keys():
ans *= i
print(ans)
return
#C
def C():
return
#D
def D():
def root(x):
if par[x] == x:
return par[x]
par[x] = root(par[x])
return par[x]
def same(x,y):
return root(x) == root(y)
def unite(x,y):
x = root(x)
y = root(y)
if rank[x] < rank[y]:
par[x] = y
else:
par[y] = x
if rank[x] == rank[y]:
rank[x] += 1
while 1:
n,m = LI()
if n == 0 and m == 0:
break
l = LIR(m)
l.sort(key = lambda x:x[2])
for i in range(m):
l[i][0] -= 1
l[i][1] -= 1
ans = []
par = [i for i in range(n)]
rank = [0 for i in range(n)]
for x,y,c in l:
if not same(x,y):
unite(x,y)
ans.append(c)
print(ans[(n-1)//2])
return
#E
def E():
return
#F
def F():
return
#G
def G():
return
#H
def H():
return
#I
def I_():
return
#J
def J():
return
#Solve
if __name__ == "__main__":
D()
``` | output | 1 | 92,582 | 13 | 185,165 |
Provide a correct Python 3 solution for this coding contest problem.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4 | instruction | 0 | 92,597 | 13 | 185,194 |
"Correct Solution:
```
from collections import defaultdict
import sys
sys.setrecursionlimit(100000)
def seq():
a = 1
while True:
yield a
a += 1
def dfs(here, went, connect, discovery, low, answer, seq):
went |= {here}
discovery[here] = low[here] = next(seq)
child = 0
for con in connect[here]:
if con not in went:
parent[con] = here
child += 1
dfs(con, went, connect, discovery, low, answer, seq)
low[here] = min(low[here], low[con])
if discovery[here] < low[con]:
answer[min(here,con)].append(max(here,con))
elif parent[here] != con:
low[here] = min(low[here], discovery[con])
vertices, edges = (int(n) for n in input().split(" "))
connect = defaultdict(list)
for _ in range(edges):
v1, v2 = (int(n) for n in input().split(" "))
connect[v1].append(v2)
connect[v2].append(v1)
answer = defaultdict(list)
new_seq = seq()
went = set()
discovery = [0 for n in range(vertices)]
low = [float("inf") for n in range(vertices)]
parent = [None for n in range(vertices)]
dfs(0, went, connect, discovery, low, answer, new_seq)
for k in sorted(answer.keys()):
for n in sorted(answer[k]):
print(k,n)
``` | output | 1 | 92,597 | 13 | 185,195 |
Provide a correct Python 3 solution for this coding contest problem.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4 | instruction | 0 | 92,598 | 13 | 185,196 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15
class LowLink():
def __init__(self,G):
self.N = len(G)
self.G = G
self.low = [-1] * self.N
self.ord = [-1] * self.N
def _dfs(self,v,time,p = -1):
self.ord[v] = self.low[v] = time
time += 1
isArticulation = False
cnt = 0
for e in self.G[v]:
if self.low[e] < 0:
cnt += 1
self._dfs(e,time,v)
self.low[v] = min(self.low[v],self.low[e])
if p != -1 and self.ord[v] <= self.low[e]:
isArticulation = True
if self.ord[v] < self.low[e]:
if v < e:
self.bridge.append((v,e))
else:
self.bridge.append((e,v))
elif e != p:
self.low[v] = min(self.low[v],self.ord[e])
if p == -1 and cnt >= 2:
isArticulation = True
if isArticulation:
self.articulation.append(v)
def build(self):
self.articulation = []
self.bridge = []
self._dfs(0,0)
def main():
V,E = map(int,input().split())
G = [[] for _ in range(V)]
for _ in range(E):
a,b = map(int,input().split())
G[a].append(b)
G[b].append(a)
lowlink = LowLink(G)
lowlink.build()
ans = lowlink.bridge
ans.sort()
if ans:
for t in ans:
print(*t)
if __name__ == '__main__':
main()
``` | output | 1 | 92,598 | 13 | 185,197 |
Provide a correct Python 3 solution for this coding contest problem.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4 | instruction | 0 | 92,599 | 13 | 185,198 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10 ** 9)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
INF=float('inf')
N,M=MAP()
nodes=[[] for i in range(N)]
for i in range(M):
u,v=MAP()
nodes[u].append(v)
nodes[v].append(u)
timer=1
prenum=[0]*(N+1)
lowest=[0]*(N+1)
ans=[]
def rec(cur, prev):
global timer
# curを訪問した直後の処理
prenum[cur]=lowest[cur]=timer
timer+=1
for nxt in nodes[cur]:
# 未訪問なら再帰探索する
if not prenum[nxt]:
rec(nxt, cur)
# nxtの探索が終了した直後の処理
lowest[cur]=min(lowest[cur], lowest[nxt])
# より近い経路を含まないなら橋とする
if lowest[nxt]==prenum[nxt]:
# 番号の小さい方から入れる
ans.append((min(cur, nxt), max(cur, nxt)))
# 訪問済の場合、親への経路は無視して、他は近い経路となるか確認を取る
elif nxt!=prev:
lowest[cur]=min(lowest[cur], lowest[nxt])
rec(0, -1)
ans.sort()
for edge in ans:
print(*edge)
``` | output | 1 | 92,599 | 13 | 185,199 |
Provide a correct Python 3 solution for this coding contest problem.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4 | instruction | 0 | 92,600 | 13 | 185,200 |
"Correct Solution:
```
# Undirected Graph
class Edge:
__slots__ = ('v', 'w')
def __init__(self, v, w):
self.v = v
self.w = w
def either(self):
return self.v
def other(self, v):
if v == self.v:
return self.w
else:
return self.v
class Graph:
def __init__(self, v):
self.v = v
self._edges = [[] for _ in range(v)]
def add(self, e):
self._edges[e.v].append(e)
self._edges[e.w].append(e)
def adj(self, v):
return self._edges[v]
def edges(self):
for es in self._edges:
for e in es:
yield e
def bridges(graph):
def visit(v, e):
nonlocal n
w = e.other(v)
if not visited[w]:
parent[w] = v
n += 1
visited[w] = n
low[w] = n
return True
elif w != parent[v]:
low[v] = min(low[v], visited[w])
return False
def leave(p, e):
c = e.other(p)
if p == parent[c] and low[c] > visited[p]:
es.append(e)
low[p] = min(low[p], low[c])
return False
visited = [0] * graph.v
low = [0] * graph.v
parent = [-1] * graph.v
es = []
s = 0
n = 1
visited[s] = n
low[s] = n
stack = [(s, e, visit) for e in graph.adj(s)]
while stack:
v, e, func = stack.pop()
# print(v, e.v, e.w, func.__name__, visited, low)
if func(v, e):
stack.append((v, e, leave))
w = e.other(v)
for ne in graph.adj(w):
stack.append((w, ne, visit))
return es
def run():
v, e = [int(i) for i in input().split()]
g = Graph(v)
for _ in range(e):
s, t = [int(i) for i in input().split()]
g.add(Edge(s, t))
edges = [(e.v, e.w) if e.v < e.w else (e.w, e.v)
for e in bridges(g)]
for v, w in sorted(edges):
print(v, w)
if __name__ == '__main__':
run()
``` | output | 1 | 92,600 | 13 | 185,201 |
Provide a correct Python 3 solution for this coding contest problem.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4 | instruction | 0 | 92,601 | 13 | 185,202 |
"Correct Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
5 4
0 1
1 2
2 3
3 4
output:
0 1
1 2
2 3
3 4
"""
import sys
sys.setrecursionlimit(int(1e5))
def generate_adj_table(_v_info):
for v_detail in _v_info:
v_from, v_to = map(int, v_detail)
init_adj_table[v_from].append(v_to)
# undirected graph
init_adj_table[v_to].append(v_from)
return init_adj_table
def graph_dfs(u, visited, parent, low, disc):
global Time
# Count of children in current node
children = 0
# Mark the current node as visited and print it
visited[u] = True
# Initialize discovery time and low value
disc[u] = Time
low[u] = Time
Time += 1
# Recur for all the vertices adjacent to this vertex
for v in adj_table[u]:
# If v is not visited yet, then make it a child of u
# in DFS tree and recur for it
if not visited[v]:
parent[v] = u
children += 1
graph_dfs(v, visited, parent, low, disc)
# Check if the subtree rooted with v has a connection to
# one of the ancestors of u
low[u] = min(low[u], low[v])
''' If the lowest vertex reachable from subtree
under v is below u in DFS tree, then u-v is
a bridge'''
if low[v] > disc[u]:
ans.append(sorted([u, v]))
elif v != parent[u]: # Update low value of u for parent function calls.
low[u] = min(low[u], disc[v])
return None
def bridge():
visited = [False] * vertices
disc = [float("Inf")] * vertices
low = [float("Inf")] * vertices
parent = [-1] * vertices
for v in range(vertices):
if not visited[v]:
graph_dfs(v, visited, parent, low, disc)
return ans
if __name__ == '__main__':
_input = sys.stdin.readlines()
vertices, edges = map(int, _input[0].split())
v_info = map(lambda x: x.split(), _input[1:])
Time = 0
ans = []
init_adj_table = tuple([] for _ in range(vertices))
adj_table = generate_adj_table(v_info)
res = bridge()
res.sort()
for ele in res:
print(*ele)
``` | output | 1 | 92,601 | 13 | 185,203 |
Provide a correct Python 3 solution for this coding contest problem.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4 | instruction | 0 | 92,602 | 13 | 185,204 |
"Correct Solution:
```
#!/usr/bin/env python3
# N,M = map(int,sys.stdin.readline().split())
# a = tuple(map(int,sys.stdin.readline().split())) # single line with multi param
# a = tuple(int(sys.stdin.readline()) for _ in range(N)) # multi line with single param
# a = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(N)) # multi line with multi param
# s = sys.stdin.readline().rstrip()
# N = int(sys.stdin.readline())
# INF = float("inf")
import sys,collections
sys.setrecursionlimit(100000)
INF = float("inf")
V,E = map(int,sys.stdin.readline().split())
st = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(E)) # multi line with multi param
G = [[] for _ in range(V)]
for s,t in st:
G[s].append(t)
G[t].append(s) #not directed
visited = set()
prenum = [0]*V
parent = [0]*V
lowest = [0]*V
timer = 0
def dfs(current,prev):
global timer
parent[current]=prev
prenum[current]=lowest[current]=timer
timer += 1
visited.add(current)
for nex in G[current]:
if not nex in visited:
dfs(nex,current)
lowest[current]=min(lowest[current],lowest[nex])
elif nex != prev:
lowest[current]=min(lowest[current],prenum[nex])
dfs(0,-1)
ret = []
for i in range(1,V):
p = parent[i]
if prenum[p] < lowest[i]:
if p < i:
ret.append([p,i])
else:
ret.append([i,p])
ret = sorted(list(ret))
for s,t in ret:
print(s,t)
``` | output | 1 | 92,602 | 13 | 185,205 |
Provide a correct Python 3 solution for this coding contest problem.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4 | instruction | 0 | 92,603 | 13 | 185,206 |
"Correct Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.readline
# return: articulation points, bridges
# The graph must be connected.
def lowlink(adj, root=1):
N = len(adj) - 1
order = [N + 1] * (N + 1)
low = [N + 1] * (N + 1)
AP = []
bridge = []
st = [root]
cnt = 1
par = [0] * (N + 1)
seq = []
while st:
v = st.pop()
if order[v] != N+1:
continue
order[v] = cnt
seq.append(v)
low[v] = cnt
cnt += 1
for u in adj[v]:
if order[u] < cnt:
if par[v] != u:
low[v] = min(low[v], order[u])
continue
else:
par[u] = v
st.append(u)
child = [[] for _ in range(N + 1)]
for v in range(1, N + 1):
child[par[v]].append(v)
seq.reverse()
for v in seq:
for u in child[v]:
low[v] = min(low[v], low[u])
# bridge
for p in range(1, N+1):
for c in child[p]:
if order[p] < low[c]:
bridge.append((p, c))
# articulation point
for v in range(1, N + 1):
if v == root:
if len(child[v]) > 1:
AP.append(v)
else:
for c in child[v]:
if order[v] <= low[c]:
AP.append(v)
break
return AP, bridge
N, M = map(int, input().split())
adj = [[] for _ in range(N+1)]
for _ in range(M):
a, b = map(int, input().split())
a += 1
b += 1
adj[a].append(b)
adj[b].append(a)
AP, bridge = lowlink(adj)
ans = []
for u, v in bridge:
u -= 1
v -= 1
if u > v:
u, v = v, u
ans.append((u, v))
ans.sort(key=lambda x: x[1])
ans.sort(key=lambda x: x[0])
for u, v in ans:
print(u, v)
if __name__ == '__main__':
main()
``` | output | 1 | 92,603 | 13 | 185,207 |
Provide a correct Python 3 solution for this coding contest problem.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4 | instruction | 0 | 92,604 | 13 | 185,208 |
"Correct Solution:
```
from math import inf
import sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**6)
def dfs(v,par):
global cur
vis[v]=1 ; disc[v]=cur ;low[v]=cur
cur+=1
for i in g[v]:
if vis[i]==0:
dfs(i,v)
low[v]=min(low[i],low[v])
if low[i]>disc[v]:
apts.add((min(v,i),max(v,i)))
elif i!=par: low[v]=min(disc[i],low[v])
def articulation_pts():
global apts,disc,low,vis
disc=[0]*n ; low=[inf]*n ; vis=[0]*n ; apts=set()
for i in range(n):
if vis[i]==0:
dfs(i,-1)
n,e=map(int,input().split())
cur=0
g=[[] for i in range(n)]
for i in range(e):
x,y=map(int,input().split())
g[x].append(y)
g[y].append(x)
articulation_pts()
apts=sorted(apts)
for i in apts:
print(*i)
``` | output | 1 | 92,604 | 13 | 185,209 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4
Submitted Solution:
```
import sys
sys.setrecursionlimit(10 ** 8)
def lowLink(N: int, Adj: list):
articulation = []
bridge = []
order = [None] * N
lowest = [1 << 100] * N
def _dfs(cur, pre, k):
order[cur] = lowest[cur] = k
is_articulation = False
cnt = 0
for nxt in Adj[cur]:
if order[nxt] is None:
cnt += 1
_dfs(nxt, cur, k + 1)
if lowest[cur] > lowest[nxt]:
lowest[cur] = lowest[nxt]
is_articulation |= pre >= 0 and lowest[nxt] >= order[cur]
if order[cur] < lowest[nxt]:
if cur < nxt:
bridge.append((cur, nxt))
else:
bridge.append((nxt, cur))
elif nxt != pre and lowest[cur] > order[nxt]:
lowest[cur] = order[nxt]
is_articulation |= pre < 0 and cnt > 1
if is_articulation:
articulation.append(cur)
_dfs(0, -1, 0)
return articulation, bridge
def main():
n, m, *L = map(int, open(0).read().split())
adj = [[] for _ in range(n)]
for s, t in zip(*[iter(L)] * 2):
adj[s] += t,
adj[t] += s,
_, bridge = lowLink(n, adj)
for x, y in sorted(bridge):
print(x, y)
if __name__ == '__main__':
main()
``` | instruction | 0 | 92,605 | 13 | 185,210 |
Yes | output | 1 | 92,605 | 13 | 185,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4
Submitted Solution:
```
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**7)
class LowLinks:
def __init__(self, edges, edges_num:int):
"""edges[u]: all vertexes connected with vertex 'u'
edges_num: number of edges of graph
the root of DFS-tree is vertex 0
"""
self.edges = edges
self.V = len(edges)
self.order = [-1]*V
self.low = [float('inf')]*V
self.bridges = []
# if degreee(root) > 1 and graph is tree: root is articulation
self.articulations = []
if len(edges[0]) > 1 and edges_num == self.V-1:
self.articulations.append(0)
self.k = 0
def build(self):
self.dfs(0, 0)
def get_bridges(self)->tuple:
return self.bridges
def get_articulations(self)->tuple:
return self.articulations
def dfs(self, v:int, prev:int):
self.order[v] = self.k
self.low[v] = self.k
self.k += 1
is_articulation = False
for to in self.edges[v]:
if self.order[to] < 0: # not visited
self.dfs(to, v)
self.low[v] = min(self.low[v], self.low[to])
if self.order[v] < self.low[to]:
self.bridges.append((v, to) if v < to else (to, v))
is_articulation |= self.order[v] <= self.low[to]
elif to != prev: # back edge
self.low[v] = min(self.low[v], self.order[to])
if v>0 and is_articulation:
self.articulations.append(v)
if __name__ == "__main__":
V,E = map(int, readline().split())
edges = [[] for _ in range(V)]
for _ in range(E):
s,t = map(int, readline().split())
edges[s].append(t)
edges[t].append(s)
lowlinks = LowLinks(edges, E)
lowlinks.build()
bridges = lowlinks.get_bridges()
bridges.sort()
if bridges:
for s,t in bridges:
print(s, t)
``` | instruction | 0 | 92,606 | 13 | 185,212 |
Yes | output | 1 | 92,606 | 13 | 185,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4
Submitted Solution:
```
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10 ** 9)
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
INF=float('inf')
N,M=MAP()
nodes=[[] for i in range(N)]
for i in range(M):
u,v=MAP()
nodes[u].append(v)
nodes[v].append(u)
visited=[False]*N
timer=1
prenum=[0]*(N+1)
lowest=[0]*(N+1)
ans=[]
def rec(cur, prev):
global timer
# curを訪問した直後の処理
prenum[cur]=lowest[cur]=timer
timer+=1
visited[cur]=True
for nxt in nodes[cur]:
# 未訪問なら再帰探索する
if not visited[nxt]:
rec(nxt, cur)
# nxtの探索が終了した直後の処理
lowest[cur]=min(lowest[cur], lowest[nxt])
# より近い経路を含まないなら橋とする
if lowest[nxt]==prenum[nxt]:
# 番号の小さい方から入れる
ans.append((min(cur, nxt), max(cur, nxt)))
# 訪問済の場合、親への経路は無視して、他は近い経路となるか確認を取る
elif nxt!=prev:
lowest[cur]=min(lowest[cur], lowest[nxt])
rec(0, -1)
ans.sort()
for edge in ans:
print(*edge)
``` | instruction | 0 | 92,607 | 13 | 185,214 |
Yes | output | 1 | 92,607 | 13 | 185,215 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4
Submitted Solution:
```
# 橋検出
from collections import defaultdict
import sys
sys.setrecursionlimit(10**7)
def input(): return sys.stdin.readline().rstrip()
# 二つの配列ord,miniを持つ。
V, E = map(int, input().split())
edge = []
graph = [[] for i in range(V)]
for i in range(E):
x, y = map(int, input().split())
graph[x].append(y)
graph[y].append(x)
edge.append((min(x, y), max(x, y)))
order = [i for i in range(V)]
mini = [V+1 for i in range(V)]
visited = [False for i in range(V)]
used = defaultdict(bool)
for node in range(V):
for point in graph[node]:
used[(node, point)] = False
cnt = 0
def dfs(node):
global cnt
visited[node] = True
cnt += 1
order[node] = cnt
mini[node] = cnt
for point in graph[node]:
if visited[point] == False:
used[(node, point)] = True
dfs(point)
mini[node] = min(mini[node], mini[point])
elif not used[(point, node)]:
mini[node] = min(mini[node], order[point])
return
dfs(0)
answer = []
for x, y in edge:
if order[x] < order[y]:
if order[x] < mini[y]:
answer.append((x, y))
elif order[x] > order[y]:
if order[y] < mini[x]:
answer.append((x, y))
answer.sort()
for x, y in answer:
print(x, y)
``` | instruction | 0 | 92,608 | 13 | 185,216 |
Yes | output | 1 | 92,608 | 13 | 185,217 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4
Submitted Solution:
```
import sys
f_i = sys.stdin
V, E = map(int, f_i.readline().split())
adj = [[] for i in range(V)]
for l_i in f_i:
s, t = map(int, l_i.split())
adj[s].append(t)
adj[t].append(s)
# dfs traverse
prenum = [1] + [None] * (V - 1)
parent = [0] * V
lowest = [1] + [V] * (V - 1)
import collections
path = collections.deque()
path.append(0)
cnt = 1
while path:
u = path[-1]
adj_v = adj[u]
for v in adj_v:
if not prenum[v]:
parent[v] = u
path.append(v)
cnt += 1
prenum[v] = cnt
lowest[v] = cnt
adj[u].remove(v)
adj[v].remove(u)
break
if u == path[-1]:
lowest[u] = min(lowest[u], prenum[u])
for v in adj_v:
l = min(lowest[u], lowest[v])
lowest[u] = l
lowest[v] = l
p = parent[u]
lowest[p] = min(lowest[u], lowest[p])
path.pop()
# output
bridge = []
for u in range(1, V):
p = parent[u]
if lowest[p] != lowest[u]:
b = [p, u]
b.sort()
bridge.append(b)
bridge.sort()
for b in bridge:
print(*b)
``` | instruction | 0 | 92,609 | 13 | 185,218 |
No | output | 1 | 92,609 | 13 | 185,219 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4
Submitted Solution:
```
from sys import stdin
readline = stdin.readline
from sys import stdin
readline = stdin.readline
def main():
v, e = map(int, readline().split())
from collections import defaultdict
g = defaultdict(list)
for _ in range(e):
s, t = map(int, readline().split())
g[s].append(t)
g[t].append(s)
visited = set()
lowest = [None] * v
parent = [None] * v
prenum = [None] * v
child = defaultdict(list)
root = 0
# dfs??§tree?????????
stack = [(root, None)]
while stack:
u, prev = stack.pop()
if u not in visited:
parent[u] = prev
if prev is not None:
child[prev].append(u)
visited |= {u}
prenum[u] = lowest[u] = len(visited)
stack.extend([(v, u) for v in g[u] if v not in visited])
# lowest????¨????
from collections import Counter
leaf = [i for i in range(v) if not child[i]]
unfinished = Counter()
for li in leaf:
while li is not None:
candidate = [prenum[li]] + [prenum[i] for i in g[li] if i != parent[li]] + [lowest[i] for i in child[li]]
lowest[li] = min(candidate)
li = parent[li]
if li is not None and 1 < len(child[li]):
unfinished[li] += 1
if unfinished[li] < len(child[li]):
break
# ????????????
bridge = []
for i in range(v):
if child[i]:
for j in child[i]:
if prenum[i] < lowest[j]:
if i > j:
i, j = j, i
bridge.append((i, j))
bridge.sort()
for bi in bridge:
print(*bi)
main()
``` | instruction | 0 | 92,610 | 13 | 185,220 |
No | output | 1 | 92,610 | 13 | 185,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4
Submitted Solution:
```
# Acceptance of input
import sys
f_i = sys.stdin
V, E = map(int, f_i.readline().split())
adj = [[] for i in range(V)]
for l_i in f_i:
s, t = map(int, l_i.split())
adj[s].append(t)
adj[t].append(s)
# dfs traverse
prenum = [1] + [None] * (V - 1)
parent = [0] * V
lowest = [1] + [V] * (V - 1)
import collections
path = collections.deque()
path.append(0)
cnt = 1
while path:
u = path[-1]
adj_v = adj[u]
for v in adj_v:
if not prenum[v]:
parent[v] = u
path.append(v)
cnt += 1
prenum[v] = cnt
adj[u].remove(v)
adj[v].remove(u)
break
if u == path[-1]:
lowest[u] = min(lowest[u], prenum[u])
for v in adj_v:
l = min(lowest[u], lowest[v])
lowest[u] = l
lowest[v] = l
p = parent[u]
lowest[p] = min(lowest[u], lowest[p])
path.pop()
# output
bridge = []
for u in range(1, V):
p = parent[u]
if lowest[p] != lowest[u]:
b = [p, u]
b.sort()
bridge.append(b)
bridge.sort()
for b in bridge:
print(*b)
``` | instruction | 0 | 92,611 | 13 | 185,222 |
No | output | 1 | 92,611 | 13 | 185,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Find bridges of an undirected graph G(V, E).
A bridge (also known as a cut-edge) is an edge whose deletion increase the number of connected components.
Constraints
* 1 ≤ |V| ≤ 100,000
* 0 ≤ |E| ≤ 100,000
* The graph is connected
* There are no parallel edges
* There are no self-loops
Input
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
, where |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (undirected).
Output
A list of bridges of the graph ordered by name. For each bridge, names of its end-ponints, source and target (source < target), should be printed separated by a space. The sources should be printed ascending order, then the target should also be printed ascending order for the same source.
Examples
Input
4 4
0 1
0 2
1 2
2 3
Output
2 3
Input
5 4
0 1
1 2
2 3
3 4
Output
0 1
1 2
2 3
3 4
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
5 4
0 1
1 2
2 3
3 4
output:
0 1
1 2
2 3
3 4
"""
import sys
sys.setrecursionlimit(int(1e10))
def generate_adj_table(_v_info):
for v_detail in _v_info:
v_from, v_to = map(int, v_detail)
init_adj_table[v_from].append(v_to)
# undirected graph
init_adj_table[v_to].append(v_from)
return init_adj_table
def graph_dfs(u, visited, parent, low, disc):
global Time
# Count of children in current node
children = 0
# Mark the current node as visited and print it
visited[u] = True
# Initialize discovery time and low value
disc[u] = Time
low[u] = Time
Time += 1
# Recur for all the vertices adjacent to this vertex
for v in adj_table[u]:
# If v is not visited yet, then make it a child of u
# in DFS tree and recur for it
if not visited[v]:
parent[v] = u
children += 1
graph_dfs(v, visited, parent, low, disc)
# Check if the subtree rooted with v has a connection to
# one of the ancestors of u
low[u] = min(low[u], low[v])
''' If the lowest vertex reachable from subtree
under v is below u in DFS tree, then u-v is
a bridge'''
if low[v] > disc[u]:
ans.append(sorted([u, v]))
elif v != parent[u]: # Update low value of u for parent function calls.
low[u] = min(low[u], disc[v])
return None
def bridge():
visited = [False] * vertices
disc = [float("Inf")] * vertices
low = [float("Inf")] * vertices
parent = [-1] * vertices
for v in range(vertices):
if not visited[v]:
graph_dfs(v, visited, parent, low, disc)
return ans
if __name__ == '__main__':
_input = sys.stdin.readlines()
vertices, edges = map(int, _input[0].split())
v_info = map(lambda x: x.split(), _input[1:])
Time = 0
ans = []
init_adj_table = tuple([] for _ in range(vertices))
adj_table = generate_adj_table(v_info)
res = bridge()
res.sort()
for ele in res:
print(*ele)
``` | instruction | 0 | 92,612 | 13 | 185,224 |
No | output | 1 | 92,612 | 13 | 185,225 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that the memory limit is unusual.
You are given an integer n and two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n.
Let's call a set of integers S such that S ⊆ \{1, 2, 3, ..., n\} strange, if, for every element i of S, the following condition is met: for every j ∈ [1, i - 1], if a_j divides a_i, then j is also included in S. An empty set is always strange.
The cost of the set S is ∑_{i ∈ S} b_i. You have to calculate the maximum possible cost of a strange set.
Input
The first line contains one integer n (1 ≤ n ≤ 3000).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100).
The third line contains n integers b_1, b_2, ..., b_n (-10^5 ≤ b_i ≤ 10^5).
Output
Print one integer — the maximum cost of a strange set.
Examples
Input
9
4 7 3 4 5 6 7 8 13
-2 3 -19 5 -6 7 -8 9 1
Output
16
Input
2
42 42
-37 13
Output
0
Input
2
42 42
13 -37
Output
13
Note
The strange set with the maximum cost in the first example is \{1, 2, 4, 8, 9\}.
The strange set with the maximum cost in the second example is empty. | instruction | 0 | 92,858 | 13 | 185,716 |
Tags: flows, math
Correct Solution:
```
from typing import NamedTuple, Optional, List, cast
class MFGraph:
class Edge(NamedTuple):
src: int
dst: int
cap: int
flow: int
class _Edge:
def __init__(self, dst: int, cap: int) -> None:
self.dst = dst
self.cap = cap
self.rev: Optional[MFGraph._Edge] = None
def __init__(self, n: int) -> None:
self._n = n
self._g: List[List[MFGraph._Edge]] = [[] for _ in range(n)]
self._edges: List[MFGraph._Edge] = []
def add_edge(self, src: int, dst: int, cap: int) -> int:
assert 0 <= src < self._n
assert 0 <= dst < self._n
assert 0 <= cap
m = len(self._edges)
e = MFGraph._Edge(dst, cap)
re = MFGraph._Edge(src, 0)
e.rev = re
re.rev = e
self._g[src].append(e)
self._g[dst].append(re)
self._edges.append(e)
return m
def get_edge(self, i: int) -> Edge:
assert 0 <= i < len(self._edges)
e = self._edges[i]
re = cast(MFGraph._Edge, e.rev)
return MFGraph.Edge(
re.dst,
e.dst,
e.cap + re.cap,
re.cap
)
def edges(self) -> List[Edge]:
return [self.get_edge(i) for i in range(len(self._edges))]
def change_edge(self, i: int, new_cap: int, new_flow: int) -> None:
assert 0 <= i < len(self._edges)
assert 0 <= new_flow <= new_cap
e = self._edges[i]
e.cap = new_cap - new_flow
assert e.rev is not None
e.rev.cap = new_flow
def flow(self, s: int, t: int, flow_limit: Optional[int] = None) -> int:
assert 0 <= s < self._n
assert 0 <= t < self._n
assert s != t
if flow_limit is None:
flow_limit = cast(int, sum(e.cap for e in self._g[s]))
current_edge = [0] * self._n
level = [0] * self._n
def fill(arr: List[int], value: int) -> None:
for i in range(len(arr)):
arr[i] = value
def bfs() -> bool:
fill(level, self._n)
queue = []
q_front = 0
queue.append(s)
level[s] = 0
while q_front < len(queue):
v = queue[q_front]
q_front += 1
next_level = level[v] + 1
for e in self._g[v]:
if e.cap == 0 or level[e.dst] <= next_level:
continue
level[e.dst] = next_level
if e.dst == t:
return True
queue.append(e.dst)
return False
def dfs(lim: int) -> int:
stack = []
edge_stack: List[MFGraph._Edge] = []
stack.append(t)
while stack:
v = stack[-1]
if v == s:
flow = min(lim, min(e.cap for e in edge_stack))
for e in edge_stack:
e.cap -= flow
assert e.rev is not None
e.rev.cap += flow
return flow
next_level = level[v] - 1
while current_edge[v] < len(self._g[v]):
e = self._g[v][current_edge[v]]
re = cast(MFGraph._Edge, e.rev)
if level[e.dst] != next_level or re.cap == 0:
current_edge[v] += 1
continue
stack.append(e.dst)
edge_stack.append(re)
break
else:
stack.pop()
if edge_stack:
edge_stack.pop()
level[v] = self._n
return 0
flow = 0
while flow < flow_limit:
if not bfs():
break
fill(current_edge, 0)
while flow < flow_limit:
f = dfs(flow_limit - flow)
flow += f
if f == 0:
break
return flow
def min_cut(self, s: int) -> List[bool]:
visited = [False] * self._n
stack = [s]
visited[s] = True
while stack:
v = stack.pop()
for e in self._g[v]:
if e.cap > 0 and not visited[e.dst]:
visited[e.dst] = True
stack.append(e.dst)
return visited
INF=10**20
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
k=max(b)
if k<=0:
print(0)
exit()
g=MFGraph(n+2)
for i in range(n):
b[i]=k-b[i]
for i in range(n):
g.add_edge(n,i,b[i])
g.add_edge(i,n+1,k)
for i in range(n):
q=[0]*101
for j in range(i-1,-1,-1):
if a[i]%a[j]==0 and q[a[j]]==0:
q[a[j]]=1
g.add_edge(j,i,INF)
print(k*n-g.flow(n,n+1))
``` | output | 1 | 92,858 | 13 | 185,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 ≤ k ≤ 109).
Output
You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 93,011 | 13 | 186,022 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
k=str(input())
l=len(k)
paths=[]
for i in range(l):
paths.append([1]*i+[int(k[i])]+[10]*(l-i-1))
lens = [sum(p) for p in paths]
n = sum(lens)+2
m = ['']*n
m[0] = 'N'*2
for i in range(len(paths)):
m[0] += 'Y'*paths[i][0]+'N'*(lens[i]-paths[i][0])
m[1] = 'N'
for i in range(len(paths)):
m[1] += 'N'*(lens[i]-paths[i][-1])+'Y'*paths[i][-1]
ind=2
for p in paths:
for i in range(len(p)-1):
for j in range(p[i]):
m[ind] = 'N'*(p[i]-j)+'Y'*(p[i+1])+'N'*n
ind+=1
for j in range(p[-1]):
m[ind] = 'N'*n
ind+=1
m2=['']*n
for i in range(n):
m2[i] = ''
for j in range(i):
m2[i]+=m2[j][i]
m2[i]+=m[i][:n-i]
print(len(m2))
for s in m2:
print(s)
``` | output | 1 | 93,011 | 13 | 186,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 ≤ k ≤ 109).
Output
You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 93,012 | 13 | 186,024 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
k = int(input())
edges = [['N' for i in range(1010)] for j in range(1010)]
vertices = 2
def add_edge(a, b):
global edges
edges[a][b] = edges[b][a] = 'Y'
for i in range(1, 29 + 1):
vertices += 3
add_edge(i * 3, i * 3 - 1)
add_edge(i * 3, i * 3 + 2)
add_edge(i * 3 + 1, i * 3 - 1)
add_edge(i * 3 + 1, i * 3 + 2)
for bit in range(30):
if (1 << bit) & k:
lst = 1
for i in range((29 - bit) * 2):
vertices += 1
add_edge(lst, vertices)
lst = vertices
add_edge(lst, 3 * bit + 2)
print(vertices)
if 0:
for i in range(1, vertices + 1):
print(i, ':', '\n\t', end='')
for j in range(1, vertices + 1):
if edges[i][j] == 'Y':
print(j, end=' ')
print('')
else:
print('\n'.join(map(lambda x: ''.join(x[1:vertices+1]), edges[1:vertices + 1])))
``` | output | 1 | 93,012 | 13 | 186,025 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 ≤ k ≤ 109).
Output
You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 93,013 | 13 | 186,026 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
n, m, cnt = int(input()), 148, 0
ans = [['N'] * m for i in range(m)]
def edge(i, j):
ans[i][j] = ans[j][i] = 'Y'
def node(*adj):
global cnt
i = cnt
cnt += 1
for j in adj:
edge(i, j)
return i
start, end, choice = node(), node(), node()
if n&1:
edge(choice, end)
for i in range(1, 30):
end, choice = node(node(end), node(end)), node(node(choice))
if n&(1<<i):
edge(choice, end)
edge(start, choice)
print(m)
for line in ans:
print(''.join(line))
# Made By Mostafa_Khaled
``` | output | 1 | 93,013 | 13 | 186,027 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2."
Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k?
Input
The first line contains a single integer k (1 ≤ k ≤ 109).
Output
You should output a graph G with n vertexes (2 ≤ n ≤ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph.
The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n.
The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them.
Examples
Input
2
Output
4
NNYY
NNYY
YYNN
YYNN
Input
9
Output
8
NNYYYNNN
NNNNNYYY
YNNNNYYY
YNNNNYYY
YNNNNYYY
NYYYYNNN
NYYYYNNN
NYYYYNNN
Input
1
Output
2
NY
YN
Note
In first example, there are 2 shortest paths: 1-3-2 and 1-4-2.
In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2. | instruction | 0 | 93,014 | 13 | 186,028 |
Tags: bitmasks, constructive algorithms, graphs, implementation, math
Correct Solution:
```
from collections import defaultdict
k=int(input())
mask=0
d=defaultdict(lambda:0)
while(mask<=30):
if k&(1<<mask):
d[mask]=1
ma=mask
mask+=1
adj=defaultdict(lambda:"N")
currl=1
currvu=3
prevu=[1]
prevl=[]
currvl=4
m=4
while((currl//2)<=ma):
if d[currl//2]:
adj[currvu,currvl]="Y"
adj[currvl, currvu] = "Y"
for j in prevu:
adj[currvu, j] = "Y"
adj[j, currvu] = "Y"
for j in prevl:
adj[currvl, j] = "Y"
adj[j, currvl] = "Y"
if ((currl+2)//2)<=ma:
prevu=[currvl+1,currvl+2]
for j in prevu:
adj[currvu, j] = "Y"
adj[j, currvu] = "Y"
prevl=[currvl+3]
for j in prevl:
adj[currvl, j] = "Y"
adj[j, currvl] = "Y"
currvu=currvl+4
currvl=currvu+1
m=max(m,currvl)
else:
break
currl+=2
print(m)
adj[2,currvl]="Y"
adj[currvl,2]="Y"
for i in range(1,m+1):
for j in range(1,m+1):
print(adj[i,j],end="")
print()
``` | output | 1 | 93,014 | 13 | 186,029 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.