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 |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has a tree consisting of n nodes numbered 1 to n rooted at node 1. The i-th node in the tree has a cost a_i, and binary digit b_i is written in it. He wants to have binary digit c_i written in the i-th node in the end.
To achieve this, he can perform the following operation any number of times:
* Select any k nodes from the subtree of any node u, and shuffle the digits in these nodes as he wishes, incurring a cost of k ⋅ a_u. Here, he can choose k ranging from 1 to the size of the subtree of u.
He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.
Help him find the minimum total cost he needs to spend so that after all the operations, every node u has digit c_u written in it, or determine that it is impossible.
Input
First line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) denoting the number of nodes in the tree.
i-th line of the next n lines contains 3 space-separated integers a_i, b_i, c_i (1 ≤ a_i ≤ 10^9, 0 ≤ b_i, c_i ≤ 1) — the cost of the i-th node, its initial digit and its goal digit.
Each of the next n - 1 lines contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v in the tree.
Output
Print the minimum total cost to make every node reach its target digit, and -1 if it is impossible.
Examples
Input
5
1 0 1
20 1 0
300 0 1
4000 0 0
50000 1 0
1 2
2 3
2 4
1 5
Output
4
Input
5
10000 0 1
2000 1 0
300 0 1
40 0 0
1 1 0
1 2
2 3
2 4
1 5
Output
24000
Input
2
109 0 1
205 0 1
1 2
Output
-1
Note
The tree corresponding to samples 1 and 2 are:
<image>
In sample 1, we can choose node 1 and k = 4 for a cost of 4 ⋅ 1 = 4 and select nodes {1, 2, 3, 5}, shuffle their digits and get the desired digits in every node.
In sample 2, we can choose node 1 and k = 2 for a cost of 10000 ⋅ 2, select nodes {1, 5} and exchange their digits, and similarly, choose node 2 and k = 2 for a cost of 2000 ⋅ 2, select nodes {2, 3} and exchange their digits to get the desired digits in every node.
In sample 3, it is impossible to get the desired digits, because there is no node with digit 1 initially.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
t = int(input())
C = [] # cost
P = [-1 for i in range(t)] # parents
Y = [] # difference in types
X = [[] for i in range(t)]
for i in range(t):
a,b,c = list(map(int, input().split()))
C.append(a)
Y.append(b-c)
for i in range(t-1):
a,b = list(map(int, input().split()))
a -= 1
b -= 1
X[a].append(b)
#X[b].append(a)
if sum(Y) != 0:
print(-1)
exit()
else:
R = [] # list of nodes in order
Q = deque([0])
while Q:
x = deque.popleft(Q)
R.append(x)
for c in X[x]:
P[c] = x
deque.append(Q,c)
#print(P)
#print(R)
for j in R[1:]:
C[j] = min(C[j], C[P[j]])
#print(Y)
ans = 0
for i in R[1:][::-1]:
if Y[i] != Y[P[i]]:
ans += C[P[i]] * min(abs(Y[i]), abs(Y[P[i]]))
Y[P[i]] += Y[i]
print(ans*2)
``` | instruction | 0 | 108,000 | 13 | 216,000 |
No | output | 1 | 108,000 | 13 | 216,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has a tree consisting of n nodes numbered 1 to n rooted at node 1. The i-th node in the tree has a cost a_i, and binary digit b_i is written in it. He wants to have binary digit c_i written in the i-th node in the end.
To achieve this, he can perform the following operation any number of times:
* Select any k nodes from the subtree of any node u, and shuffle the digits in these nodes as he wishes, incurring a cost of k ⋅ a_u. Here, he can choose k ranging from 1 to the size of the subtree of u.
He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.
Help him find the minimum total cost he needs to spend so that after all the operations, every node u has digit c_u written in it, or determine that it is impossible.
Input
First line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) denoting the number of nodes in the tree.
i-th line of the next n lines contains 3 space-separated integers a_i, b_i, c_i (1 ≤ a_i ≤ 10^9, 0 ≤ b_i, c_i ≤ 1) — the cost of the i-th node, its initial digit and its goal digit.
Each of the next n - 1 lines contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v in the tree.
Output
Print the minimum total cost to make every node reach its target digit, and -1 if it is impossible.
Examples
Input
5
1 0 1
20 1 0
300 0 1
4000 0 0
50000 1 0
1 2
2 3
2 4
1 5
Output
4
Input
5
10000 0 1
2000 1 0
300 0 1
40 0 0
1 1 0
1 2
2 3
2 4
1 5
Output
24000
Input
2
109 0 1
205 0 1
1 2
Output
-1
Note
The tree corresponding to samples 1 and 2 are:
<image>
In sample 1, we can choose node 1 and k = 4 for a cost of 4 ⋅ 1 = 4 and select nodes {1, 2, 3, 5}, shuffle their digits and get the desired digits in every node.
In sample 2, we can choose node 1 and k = 2 for a cost of 10000 ⋅ 2, select nodes {1, 5} and exchange their digits, and similarly, choose node 2 and k = 2 for a cost of 2000 ⋅ 2, select nodes {2, 3} and exchange their digits to get the desired digits in every node.
In sample 3, it is impossible to get the desired digits, because there is no node with digit 1 initially.
Submitted Solution:
```
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == "\n":
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
ans = 0
def solve():
global ans
def dfs(x):
global ans
p = [0,0]
if b[x] != c[x]:
p[b[x]] += 1
for y in v[x]:
if d[y]:
d[y] = 0
q = dfs(y)
p[0] += q[0]
p[1] += q[1]
m = min(p)
ans += m*a[x]
p[0] -= m
p[1] -= m
return p
n = I()
a = []
b = []
c = []
for _ in range(n):
x,y,z = LI()
a.append(x)
b.append(y)
c.append(z)
v = [[] for i in range(n)]
for _ in range(n-1):
x,y = LI()
x -= 1
y -= 1
v[x].append(y)
v[y].append(x)
if b.count(1) != c.count(1):
print(-1)
return
q = [0]
d = [1]*n
d[0] = 0
while q:
x = q.pop()
ax = a[x]
for y in v[x]:
if d[y]:
d[y] = 0
if ax < a[y]:
a[y] = ax
q.append(y)
d = [1]*n
dfs(0)
print(ans*2)
return
#Solve
if __name__ == "__main__":
solve()
``` | instruction | 0 | 108,001 | 13 | 216,002 |
No | output | 1 | 108,001 | 13 | 216,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has a tree consisting of n nodes numbered 1 to n rooted at node 1. The i-th node in the tree has a cost a_i, and binary digit b_i is written in it. He wants to have binary digit c_i written in the i-th node in the end.
To achieve this, he can perform the following operation any number of times:
* Select any k nodes from the subtree of any node u, and shuffle the digits in these nodes as he wishes, incurring a cost of k ⋅ a_u. Here, he can choose k ranging from 1 to the size of the subtree of u.
He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.
Help him find the minimum total cost he needs to spend so that after all the operations, every node u has digit c_u written in it, or determine that it is impossible.
Input
First line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) denoting the number of nodes in the tree.
i-th line of the next n lines contains 3 space-separated integers a_i, b_i, c_i (1 ≤ a_i ≤ 10^9, 0 ≤ b_i, c_i ≤ 1) — the cost of the i-th node, its initial digit and its goal digit.
Each of the next n - 1 lines contain two integers u, v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v in the tree.
Output
Print the minimum total cost to make every node reach its target digit, and -1 if it is impossible.
Examples
Input
5
1 0 1
20 1 0
300 0 1
4000 0 0
50000 1 0
1 2
2 3
2 4
1 5
Output
4
Input
5
10000 0 1
2000 1 0
300 0 1
40 0 0
1 1 0
1 2
2 3
2 4
1 5
Output
24000
Input
2
109 0 1
205 0 1
1 2
Output
-1
Note
The tree corresponding to samples 1 and 2 are:
<image>
In sample 1, we can choose node 1 and k = 4 for a cost of 4 ⋅ 1 = 4 and select nodes {1, 2, 3, 5}, shuffle their digits and get the desired digits in every node.
In sample 2, we can choose node 1 and k = 2 for a cost of 10000 ⋅ 2, select nodes {1, 5} and exchange their digits, and similarly, choose node 2 and k = 2 for a cost of 2000 ⋅ 2, select nodes {2, 3} and exchange their digits to get the desired digits in every node.
In sample 3, it is impossible to get the desired digits, because there is no node with digit 1 initially.
Submitted Solution:
```
# from math import factorial as fac
from collections import defaultdict
# from copy import deepcopy
import sys, math
f = None
try:
f = open('q1.input', 'r')
except IOError:
f = sys.stdin
if 'xrange' in dir(__builtins__):
range = xrange
# print(f.readline())
def print_case_iterable(case_num, iterable):
print("Case #{}: {}".format(case_num," ".join(map(str,iterable))))
def print_case_number(case_num, iterable):
print("Case #{}: {}".format(case_num,iterable))
def print_iterable(A):
print (' '.join(A))
def read_int():
return int(f.readline().strip())
def read_int_array():
return [int(x) for x in f.readline().strip().split(" ")]
def rns():
a = [x for x in f.readline().split(" ")]
return int(a[0]), a[1].strip()
def read_string():
return list(f.readline().strip())
def bi(x):
return bin(x)[2:]
from collections import deque
import math
from collections import deque, defaultdict
import heapq
from sys import stdout
# a=cost, b=written, c=wanted
import threading
sys.setrecursionlimit(2*10**5+2)
# sys.setrecursionlimit(10**6)
threading.stack_size(10**8)
def dfs(v,adj,curr_min,visited,data,res):
visited[v] = True
curr_min = min(curr_min,data[v][0])
balance = data[v][2]-data[v][1]
total = abs(balance)
for u in adj[v]:
if visited[u]:
continue
zeros = dfs(u,adj,curr_min,visited,data,res)
balance += zeros
total += abs(zeros)
res[0] += curr_min * (total-abs(balance))
return balance
def solution(n,data,adj):
#dfs, correct as much as possible with minimum up to know, propogate up.
visited = [False]*(n+1)
res = [0]
balance = dfs(1,adj,10**10,visited,data,res)
if balance == 0:
return res[0]
return -1
def main():
T = 1
for i in range(T):
n = read_int()
adj = defaultdict(list)
data = [0]
for j in range(n):
data.append(read_int_array())
for j in range(n-1):
u,v = read_int_array()
adj[u].append(v)
adj[v].append(u)
x = solution(n,data,adj)
if 'xrange' not in dir(__builtins__):
print(x)
else:
print >>output,str(x)# "Case #"+str(i+1)+':',
if 'xrange' in dir(__builtins__):
print(output.getvalue())
output.close()
stdout.flush()
if 'xrange' in dir(__builtins__):
import cStringIO
output = cStringIO.StringIO()
#example usage:
# for l in res:
# print >>output, str(len(l)) + ' ' + ' '.join(l)
threading.stack_size(10**8)
if __name__ == '__main__':
t = threading.Thread(target=main)
t.start()
t.join()
stdout.flush()
stdout.flush()
print(-1)
``` | instruction | 0 | 108,002 | 13 | 216,004 |
No | output | 1 | 108,002 | 13 | 216,005 |
Provide tags and a correct Python 3 solution for this coding contest problem.
George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria:
* The graph doesn't contain any multiple arcs;
* There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v).
* The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops.
However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph.
George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 1000) — the number of vertices and arcs in the presented graph.
Each of the next m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs.
Assume that the grah vertices are numbered 1 through n.
Output
Print a single integer — the answer to George's question.
Examples
Input
3 7
1 1
2 2
3 1
1 3
3 2
2 3
3 3
Output
0
Input
3 6
1 1
2 2
3 1
3 2
2 3
3 3
Output
1
Input
3 1
2 2
Output
6
Note
For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph
In the first sample the graph already is interesting, its center is vertex 3. | instruction | 0 | 108,180 | 13 | 216,360 |
Tags: graph matchings
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def matching(n,m,path):
# Hopkrocft Karp O(EV^0.5)
match1 = [-1]*n
match2 = [-1]*m
for node in range(n):
for nei in path[node]:
if match2[nei] == -1:
match1[node] = nei
match2[nei] = node
break
while 1:
bfs = [node for node in range(n) if match1[node] == -1]
depth = [-1]*n
for node in bfs:
depth[node] = 0
for node in bfs:
for nei in path[node]:
next_node = match2[nei]
if next_node == -1:
break
if depth[next_node] == -1:
depth[next_node] = depth[node]+1
bfs.append(next_node)
else:
continue
break
else:
break
pointer = [len(c) for c in path]
dfs = [node for node in range(n) if depth[node] == 0]
while dfs:
node = dfs[-1]
while pointer[node]:
pointer[node] -= 1
nei = path[node][pointer[node]]
next_node = match2[nei]
if next_node == -1:
while nei != -1:
node = dfs.pop()
match2[nei],match1[node],nei = node,nei,match1[node]
break
elif depth[node]+1 == depth[next_node]:
dfs.append(next_node)
break
else:
dfs.pop()
return n-match1.count(-1)
def main():
n,m = map(int,input().split())
edg = [tuple(map(lambda xx:int(xx)-1,input().split())) for _ in range(m)]
ans = float("inf")
for centre in range(n):
path = [[] for _ in range(n)]
cost = 2*n-1
extra = m
for u,v in edg:
if u == centre or v == centre:
cost -= 1
extra -= 1
else:
path[u].append(v)
maxMatch = matching(n,n,path)
extra -= maxMatch
cost += n-1-maxMatch+extra
ans = min(ans,cost)
print(ans)
# 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 | 108,180 | 13 | 216,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria:
* The graph doesn't contain any multiple arcs;
* There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v).
* The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops.
However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph.
George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 1000) — the number of vertices and arcs in the presented graph.
Each of the next m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs.
Assume that the grah vertices are numbered 1 through n.
Output
Print a single integer — the answer to George's question.
Examples
Input
3 7
1 1
2 2
3 1
1 3
3 2
2 3
3 3
Output
0
Input
3 6
1 1
2 2
3 1
3 2
2 3
3 3
Output
1
Input
3 1
2 2
Output
6
Note
For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph
In the first sample the graph already is interesting, its center is vertex 3.
Submitted Solution:
```
import sys
def invariant(edges, incomingEdges):
edgesCount = sum(map(len, edges))
incomingCount = sum(map(len, incomingEdges))
assert edgesCount == incomingCount, "%i %i - %s %s" % (edgesCount, incomingCount, edges, incomingEdges)
for (i, edge) in enumerate(edges):
for e in edge:
assert i in incomingEdges[e], "%i %s" % (i, incomingEdges[e])
def findCenter(edges, incomingEdges):
center = 0
max = 0
for (i, edge) in enumerate(edges):
outLength = len(edge)
inLength = len(incomingEdges[i])
if i in incomingEdges:
inLength -= 1
if outLength + inLength > max:
max = outLength + inLength
center = i
return center
def centerise(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
if not i in edges[i]:
edges[i].append(i)
incomingEdges[i].append(i)
count += 1
else:
if not center in edge: # в центр
edge.append(center)
incomingEdges[center].append(i)
count += 1
if not i in edges[center]: # из центра в меня
edges[center].append(i)
incomingEdges[i].append(center)
count += 1
return count
def deleteExtra(edges, incomingEdges, center):
count = 0
#outgoing overhead
for (i, edge) in enumerate(edges):
if i == center:
continue
while len(edge) > 2:
for outgoingEdge in edge:
if outgoingEdge == center or i == outgoingEdge:
continue
if len(incomingEdges[outgoingEdge]) > 2:
edge.remove(outgoingEdge)
incomingEdges[outgoingEdge].remove(i)
count += 1
break
else: # passed all element
break
if len(edge) > 2 and i in edge:
edge.remove(i)
incomingEdges[i].remove(i)
count += 1
while len(edge) > 2:
for (j, toRemove) in enumerate(edge):
if j == center:
continue
edge.remove(toRemove)
incomingEdges[toRemove].remove(i)
count += 1
break
return count
def addRequired(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
continue
if len(edge) < 2:
#we should add edge
#look for candidate
for (j, incomingEdge) in enumerate(incomingEdges):
#print("%s %s" % (incomingEdges, incomingEdge))
if len(edge) >= 2:
break
if i in incomingEdge:
continue
if len(incomingEdge) < 2:
edge.append(j)
incomingEdge.append(i)
count += 1
#if len(edge) < 2 and i not in edge:
# edge.append(i)
# incomingEdges[i].append(i)
# count += 1
#assert len(edge) == 2, "len(%i) != %i" % (i, len(edge))
return count
def addLoops(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
continue
if len(edge) < 2 and i not in edge:
edge.append(i)
incomingEdges[i].append(i)
count += 1
assert len(edge) == 2, "len(%i) != %i" % (i, len(edge))
return count
def read():
pairs = []
firstRow = sys.stdin.readline()
pairs.append(firstRow)
v = int(firstRow.split(' ')[1])
for i in range(v):
eString = sys.stdin.readline()
pairs.append(eString)
return pairs
def parse(pairs):
firstrow = pairs[0].split(' ')
(E, V) = (int(firstrow[0]), int(firstrow[1]))
es = []
ies = []
for i in range(E):
es.append([])
ies.append([])
for row in pairs[1:]:
eString = row.split(' ')
eFrom = int(eString[0]) - 1
eTo = int(eString[1]) - 1
es[eFrom].append(eTo)
ies[eTo].append(eFrom)
return es, ies
def main(edges, incomingEdges):
invariant(edges, incomingEdges)
center = findCenter(edges, incomingEdges)
result = 0
centerLen = len(edges[center]) + len(incomingEdges[center])
if centerLen != len(edges) * 2:
result += centerise(edges, incomingEdges, center)
invariant(edges, incomingEdges)
invariant(edges, incomingEdges)
result += addRequired(edges, incomingEdges, center)
result += deleteExtra(edges, incomingEdges, center)
invariant(edges, incomingEdges)
result += deleteExtra(incomingEdges, edges, center)
result += addLoops(edges, incomingEdges, center)
invariant(edges, incomingEdges)
return result
rows = read()
edges, incomingEdges = parse(rows)
result = main(edges, incomingEdges)
print(result)
``` | instruction | 0 | 108,181 | 13 | 216,362 |
No | output | 1 | 108,181 | 13 | 216,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria:
* The graph doesn't contain any multiple arcs;
* There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v).
* The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops.
However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph.
George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 1000) — the number of vertices and arcs in the presented graph.
Each of the next m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs.
Assume that the grah vertices are numbered 1 through n.
Output
Print a single integer — the answer to George's question.
Examples
Input
3 7
1 1
2 2
3 1
1 3
3 2
2 3
3 3
Output
0
Input
3 6
1 1
2 2
3 1
3 2
2 3
3 3
Output
1
Input
3 1
2 2
Output
6
Note
For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph
In the first sample the graph already is interesting, its center is vertex 3.
Submitted Solution:
```
import sys
def invariant(edges, incomingEdges):
edgesCount = sum(map(len, edges))
incomingCount = sum(map(len, incomingEdges))
assert edgesCount == incomingCount, "%i %i - %s %s" % (edgesCount, incomingCount, edges, incomingEdges)
for (i, edge) in enumerate(edges):
for e in edge:
assert i in incomingEdges[e], "%i %s" % (i, incomingEdges[e])
def findCenter(edges, incomingEdges):
center = 0
max = 0
for (i, edge) in enumerate(edges):
outLength = len(edge)
inLength = len(incomingEdges[i])
if outLength + inLength > max:
max = outLength + inLength
center = i
return center
def centerise(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
if not i in edges[i]:
edges[i].append(i)
incomingEdges[i].append(i)
count += 1
else:
if not center in edge: # в центр
edge.append(center)
incomingEdges[center].append(i)
count += 1
if not i in edges[center]: # из центра в меня
edges[center].append(i)
incomingEdges[i].append(center)
count += 1
return count
def deleteExtra(edges, incomingEdges, center):
count = 0
#outgoing overhead
for (i, edge) in enumerate(edges):
if i == center:
continue
while len(edge) > 2:
for outgoingEdge in edge:
if outgoingEdge == center or i == outgoingEdge:
continue
if len(incomingEdges[outgoingEdge]) > 2:
edge.remove(outgoingEdge)
incomingEdges[outgoingEdge].remove(i)
count += 1
break
else: # passed all element
break
if len(edge) > 2 and i in edge:
edge.remove(i)
incomingEdges[i].remove(i)
count += 1
while len(edge) > 2:
for (j, toRemove) in enumerate(edge):
if j == center:
continue
edge.remove(toRemove)
incomingEdges[toRemove].remove(i)
count += 1
break
return count
def addRequired(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
continue
if len(edge) < 2:
#we should add edge
#look for candidate
for (j, incomingEdge) in enumerate(incomingEdges):
#print("%s %s" % (incomingEdges, incomingEdge))
if len(edge) >= 2:
break
if i in incomingEdge:
continue
if len(incomingEdge) < 2:
edge.append(j)
incomingEdge.append(i)
count += 1
if len(edge) < 2 and i not in edge:
edge.append(i)
incomingEdges[i].append(i)
count += 1
#assert len(edge) == 2, "len(%i) != %i" % (i, len(edge))
return count
def read():
pairs = []
firstRow = sys.stdin.readline()
pairs.append(firstRow)
v = int(firstRow.split(' ')[1])
for i in range(v):
eString = sys.stdin.readline()
pairs.append(eString)
return pairs
def parse(pairs):
firstrow = pairs[0].split(' ')
(E, V) = (int(firstrow[0]), int(firstrow[1]))
es = []
ies = []
for i in range(E):
es.append([])
ies.append([])
for row in pairs[1:]:
eString = row.split(' ')
eFrom = int(eString[0]) - 1
eTo = int(eString[1]) - 1
es[eFrom].append(eTo)
ies[eTo].append(eFrom)
return es, ies
def main(edges, incomingEdges):
invariant(edges, incomingEdges)
center = findCenter(edges, incomingEdges)
result = 0
centerLen = len(edges[center]) + len(incomingEdges[center])
if centerLen != len(edges) * 2:
result += centerise(edges, incomingEdges, center)
invariant(edges, incomingEdges)
invariant(edges, incomingEdges)
result += addRequired(edges, incomingEdges, center)
result += deleteExtra(edges, incomingEdges, center)
invariant(edges, incomingEdges)
result += deleteExtra(incomingEdges, edges, center)
invariant(edges, incomingEdges)
return result
rows = read()
edges, incomingEdges = parse(rows)
result = main(edges, incomingEdges)
print(result)
``` | instruction | 0 | 108,182 | 13 | 216,364 |
No | output | 1 | 108,182 | 13 | 216,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria:
* The graph doesn't contain any multiple arcs;
* There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v).
* The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops.
However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph.
George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 1000) — the number of vertices and arcs in the presented graph.
Each of the next m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs.
Assume that the grah vertices are numbered 1 through n.
Output
Print a single integer — the answer to George's question.
Examples
Input
3 7
1 1
2 2
3 1
1 3
3 2
2 3
3 3
Output
0
Input
3 6
1 1
2 2
3 1
3 2
2 3
3 3
Output
1
Input
3 1
2 2
Output
6
Note
For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph
In the first sample the graph already is interesting, its center is vertex 3.
Submitted Solution:
```
import sys
def invariant(edges, incomingEdges):
edgesCount = sum(map(len, edges))
incomingCount = sum(map(len, incomingEdges))
assert edgesCount == incomingCount, "%i %i - %s %s" % (edgesCount, incomingCount, edges, incomingEdges)
for (i, edge) in enumerate(edges):
for e in edge:
assert i in incomingEdges[e], "%i %s" % (i, incomingEdges[e])
def findCenter(edges, incomingEdges):
center = 0
max = 0
for (i, edge) in enumerate(edges):
outLength = len(edge)
inLength = len(incomingEdges[i])
if outLength + inLength > max:
max = outLength + inLength
center = i
return center
def centerise(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
if not i in edges[i]:
edges[i].append(i)
incomingEdges[i].append(i)
count += 1
else:
if not center in edge: # в центр
edge.append(center)
incomingEdges[center].append(i)
count += 1
if not i in edges[center]: # из центра в меня
edges[center].append(i)
incomingEdges[i].append(center)
count += 1
return count
def deleteExtra(edges, incomingEdges, center):
count = 0
#outgoing overhead
for (i, edge) in enumerate(edges):
if i == center:
continue
while len(edge) > 2:
for outgoingEdge in edge:
if outgoingEdge == center or i == outgoingEdge:
continue
if len(incomingEdges[outgoingEdge]) > 2:
edge.remove(outgoingEdge)
incomingEdges[outgoingEdge].remove(i)
count += 1
break
else: # passed all element
break
if len(edge) > 2 and i in edge:
edge.remove(i)
incomingEdges[i].remove(i)
count += 1
while len(edge) > 2:
for (j, toRemove) in enumerate(edge):
if j == center:
continue
edge.remove(toRemove)
incomingEdges[toRemove].remove(i)
count += 1
break
return count
def addRequired(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
continue
if len(edge) < 2:
#we should add edge
#look for candidate
for (j, incomingEdge) in enumerate(incomingEdges):
#print("%s %s" % (incomingEdges, incomingEdge))
if len(edge) >= 2:
break
if i in incomingEdge:
continue
if len(incomingEdge) < 2:
edge.append(j)
incomingEdge.append(i)
count += 1
#if len(edge) < 2 and i not in edge:
# edge.append(i)
# incomingEdges[i].append(i)
# count += 1
#assert len(edge) == 2, "len(%i) != %i" % (i, len(edge))
return count
def addLoops(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
continue
if len(edge) < 2 and i not in edge:
edge.append(i)
incomingEdges[i].append(i)
count += 1
assert len(edge) == 2, "len(%i) != %i" % (i, len(edge))
return count
def read():
pairs = []
firstRow = sys.stdin.readline()
pairs.append(firstRow)
v = int(firstRow.split(' ')[1])
for i in range(v):
eString = sys.stdin.readline()
pairs.append(eString)
return pairs
def parse(pairs):
firstrow = pairs[0].split(' ')
(E, V) = (int(firstrow[0]), int(firstrow[1]))
es = []
ies = []
for i in range(E):
es.append([])
ies.append([])
for row in pairs[1:]:
eString = row.split(' ')
eFrom = int(eString[0]) - 1
eTo = int(eString[1]) - 1
es[eFrom].append(eTo)
ies[eTo].append(eFrom)
return es, ies
def main(edges, incomingEdges):
invariant(edges, incomingEdges)
center = findCenter(edges, incomingEdges)
result = 0
centerLen = len(edges[center]) + len(incomingEdges[center])
if centerLen != len(edges) * 2:
result += centerise(edges, incomingEdges, center)
invariant(edges, incomingEdges)
invariant(edges, incomingEdges)
result += addRequired(edges, incomingEdges, center)
result += deleteExtra(edges, incomingEdges, center)
invariant(edges, incomingEdges)
result += deleteExtra(incomingEdges, edges, center)
result += addLoops(edges, incomingEdges, center)
invariant(edges, incomingEdges)
return result
rows = read()
edges, incomingEdges = parse(rows)
result = main(edges, incomingEdges)
print(result)
``` | instruction | 0 | 108,183 | 13 | 216,366 |
No | output | 1 | 108,183 | 13 | 216,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
George loves graphs. Most of all, he loves interesting graphs. We will assume that a directed graph is interesting, if it meets the following criteria:
* The graph doesn't contain any multiple arcs;
* There is vertex v (we'll call her the center), such that for any vertex of graph u, the graph contains arcs (u, v) and (v, u). Please note that the graph also contains loop (v, v).
* The outdegree of all vertexes except for the center equals two and the indegree of all vertexes except for the center equals two. The outdegree of vertex u is the number of arcs that go out of u, the indegree of vertex u is the number of arcs that go in u. Please note that the graph can contain loops.
However, not everything's that simple. George got a directed graph of n vertices and m arcs as a present. The graph didn't have any multiple arcs. As George loves interesting graphs, he wants to slightly alter the presented graph and transform it into an interesting one. In one alteration he can either remove an arbitrary existing arc from the graph or add an arbitrary arc to the graph.
George wonders: what is the minimum number of changes that he needs to obtain an interesting graph from the graph he's got as a present? Help George and find the answer to the question.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 1000) — the number of vertices and arcs in the presented graph.
Each of the next m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the descriptions of the graph's arcs. Pair (ai, bi) means that the graph contains an arc from vertex number ai to vertex number bi. It is guaranteed that the presented graph doesn't contain multiple arcs.
Assume that the grah vertices are numbered 1 through n.
Output
Print a single integer — the answer to George's question.
Examples
Input
3 7
1 1
2 2
3 1
1 3
3 2
2 3
3 3
Output
0
Input
3 6
1 1
2 2
3 1
3 2
2 3
3 3
Output
1
Input
3 1
2 2
Output
6
Note
For more information about directed graphs, please visit: http://en.wikipedia.org/wiki/Directed_graph
In the first sample the graph already is interesting, its center is vertex 3.
Submitted Solution:
```
import sys
def findCenter(edges, incomingEdges):
center = 0
max = 0
for (i, edge) in enumerate(edges):
outLength = len(edge)
inLength = len(incomingEdges[i])
if i in incomingEdges:
inLength -= 1
if outLength + inLength > max:
max = outLength + inLength
center = i
return center
def centerise(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
if not i in edges[i]:
edges[i].append(i)
incomingEdges[i].append(i)
count += 1
else:
if not center in edge: # в центр
edge.append(center)
incomingEdges[center].append(i)
count += 1
if not i in edges[center]: # из центра в меня
edges[center].append(i)
incomingEdges[i].append(center)
count += 1
return count
def deleteExtra(edges, incomingEdges, center):
count = 0
#outgoing overhead
for (i, edge) in enumerate(edges):
if i == center:
continue
while len(edge) > 2:
for outgoingEdge in edge:
if outgoingEdge == center or i == outgoingEdge:
continue
if len(incomingEdges[outgoingEdge]) > 2:
edge.remove(outgoingEdge)
incomingEdges[outgoingEdge].remove(i)
count += 1
break
else: # passed all element
break
if len(edge) > 2 and i in edge:
edge.remove(i)
incomingEdges[i].remove(i)
count += 1
while len(edge) > 2:
for toRemove in edge:
if toRemove == center:
continue
edge.remove(toRemove)
incomingEdges[toRemove].remove(i)
count += 1
break
return count
def addRequired(edges, incomingEdges, center):
count = 0
for (i, edge) in enumerate(edges):
if i == center:
continue
while len(edge) < 2:
if len(incomingEdges[i]) < 2:
edge.append(i)
incomingEdges[i].append(i)
count += 1
else:
for (j, incomingEdge) in enumerate(incomingEdges):
if len(incomingEdge) < 2:
incomingEdge.append(i)
edge.append(j)
count += 1
break
return count
def read():
pairs = []
firstRow = sys.stdin.readline()
pairs.append(firstRow)
v = int(firstRow.split(' ')[1])
for i in range(v):
eString = sys.stdin.readline()
pairs.append(eString)
return pairs
def parse(pairs):
firstrow = pairs[0].split(' ')
(E, V) = (int(firstrow[0]), int(firstrow[1]))
es = []
ies = []
for i in range(E):
es.append([])
ies.append([])
for row in pairs[1:]:
eString = row.split(' ')
eFrom = int(eString[0]) - 1
eTo = int(eString[1]) - 1
es[eFrom].append(eTo)
ies[eTo].append(eFrom)
return es, ies
def check(edges, center):
for (i, edge) in enumerate(edges):
if i == center:
assert len(edge) == len(edges), "len = %i, %s" % (len(edge), edge)
continue
assert len(edge) == 2, "len() == %i %s i=%i" % (len(edge), edge, i)
def main(edges, incomingEdges):
center = findCenter(edges, incomingEdges)
result = 0
centerLen = len(edges[center]) + len(incomingEdges[center])
if centerLen != len(edges) * 2:
result += centerise(edges, incomingEdges, center)
result += deleteExtra(edges, incomingEdges, center)
result += deleteExtra(incomingEdges, edges, center)
result += addRequired(edges, incomingEdges, center)
check(edges, center)
check(incomingEdges, center)
return result
rows = read()
edges, incomingEdges = parse(rows)
result = main(edges, incomingEdges)
print(result)
``` | instruction | 0 | 108,184 | 13 | 216,368 |
No | output | 1 | 108,184 | 13 | 216,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two trees (connected undirected acyclic graphs) S and T.
Count the number of subtrees (connected subgraphs) of S that are isomorphic to tree T. Since this number can get quite large, output it modulo 109 + 7.
Two subtrees of tree S are considered different, if there exists a vertex in S that belongs to exactly one of them.
Tree G is called isomorphic to tree H if there exists a bijection f from the set of vertices of G to the set of vertices of H that has the following property: if there is an edge between vertices A and B in tree G, then there must be an edge between vertices f(A) and f(B) in tree H. And vice versa — if there is an edge between vertices A and B in tree H, there must be an edge between f - 1(A) and f - 1(B) in tree G.
Input
The first line contains a single integer |S| (1 ≤ |S| ≤ 1000) — the number of vertices of tree S.
Next |S| - 1 lines contain two integers ui and vi (1 ≤ ui, vi ≤ |S|) and describe edges of tree S.
The next line contains a single integer |T| (1 ≤ |T| ≤ 12) — the number of vertices of tree T.
Next |T| - 1 lines contain two integers xi and yi (1 ≤ xi, yi ≤ |T|) and describe edges of tree T.
Output
On the first line output a single integer — the answer to the given task modulo 109 + 7.
Examples
Input
5
1 2
2 3
3 4
4 5
3
1 2
2 3
Output
3
Input
3
2 3
3 1
3
1 2
1 3
Output
1
Input
7
1 2
1 3
1 4
1 5
1 6
1 7
4
4 1
4 2
4 3
Output
20
Input
5
1 2
2 3
3 4
4 5
4
4 1
4 2
4 3
Output
0
Submitted Solution:
```
a=int(input())
``` | instruction | 0 | 108,309 | 13 | 216,618 |
No | output | 1 | 108,309 | 13 | 216,619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.