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.
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.
Submitted Solution:
```
n, m = 337, int(input())
p = [['N'] * n for i in range(n)]
def f(i, j): p[i][j] = p[j][i] = 'Y'
k = 6 + 15 * 5
for j in range(2, 6): f(1, j)
for i in range(6, k, 5):
for j in range(i - 4, i): f(i, j)
for j in range(i + 1, i + 5): f(i, j)
q, d, s = 4 ** 15, 0, k
while q:
if m >= q:
t = m // q
m -= t * q
if d == 0:
for j in range(k - t, k): f(0, j)
else:
f(0, s)
for i in range(s, s + d): f(i, i + 1)
s += d
for j in range(k - t, k): f(s, j)
s += 1
k -= 5
d += 2
q //= 4
print(s)
for i in range(s): print(''.join(p[i][: s]))
``` | instruction | 0 | 98,984 | 13 | 197,968 |
Yes | output | 1 | 98,984 | 13 | 197,969 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted 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 = node([])
end = node([])
choice = node([end] if n&1 else [])
for i in range(1, 30):
end = node([node([end]), node([end])])
choice = node([node([choice])] + ([end] if (n>>i)&1 else []))
edge(start, choice)
print(m)
for line in ans:
print(''.join(line))
``` | instruction | 0 | 98,985 | 13 | 197,970 |
Yes | output | 1 | 98,985 | 13 | 197,971 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
class Node(object):
cnt = 0
def __init__(_, adj=None):
_.id = Node.cnt
Node.cnt += 1
_.adj = adj if adj else []
_.seen = False
def dfs(_):
if _.seen:
return
_.seen = True
for i in _.adj:
ans[_.id][i.id] = ans[_.id][i.id] = 'Y'
i.dfs()
n = int(input())
start = Node()
end = Node()
choose = Node()
for i in range(30):
if n & (1<<i):
choose.adj.append(end)
if i == 29:
break
end = Node([Node([end]), Node([end])])
choose = Node([Node([choose])])
start.adj.append(choose)
ans = [['N'] * Node.cnt for i in range(Node.cnt)]
start.dfs()
print(Node.cnt)
for line in ans:
print(''.join(line))
``` | instruction | 0 | 98,986 | 13 | 197,972 |
No | output | 1 | 98,986 | 13 | 197,973 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n, t = 901, format(int(input()), 'b')
t = [i for i in range(len(t)) if t[i] == '1']
p = [['N'] * n for i in range(n)]
def f(i, j): p[i][j] = p[j][i] = 'Y'
for i in range(2, 30): f(i, i + 1)
f(30, 1)
for i in range(29):
b = 31 + i * (i + 1)
for a in range(b, b + 2 * i, 2):
f(a, a + 2)
f(a, a + 3)
f(a + 1, a + 2)
f(a + 1, a + 3)
a = b + 2 * i
if i < 28:
f(a, i + 3)
f(a + 1, i + 3)
else:
f(a, 1)
f(a + 1, 1)
for i in t:
if i == 0: f(0, 2)
else:
j = 31 + (i - 1) * i
f(0, j)
f(0, j + 1)
print(n)
for i in p: print(''.join(i))
``` | instruction | 0 | 98,987 | 13 | 197,974 |
No | output | 1 | 98,987 | 13 | 197,975 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
n, m = 322, int(input())
p = [['N'] * n for i in range(n)]
def f(i, j): p[i][j] = p[j][i] = 'Y'
k = 6 + 15 * 5
for j in range(k + 1, k + 5): f(k, j)
for i in range(6, k, 5):
for j in range(i - 4, i): f(i, j)
for j in range(i + 1, i + 5): f(i, j)
for j in range(k - 4, k): f(k, j)
q, d, s = 4 ** 15, 0, k
while q:
if m > q:
t = m // q
m -= t * q
if d == 0:
for j in range(k - t, k): f(0, j)
else:
f(0, s)
for i in range(s, s + d): f(i, i + 1)
s += d
for j in range(k - t, k): f(s, j)
k -= 5
d += 2
q //= 4
s += 1
print(n)
for i in range(s): print(''.join(p[i][: s]))
``` | instruction | 0 | 98,988 | 13 | 197,976 |
No | output | 1 | 98,988 | 13 | 197,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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.
Submitted Solution:
```
class Node(object):
cnt = 0
def __init__(_, adj=None):
_.id = Node.cnt
Node.cnt += 1
_.adj = adj if adj else []
_.seen = False
n = int(input())
start = Node()
end = Node()
choose = Node()
for i in range(30):
if n & (1<<i):
choose.adj.append(end)
if i == 29:
break
end = Node([Node([end]), Node([end])])
choose = Node([Node([choose])])
start.adj.append(choose)
ans = [['N'] * Node.cnt for i in range(Node.cnt)]
def dfs(v):
if v.seen:
return
v.seen = True
for u in v.adj:
ans[v.id][u.id] = ans[v.id][u.id] = 'Y'
dfs(u)
dfs(start)
print(Node.cnt)
for line in ans:
print(''.join(line))
``` | instruction | 0 | 98,989 | 13 | 197,978 |
No | output | 1 | 98,989 | 13 | 197,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i. The lengths of all the edges are 1.
Snuke likes some of the vertices. The information on his favorite vertices are given to you as a string s of length N. For each 1 ≤ i ≤ N, s_i is `1` if Snuke likes vertex i, and `0` if he does not like vertex i.
Initially, all the vertices are white. Snuke will perform the following operation exactly once:
* Select a vertex v that he likes, and a non-negative integer d. Then, paint all the vertices black whose distances from v are at most d.
Find the number of the possible combinations of colors of the vertices after the operation.
Constraints
* 2 ≤ N ≤ 2×10^5
* 1 ≤ a_i, b_i ≤ N
* The given graph is a tree.
* |s| = N
* s consists of `0` and `1`.
* s contains at least one occurrence of `1`.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
s
Output
Print the number of the possible combinations of colors of the vertices after the operation.
Examples
Input
4
1 2
1 3
1 4
1100
Output
4
Input
5
1 2
1 3
1 4
4 5
11111
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
100011
Output
8
Submitted Solution:
```
def solve():
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = [int(x) for x in input().split()]
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
ds = dict()
parent = [-1] * n
dfs_order = [0]
for i in range(n):
a = dfs_order[i]
for b in g[a]:
if b == parent[a]:
continue
dfs_order.append(b)
parent[b] = a
vd = [-1] * n
for a in reversed(dfs_order):
vd[a] = 0
for b in g[a]:
if b == parent[a]:
continue
ds[(a, b)] = vd[b]
vd[a] = max(vd[a], vd[b])
vd[a] = vd[a] + 1
ans = 0
d_parent = [0] * n
for a in dfs_order:
cd = [(d_parent[a], parent[a])]
for b in g[a]:
if b == parent[a]:
continue
cd.append((ds[(a, b)], b))
cd.sort()
cd.reverse()
cur = (cd[1][0] + 1) if (len(cd) > 1) else 1
cur = min(cur, cd[0][0] - 1)
ans += cur + 1
for b in g[a]:
if b == parent[a]:
continue
x = cd[0][0]
if cd[0][1] == b:
x = cd[1][0]
d_parent[b] = x + 1
print(ans + 1)
if __name__ == '__main__':
# t = int(input())
t=1
for _ in range(t):
solve()
``` | instruction | 0 | 99,341 | 13 | 198,682 |
No | output | 1 | 99,341 | 13 | 198,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i. The lengths of all the edges are 1.
Snuke likes some of the vertices. The information on his favorite vertices are given to you as a string s of length N. For each 1 ≤ i ≤ N, s_i is `1` if Snuke likes vertex i, and `0` if he does not like vertex i.
Initially, all the vertices are white. Snuke will perform the following operation exactly once:
* Select a vertex v that he likes, and a non-negative integer d. Then, paint all the vertices black whose distances from v are at most d.
Find the number of the possible combinations of colors of the vertices after the operation.
Constraints
* 2 ≤ N ≤ 2×10^5
* 1 ≤ a_i, b_i ≤ N
* The given graph is a tree.
* |s| = N
* s consists of `0` and `1`.
* s contains at least one occurrence of `1`.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
s
Output
Print the number of the possible combinations of colors of the vertices after the operation.
Examples
Input
4
1 2
1 3
1 4
1100
Output
4
Input
5
1 2
1 3
1 4
4 5
11111
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
100011
Output
8
Submitted Solution:
```
def solve():
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = [int(x) for x in input().split()]
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
ds = dict()
def dfs1(g, a, fr):
res = 0
for b in g[a]:
if b == fr:
continue
x = dfs1(g, b, a)
ds[(a, b)] = x
res = max(res, x)
return res + 1
dfs1(g, 0, -1)
# print(ds)
ans = 0
def dfs2(g, a, fr, d_fr):
nonlocal ans
# print(a, fr, d_fr)
cd = [(d_fr, fr)]
for b in g[a]:
if b == fr:
continue
cd.append((ds[(a, b)], b))
cd.sort()
cd.reverse()
# print(cd)
cur = (cd[1][0] + 1) if (len(cd) > 1) else 1
cur = min(cur, cd[0][0] - 1)
# print(cur)
ans += cur + 1
for b in g[a]:
if b == fr:
continue
x = cd[0][0]
if cd[0][1] == b:
x = cd[1][0]
dfs2(g, b, a, x + 1)
dfs2(g, 0, -1, 0)
print(ans + 1)
if __name__ == '__main__':
# t = int(input())
t = 1
for _ in range(t):
solve()
``` | instruction | 0 | 99,342 | 13 | 198,684 |
No | output | 1 | 99,342 | 13 | 198,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices. The vertices are numbered 1 through N. For each 1 ≤ i ≤ N - 1, the i-th edge connects vertices a_i and b_i. The lengths of all the edges are 1.
Snuke likes some of the vertices. The information on his favorite vertices are given to you as a string s of length N. For each 1 ≤ i ≤ N, s_i is `1` if Snuke likes vertex i, and `0` if he does not like vertex i.
Initially, all the vertices are white. Snuke will perform the following operation exactly once:
* Select a vertex v that he likes, and a non-negative integer d. Then, paint all the vertices black whose distances from v are at most d.
Find the number of the possible combinations of colors of the vertices after the operation.
Constraints
* 2 ≤ N ≤ 2×10^5
* 1 ≤ a_i, b_i ≤ N
* The given graph is a tree.
* |s| = N
* s consists of `0` and `1`.
* s contains at least one occurrence of `1`.
Input
The input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N - 1} b_{N - 1}
s
Output
Print the number of the possible combinations of colors of the vertices after the operation.
Examples
Input
4
1 2
1 3
1 4
1100
Output
4
Input
5
1 2
1 3
1 4
4 5
11111
Output
11
Input
6
1 2
1 3
1 4
2 5
2 6
100011
Output
8
Submitted Solution:
```
def solve():
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = [int(x) for x in input().split()]
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
ds = dict()
def dfs1(g, a, fr):
res = 0
for b in g[a]:
if b == fr:
continue
x = dfs1(g, b, a)
ds[(a, b)] = x
res = max(res, x)
return res + 1
dfs1(g, 0, -1)
# print(ds)
ans = 0
def dfs2(g, a, fr, d_fr):
nonlocal ans
# print(a, fr, d_fr)
cd = [(d_fr, fr)]
for b in g[a]:
if b == fr:
continue
cd.append((ds[(a, b)], b))
cd.sort()
cd.reverse()
# print(cd)
cur = (cd[1][0] + 1) if (len(cd) > 1) else 1
cur = min(cur, cd[0][0] - 1)
# print(cur)
ans += cur + 1
for b in g[a]:
if b == fr:
continue
x = cd[0][0]
if cd[0][1] == b:
x = cd[1][0]
dfs2(g, b, a, x + 1)
dfs2(g, 0, -1, 0)
print(ans + 1)
if __name__ == '__main__':
t = int(input())
for _ in range(t):
solve()
``` | instruction | 0 | 99,343 | 13 | 198,686 |
No | output | 1 | 99,343 | 13 | 198,687 |
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 with N vertices and M edges. Here, N-1≤M≤N holds and the graph is connected. There are no self-loops or multiple edges in this graph.
The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices a_i and b_i.
The color of each vertex can be either white or black. Initially, all the vertices are white. Snuke is trying to turn all the vertices black by performing the following operation some number of times:
* Select a pair of adjacent vertices with the same color, and invert the colors of those vertices. That is, if the vertices are both white, then turn them black, and vice versa.
Determine if it is possible to turn all the vertices black. If the answer is positive, find the minimum number of times the operation needs to be performed in order to achieve the objective.
Constraints
* 2≤N≤10^5
* N-1≤M≤N
* 1≤a_i,b_i≤N
* There are no self-loops or multiple edges in the given graph.
* The given graph is connected.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1
a_2 b_2
:
a_M b_M
Output
If it is possible to turn all the vertices black, print the minimum number of times the operation needs to be performed in order to achieve the objective. Otherwise, print `-1` instead.
Examples
Input
6 5
1 2
1 3
1 4
2 5
2 6
Output
5
Input
3 2
1 2
2 3
Output
-1
Input
4 4
1 2
2 3
3 4
4 1
Output
2
Input
6 6
1 2
2 3
3 1
1 4
1 5
1 6
Output
7
Submitted Solution:
```
print(-1)
``` | instruction | 0 | 99,344 | 13 | 198,688 |
No | output | 1 | 99,344 | 13 | 198,689 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1 | instruction | 0 | 99,428 | 13 | 198,856 |
"Correct Solution:
```
from collections import defaultdict
# 頂点がn個, 辺がw個の場合
n, w = map(int, input().split())
INF = 1 << 60
graph = defaultdict(lambda: INF)
for _ in range(w):
a, b, c = map(int, input().split())
graph[(a, b)] = c
# -1でdpテーブルを初期化。bitで集合を管理するので1<<n(状態数) * n(curr)
dp = [[-1] * n for _ in range(1 << n)]
# 既に訪れた集合がs, curr=vの時に0に戻る最短経路を計算
def rec(s, v):
# 既に計算されている場合はそのまま返す(メモ化再帰)
if dp[s][v] >= 0:
return dp[s][v]
# 全ての頂点を訪問済みで、かつcurr=0の場合は0を返す
if s == (1 << n) - 1 and v == 0:
return 0
# INFで初期化
res = INF
# sが現在の状態なので、1つずつ右シフトで読んでいく。未訪問(=0)の場合に処理
# 最初は全て未訪問
for u in range(n):
if not (s >> u & 1):
# 未訪問を1つずつ潰していくイメージ。uまで訪問していて、curr=uの場合を計算
# 1回計算された結果はメモ化再帰で再利用
res = min(res, rec(s | (1 << u), u) + graph[(v, u)])
dp[s][v] = res
return dp[s][v]
ans = rec(0, 0)
print(-1 if ans == INF else ans)
``` | output | 1 | 99,428 | 13 | 198,857 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1 | instruction | 0 | 99,429 | 13 | 198,858 |
"Correct Solution:
```
def TS(G,v,e):
INF = 16000
DP = [[INF for _ in range(v)] for _ in range(2**v)]
#DP[i][j]:訪問済みエリアのリストがiでjにいるような最短距離
DP[0][0] = 0
# どれも訪問してない状態は00...0(長さv)として訪問済みを表現
for i in range(2**v):
for j in range(v):
for k in range(v):
if i ^ 2**k < i and j != k \
and DP[i ^ 2**k][k] + G[k][j] < DP[i][j]:
DP[i][j] = DP[i ^ 2**k][k] + G[k][j]
if DP[2**v-1][0] != INF:
return DP[2**v-1][0]
else:
return -1
def main():
v,e = map(int,input().split())
INF = 16000
G = [[INF for _ in range(v)] for _ in range(v)]
for i in range(e):
s,t,d = map(int,input().split())
G[s][t] = d
print(TS(G,v,e))
if __name__ == "__main__":
main()
``` | output | 1 | 99,429 | 13 | 198,859 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1 | instruction | 0 | 99,430 | 13 | 198,860 |
"Correct Solution:
```
# https://www.slideshare.net/hcpc_hokudai/advanced-dp-2016 動的計画法の問題の解説がされている 神
# これが比較的わかりやすいかも https://algo-logic.info/bit-dp/
'''
定式化(本は"集める"DPで定義してるが、わかりやすさのため"配る"DPで定式化)
ノーテーション
S ... 頂点集合
| ... 和集合演算子
dp[S][v] ... 重みの総和の最小。頂点0から頂点集合Sを経由してvに到達する。
更新則
dp[S|{v}] = min{dp[S][u]+d(u,v) | u∈S} ただしv∉S
初期条件
dp[∅][0] = 0 #Vはあらゆる集合
dp[V][u] = INF #ほかはINFで初期化しておく
答え
dp[すべての要素][0] ... 0からスタートしてすべての要素を使って最後に0に戻るための最小コスト
'''
# verify https://onlinejudge.u-aizu.ac.jp/courses/library/7/DPL/all/DPL_2_A
INF = 2 ** 31
from itertools import product
def solve(n, graph):
'''nは頂点数、graphは隣接行列形式'''
max_S = 1 << n # n個のbitを用意するため
dp = [[INF] * n for _ in range(max_S)]
dp[0][0] = 0
for S in range(max_S):
for u, v in product(range(n), repeat=2):
if (S >> v) & 1 == 1: # vが訪問済みの場合は飛ばす
continue
dp[S | (1 << v)][v] = min(dp[S | (1 << v)][v],
dp[S][u] + graph[u][v])
print(dp[-1][0] if dp[-1][0] != INF else -1)
# # 入力例
# n = 5
# graph = [[INF, 3, INF, 4, INF],
# [INF, INF, 5, INF, INF],
# [4, INF, INF, 5, INF],
# [INF, INF, INF, 0, 3],
# [7, 6, INF, INF, INF]]
# solve(n, graph)
# verify用
n, e = map(int, input().split())
graph = [[INF] * n for _ in range(n)]
for _ in range(e):
s, t, d = map(int, input().split())
graph[s][t] = d
solve(n, graph)
``` | output | 1 | 99,430 | 13 | 198,861 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1 | instruction | 0 | 99,431 | 13 | 198,862 |
"Correct Solution:
```
SENTINEL = 15001
v, e = map(int, input().split())
links = [set() for _ in range(v)]
bests = [[SENTINEL] * v for _ in range(1 << v)]
for _ in range(e):
s, t, d = map(int, input().split())
links[s].add((t, d))
bests[0][0] = 0
for visited, best in enumerate(bests):
for last, cost in enumerate(best):
for t, d in links[last]:
bit = 1 << t
if visited & bit:
continue
new_best = bests[visited | bit]
new_best[t] = min(new_best[t], cost + d)
print(-1 if bests[-1][0] == 15001 else bests[-1][0])
``` | output | 1 | 99,431 | 13 | 198,863 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1 | instruction | 0 | 99,432 | 13 | 198,864 |
"Correct Solution:
```
def solve():
V, E = map(int, input().split())
edges = [[] for _ in [0]*V]
for _ in [0]*E:
s, t, d = map(int, input().split())
edges[s].append((t, d))
result = float("inf")
beam_width = 70
for i in range(V):
q = [(0, i, {i})]
for j in range(V-1):
_q = []
append = _q.append
for cost, v, visited in q[:beam_width+1]:
for dest, d_cost in edges[v]:
if dest not in visited:
append((cost+d_cost, dest, visited | {dest}))
q = sorted(_q)
for cost, v, visited in q[:beam_width+1]:
for dest, d_cost in edges[v]:
if dest == i:
if result > cost + d_cost:
result = cost + d_cost
break
print(result if result < float("inf") else -1)
if __name__ == "__main__":
solve()
``` | output | 1 | 99,432 | 13 | 198,865 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1 | instruction | 0 | 99,433 | 13 | 198,866 |
"Correct Solution:
```
from collections import defaultdict
v, e = map(int, input().split())
links = [set() for _ in range(v)]
bests = [None] * (1 << v)
for _ in range(e):
s, t, d = map(int, input().split())
links[s].add((t, d))
bests[0] = {0: 0}
for visited, best in enumerate(bests):
if best is None:
continue
for last, cost in best.items():
for t, d in links[last]:
new_visited = visited | (1 << t)
if visited == new_visited:
continue
new_best = bests[new_visited]
if new_best is None:
bests[new_visited] = defaultdict(lambda: 15001, [(t, cost + d)])
else:
new_best[t] = min(new_best[t], cost + d)
result = bests[-1]
print(-1 if result is None else -1 if result[0] == 15001 else result[0])
``` | output | 1 | 99,433 | 13 | 198,867 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1 | instruction | 0 | 99,434 | 13 | 198,868 |
"Correct Solution:
```
def main():
V, E = map(int, input().split())
INF = float("inf")
G = [[-1 for _ in range(V)] for _ in range(V)]
for i in range(E):
s,t,d = map(int, input().split())
G[s][t] = d
# dp[bit][i] bitの1が立っている場所を訪問済みで、現在iにいる
dp = [[INF for _ in range(V)] for _ in range(1 << V)]
# 各所一回だけ訪問して一周できるなら、どこから始めても同じなので0のみ初期化
dp[0][0] = 0
for bit in range(1 << V):
for curr in range(V):
for nxt in range(V):
# 現在地と次の場所が同じなら飛ばす
if curr == nxt:
continue
# 次行くところが既に訪問済みなら飛ばす
if bit & (1 << nxt):
continue
# 現在値から次の目的地にいけなければ飛ばす
if G[curr][nxt] == -1:
continue
dp[bit | (1 << nxt)][nxt] = min(dp[bit | (1 << nxt)][nxt], dp[bit][curr] + G[curr][nxt])
ans = dp[-1][0]
print(ans if ans != INF else -1)
if __name__ == "__main__":
main()
``` | output | 1 | 99,434 | 13 | 198,869 |
Provide a correct Python 3 solution for this coding contest problem.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1 | instruction | 0 | 99,435 | 13 | 198,870 |
"Correct Solution:
```
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))
v,e = mi()
sb = [[]for i in range(e)]
ub = [[]for i in range(e)]
w = [[float('inf')] * v for i in range(v)]
dp = [[-1] * v for i in range(2**v +1) ]
for i in range(e):
s,t,d = mi()
sb[s].append(t)
w[s][t] = d
def rec(s,p,dp):
if dp[s][p] >0:
return dp[s][p]
if s == (1<<v)-1 and p == 0:
dp[s][v-1] = 0
return 0
res = float('inf')
for i in sb[p]:
if (s >> i&1) == 0:
a = rec(s|(1<<i), i,dp) + w[p][i]
res = min(res, a)
dp[s][p] = res
return res
if v >= 3 and e >= 3:
ans = rec(0,0,dp)
else:
ans = -1
if ans == float('inf'):
print(-1)
else:
print(ans)
``` | output | 1 | 99,435 | 13 | 198,871 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1
Submitted Solution:
```
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7
def resolve():
n, m = map(int, input().split())
graph = [[f_inf] * n for _ in range(n)]
for i in range(n):
graph[i][i] = 0
for _ in range(m):
s, t, d = map(int, input().split())
graph[s][t] = d
dp = [[f_inf] * n for _ in range(1 << n)]
dp[0][0] = 0
for S in range(1 << n):
for v in range(n):
for u in range(n):
if ((1 << v) & S) == 0:
if v != u:
idx = S | (1 << v)
dp[idx][v] = min(dp[idx][v], dp[S][u] + graph[u][v])
print(dp[-1][0] if dp[-1][0] != f_inf else -1)
if __name__ == '__main__':
resolve()
``` | instruction | 0 | 99,436 | 13 | 198,872 |
Yes | output | 1 | 99,436 | 13 | 198,873 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1
Submitted Solution:
```
import sys
V, E = map(int, sys.stdin.readline().strip().split())
# edges[i][j]:i→jへの距離
edges = [[float("inf")]*V for i in range(V)]
for i in range(E):
s, t, d = map(int, sys.stdin.readline().strip().split())
edges[s][t] = d
dp = [[-1] * V for i in range(1<<V)]
# 訪れた集合がs、今いる点がvの時に、v=0に戻る最短経路
def rec(bit, v):
if dp[bit][v] >= 0:
return dp[bit][v]
if bit == (1<<V)-1 and v == 0:
#全ての頂点を訪れた(bit = 11...11 and v = 0)
dp[bit][v] = 0
return 0
res = float("inf")
for u in range(V):
if not (bit>>u & 1):
#uに訪れていない時(uの箇所が0の時),次はuとすると
res = min(res,rec(bit|(1<<u), u) + edges[v][u])
dp[bit][v] = res
return res
res = rec(0, 0)
print(-1 if res == float("inf") else res)
``` | instruction | 0 | 99,437 | 13 | 198,874 |
Yes | output | 1 | 99,437 | 13 | 198,875 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1
Submitted Solution:
```
n,w = map(int,input().split())
#d[i][j]:i→jへの距離
d = [[float("inf")]*n for i in range(n)]
for i in range(w):
x,y,z = map(int,input().split())
d[x][y] = z
dp = [[-1] * n for i in range(1<<n)]
#訪れた集合がs、今いる点がvの時0に戻る最短経路
def rec(s,v,dp):
if dp[s][v] >= 0:
return dp[s][v]
if s == (1<<n)-1 and v == 0:
#全ての頂点を訪れた(s = 11...11 and v = 0)
dp[s][v] = 0
return 0
res = float("inf")
for u in range(n):
if (s>>u&1) == 0:
#uに訪れていない時(uの箇所が0の時),次はuとすると
res = min(res,rec(s|(1<<u),u,dp)+d[v][u])
dp[s][v] = res
return res
if rec(0,0,dp) != float("inf"):
ans = rec(0,0,dp)
else:
ans = -1
print(ans)
``` | instruction | 0 | 99,438 | 13 | 198,876 |
Yes | output | 1 | 99,438 | 13 | 198,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1
Submitted Solution:
```
# DPL_2_A - 巡回セールスマン問題
import sys
sys.setrecursionlimit(10 ** 8)
V, E = map(int, sys.stdin.readline().strip().split())
d = [[float('inf')] * V for _ in range(V)]
for _ in range(E):
s, t, _d = map(int, sys.stdin.readline().strip().split())
d[s][t] = _d
# dp 初期化 -----------------
dp = [[float('inf')] * V for _ in range(1 << V)] # 1 << V は 2 ** V に同じ
dp[0][0] = 0 # 頂点 0 からスタートするとする
def res(s, v):
# s: すでに訪問した街の集合, v: 今いる街の集合, dp: 動的計画法のテーブル
# 0 から出発して s, v を満たすコストを返す関数
if dp[s][v] == -1: # 到達不可能ならば
return float('inf')
elif dp[s][v] != float('inf'):
return dp[s][v]
elif (s >> v) & 1 == 0: # 集合 s に頂点 v が含まれていないならば
dp[s][v] = -1
return float('inf')
ans = float('inf')
for u in range(V):
# if (s >> u) & 1 == 1:
# print(f's: {format(s ^ (1 << v), "b")}, u: {u}')
# print(f'{d[u][v]}')
ans = min(ans, res(s ^ (1 << v), u) + d[u][v])
if ans == float('inf'): # 到達不可能ならば
dp[s][v] = -1
else:
dp[s][v] = ans
return ans
res((1 << V) - 1, 0)
# for i in range(len(dp)):
# print(dp[i])
print(dp[-1][0])
``` | instruction | 0 | 99,439 | 13 | 198,878 |
Yes | output | 1 | 99,439 | 13 | 198,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1
Submitted Solution:
```
from sys import stdin
from collections import defaultdict
from math import isinf
readline = stdin.readline
min_cost = float('inf')
def main():
v, e = map(int, readline().split())
g = [[float('inf')] * v for _ in range(v)]
for _ in range(e):
s, t, d = map(int, readline().split())
g[s][t] = d
dfs(g, 0, 0, set(range(1, v)))
global min_cost
print(-1 if isinf(min_cost) else min_cost)
def dfs(g, cost, last, vs):
global min_cost
if min_cost < cost:
return
if vs:
for v in vs:
dfs(g, cost + g[last][v], v, vs - {v})
elif min_cost > cost + g[last][0]:
min_cost = cost + g[last][0]
main()
``` | instruction | 0 | 99,440 | 13 | 198,880 |
No | output | 1 | 99,440 | 13 | 198,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1
Submitted Solution:
```
def solve():
from heapq import heappop, heappush
V, E = map(int, input().split())
edges = [[] for _ in [0]*V]
for _ in [0]*E:
s, t, d = map(int, input().split())
edges[s].append((t, d))
result = float("inf")
for i in range(V):
q = [(0, i, {i})]
while q:
cost, v, visited = heappop(q)
if len(visited) < V:
for dest, d_cost in edges[v]:
if dest not in visited:
heappush(q, (cost+d_cost, dest, visited | {dest}))
elif len(visited) == V:
for dest, d_cost in edges[v]:
if dest == i:
heappush(q, (cost+d_cost, i, visited | {-1}))
else:
if result > cost:
result = cost
break
print(result if result < float("inf") else -1)
if __name__ == "__main__":
solve()
``` | instruction | 0 | 99,441 | 13 | 198,882 |
No | output | 1 | 99,441 | 13 | 198,883 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1
Submitted Solution:
```
# Acceptance of input
import sys
file_input = sys.stdin
V, E = map(int, file_input.readline().split())
D = [[] for i in range(V)]
for line in file_input:
s, t, d = map(int, line.split())
D[s].append((t, d))
max_d = 15001
# Full search with bit mask
def tsp(v, b):
if b == (1 << V) - 1:
if D[v]:
t, d = min(D[v])
if t == 0:
return d
else:
return max_d
else:
return max_d
res = max_d
for t, d in D[v]:
if b & (1 << t):
continue
res = min(res, d + tsp(t, b | (1 << t)))
return res
# Output
ans = tsp(0, 1)
if ans == max_d:
print(-1)
else:
print(ans)
``` | instruction | 0 | 99,442 | 13 | 198,884 |
No | output | 1 | 99,442 | 13 | 198,885 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).
Output
Print the shortest distance in a line. If there is no solution, print -1.
Examples
Input
4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4
Output
16
Input
3 3
0 1 1
1 2 1
0 2 1
Output
-1
Submitted Solution:
```
from sys import stdin
from collections import defaultdict
from math import isinf
readline = stdin.readline
from collections import deque
def main():
v, e = map(int, readline().split())
g = [[float('inf')] * v for _ in range(v)]
for _ in range(e):
s, t, d = map(int, readline().split())
g[s][t] = d
min_cost = float('inf')
que = deque([(0, 0, set(range(1, v)))])
while que:
cost, last, vs = que.pop()
if min_cost <= cost:continue
if vs:que.extend((cost + g[last][v], v, vs - {v}) for v in vs)
elif min_cost > cost + g[last][0]:min_cost = cost + g[last][0]
print(-1 if isinf(min_cost) else min_cost)
main()
``` | instruction | 0 | 99,443 | 13 | 198,886 |
No | output | 1 | 99,443 | 13 | 198,887 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You're given a tree with n vertices. The color of the i-th vertex is h_{i}.
The value of the tree is defined as ∑_{h_{i} = h_{j}, 1 ≤ i < j ≤ n}{dis(i,j)}, where dis(i,j) is the number of edges on the shortest path between i and j.
The color of each vertex is lost, you only remember that h_{i} can be any integer from [l_{i}, r_{i}](inclusive). You want to calculate the sum of values of all trees meeting these conditions modulo 10^9 + 7 (the set of edges is fixed, but each color is unknown, so there are ∏_{i = 1}^{n} (r_{i} - l_{i} + 1) different trees).
Input
The first line contains one integer n (2 ≤ n ≤ 10^5) — the number of vertices.
Then n lines follow, each line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^5) denoting the range of possible colors of vertex i.
Then n - 1 lines follow, each containing two integers u and v (1 ≤ u, v ≤ n, u ≠ v) denoting an edge of the tree. It is guaranteed that these edges form a tree.
Output
Print one integer — the sum of values of all possible trees, taken modulo 10^9 + 7.
Example
Input
4
1 1
1 2
1 1
1 2
1 2
1 3
3 4
Output
22
Note
In the first example there are four different ways to color the tree (so, there are four different trees):
* a tree with vertices colored as follows: { 1,1,1,1 }. The value of this tree is dis(1,2)+dis(1,3)+dis(1,4)+dis(2,3)+dis(2,4)+dis(3,4) = 10;
* a tree with vertices colored as follows: { 1,2,1,1 }. The value of this tree is dis(1,3)+dis(1,4)+dis(3,4)=4;
* a tree with vertices colored as follows: { 1,1,1,2 }. The value of this tree is dis(1,2)+dis(1,3)+dis(2,3)=4;
* a tree with vertices colored as follows: { 1,2,1,2 }. The value of this tree is dis(1,3)+dis(2,4)=4.
Overall the sum of all values is 10+4+4+4=22.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
NN = 18
BIT1=[0]*(2**NN+1)
BIT2=[0]*(2**NN+1)
def addrange(l0, r0, x=1):
l, r = l0, r0
while l <= 2**NN:
BIT1[l] -= x * l0
BIT2[l] -= x
l += l & (-l)
while r <= 2**NN:
BIT1[r] += x * r0
BIT2[r] += x
r += r & (-r)
def rangesum(l, r):
l0, r0, a, b, c = l, r, 0, 0, 0
while l != 0:
a -= BIT1[l]
b += BIT2[l]
l -= l&(-l)
while r != 0:
a += BIT1[r]
c += BIT2[r]
r -= r&(-r)
return a + b * l0 - c * r0
def disp():
tmp = []
for i in range(30):
tmp.append(rangesum(i, i+1))
print(tmp)
N = int(input())
Y = [[] for _ in range(N)]
MO = 10**9+7
s = 1
for i in range(N):
a, b = map(int, input().split())
Y[i] = [a, b+1, pow(b-a+1, MO-2, MO)]
s *= b-a+1
s %= MO
X = [[] for _ in range(N)]
for i in range(N-1):
a, b = map(int, input().split())
X[a-1].append(b-1)
X[b-1].append(a-1)
# print("X =", X)
ans = 0
def EulerTour(n, X):
global ans
P = [-1] * n
Q = [-1, 0]
ct = -1
ET = []
ET1 = [0] * n
ET2 = [0] * n
DE = [0] * n
de = -1
while Q:
i = Q.pop()
if i < 0:
# �� �߂�������𑫂��ꍇ�͂�����g��
# ct += 1
# �� �߂��ET�ɓ����ꍇ�͂�����g��
# ET.append(P[~i])
# print("END i =", ~i)
a, b, k = Y[i]
# addrange(a, b, -k)
ET2[~i] = ct
de -= 1
continue
if i >= 0:
# print("i =", i)
a, b, k = Y[i]
ans += rangesum(a, b)
# print("ans =", ans * s % MO)
addrange(a, b, k)
ET.append(i)
ct += 1
if ET1[i] == 0: ET1[i] = ct
de += 1
DE[i] = de
for a in X[i][::-1]:
if a != P[i]:
P[a] = i
for k in range(len(X[a])):
if X[a][k] == i:
del X[a][k]
break
Q.append(~a)
Q.append(a)
return (ET, ET1, ET2)
ET, ET1, ET2 = EulerTour(N, X)
print(ans * s % MO)
``` | instruction | 0 | 99,575 | 13 | 199,150 |
No | output | 1 | 99,575 | 13 | 199,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that
* The root is number 1
* Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
Input
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively.
The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, <image>), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
Output
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
Examples
Input
3 1
3 4 6 0
Output
7
Input
4 3
4 10 14 1
3 6 6 0
2 3 3 1
Output
14
Input
4 2
3 4 6 1
4 12 15 1
Output
Data not sufficient!
Input
4 2
3 4 5 1
2 3 3 1
Output
Game cheated!
Note
Node u is an ancestor of node v if and only if
* u is the same node as v,
* u is the parent of node v,
* or u is an ancestor of the parent of node v.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
<image> | instruction | 0 | 99,822 | 13 | 199,644 |
Tags: data structures, implementation, sortings
Correct Solution:
```
import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
h, q = mints()
a = [None]*(q*2+1)
L = 1<<(h-1)
R = (1<<h)-1
j = 0
for i in range(q):
hh,l,r,ans = mints()
l = (l<<(h-hh))
r = ((r+1)<<(h-hh))-1
if ans == 1:
L = max(L, l)
R = min(R, r)
else:
a[j] = (l,-1)
a[j+1] = (r+1,1)
j+=2
if L > R:
print("Game cheated!")
exit(0)
a[j]=((1<<h),-1)
a = a[:j+1]
a.sort()
#print(a)
#print(L,R)
cnt = 0
t = 1<<(h-1)
ans = None
for i in a:
if i[0] != t:
kk = min(R+1,i[0])-max(t,L)
#print(i,t,cnt,kk)
if cnt == 0 and kk >= 1:
if ans != None or kk > 1:
print("Data not sufficient!")
exit(0)
ans = max(t,L)
#print(ans)
t = i[0]
cnt -= i[1]
if ans == None:
print("Game cheated!")
else:
print(ans)
``` | output | 1 | 99,822 | 13 | 199,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that
* The root is number 1
* Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
Input
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively.
The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, <image>), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
Output
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
Examples
Input
3 1
3 4 6 0
Output
7
Input
4 3
4 10 14 1
3 6 6 0
2 3 3 1
Output
14
Input
4 2
3 4 6 1
4 12 15 1
Output
Data not sufficient!
Input
4 2
3 4 5 1
2 3 3 1
Output
Game cheated!
Note
Node u is an ancestor of node v if and only if
* u is the same node as v,
* u is the parent of node v,
* or u is an ancestor of the parent of node v.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
<image> | instruction | 0 | 99,823 | 13 | 199,646 |
Tags: data structures, implementation, sortings
Correct Solution:
```
from collections import *
h,q=map(int,input().split())
d=defaultdict(lambda:0)
d[2**h]=0
d[2**(h-1)]=0
for _ in range(q):
i,l,r,a=map(int,input().split())
l,r=l*2**(h-i),(r+1)*2**(h-i)
if a:d[1]+=1;d[l]-=1;d[r]+=1
else:d[l]+=1;d[r]-=1
s=0
l=0
D=sorted(d.items())
for (a,x),(b,_) in zip(D,D[1:]):
s+=x
if s==0:q=a;l+=b-a
print(("Game cheated!",q,"Data not sufficient!")[min(l,2)])
``` | output | 1 | 99,823 | 13 | 199,647 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that
* The root is number 1
* Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
Input
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively.
The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, <image>), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
Output
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
Examples
Input
3 1
3 4 6 0
Output
7
Input
4 3
4 10 14 1
3 6 6 0
2 3 3 1
Output
14
Input
4 2
3 4 6 1
4 12 15 1
Output
Data not sufficient!
Input
4 2
3 4 5 1
2 3 3 1
Output
Game cheated!
Note
Node u is an ancestor of node v if and only if
* u is the same node as v,
* u is the parent of node v,
* or u is an ancestor of the parent of node v.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
<image> | instruction | 0 | 99,824 | 13 | 199,648 |
Tags: data structures, implementation, sortings
Correct Solution:
```
h,q=map(int,input().split())
d=[(2**h,0),(2**(h-1),0)]
for _ in range(q):
i,l,r,a=map(int,input().split())
l,r=l*2**(h-i),(r+1)*2**(h-i)
d.extend([[(l,1),(r,-1)],[(0,1),(l,-1),(r,1)]][a])
s=0
l=0
d=sorted(d)
for (a,x),(b,_) in zip(d,d[1:]):
s+=x
if a!=b and s==0:q=a;l+=b-a
print(("Game cheated!",q,"Data not sufficient!")[min(l,2)])
``` | output | 1 | 99,824 | 13 | 199,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that
* The root is number 1
* Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
Input
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively.
The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, <image>), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
Output
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
Examples
Input
3 1
3 4 6 0
Output
7
Input
4 3
4 10 14 1
3 6 6 0
2 3 3 1
Output
14
Input
4 2
3 4 6 1
4 12 15 1
Output
Data not sufficient!
Input
4 2
3 4 5 1
2 3 3 1
Output
Game cheated!
Note
Node u is an ancestor of node v if and only if
* u is the same node as v,
* u is the parent of node v,
* or u is an ancestor of the parent of node v.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
<image>
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def ReadIn():
height, n = [int(x) for x in input().split()]
queries = [tuple(int(x) for x in input().split())
for q in range(n)]
return height, queries
def MoveToLeaves(height, queries):
leaves = []
for level, left, right, yn in queries:
shift = height - level
leaves.append(tuple([
left << shift,
(right << shift) | ((1 << shift) - 1),
yn]))
return leaves
def RangeIntersection(ranges):
# print(ranges)
ret = ranges[0][:2]
for r in ranges:
ret = (max(r[0], ret[0]), min(r[1], ret[1]))
return ret
def RangeUnion(ranges):
if len(ranges) == 0: return []
ranges.sort(key=lambda r: r[0])
ret = []
now = ranges[0][:2]
for r in ranges:
if r[0] > now[1] + 1:
ret.append(now)
now = r
else:
now = (now[0], max(now[1], r[1]))
ret.append(now)
return ret
def Solve(height, queries):
# print(height, queries)
queries = MoveToLeaves(height, queries)
# print(queries)
range_in = RangeIntersection(
[(1 << (height - 1), (1 << height) - 1, 1)] +
list(filter(lambda q: q[2] == 1, queries)))
# print(range_in)
ranges_out = RangeUnion(
list(filter(lambda q: q[2] == 0, queries)))
if height == 16: print(ranges_out)
if range_in[0] > range_in[1]:
print('Game cheated!')
return
for r in ranges_out:
if r[0] <= range_in[0] and range_in[1] <= r[1]:
print('Game cheated!')
return
if range_in[0] < r[0] and r[1] < range_in[1]:
print('Data not sufficient!')
return
for r in ranges_out:
if r[0] == range_in[0] + 1:
print(range_in[0])
return
if r[1] == range_in[1] - 1:
print(range_in[1])
return
for l, r in zip(ranges_out[:-1], ranges_out[1:]):
if r[0] - l[1] == 2: continue
pos = l[1] + 1
if range_in[0] <= pos <= range_in[1]:
print(pos)
return
print('Data not sufficient!')
if __name__ == '__main__':
height, queries = ReadIn()
Solve(height, queries)
``` | instruction | 0 | 99,825 | 13 | 199,650 |
No | output | 1 | 99,825 | 13 | 199,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that
* The root is number 1
* Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
Input
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively.
The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, <image>), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
Output
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
Examples
Input
3 1
3 4 6 0
Output
7
Input
4 3
4 10 14 1
3 6 6 0
2 3 3 1
Output
14
Input
4 2
3 4 6 1
4 12 15 1
Output
Data not sufficient!
Input
4 2
3 4 5 1
2 3 3 1
Output
Game cheated!
Note
Node u is an ancestor of node v if and only if
* u is the same node as v,
* u is the parent of node v,
* or u is an ancestor of the parent of node v.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
<image>
Submitted Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
"""
created by shhuan at 2017/10/6 09:03
"""
H, Q = map(int, input().split())
M1 = []
M2 = []
for i in range(Q):
i, l, r, a = map(int, input().split())
left = l * 2 ** (H - i)
right = (r + 1) * 2 ** (H - i) - 1
if a:
M1.append((abs(left-right), left, right))
else:
M2.append((abs(left-right), left, right))
# M1.sort()
# M2.sort(reverse=True)
L, R = 2**(H-1), 2**H-1
for d, left, right in M1:
L = max(L, left)
R = min(R, right)
if L > R:
print("Game cheated!")
exit(0)
LR = {(L, R)}
for d, left, right in M2:
# merge [L, R] and [1, left-1]
# merge [L, R] and [right+1, 2**H-1]
nextlr = set()
for L, R in LR:
if R < left or L > right:
nextlr.add((L, R))
elif L <= left-1 <= R:
nextlr.add((L, left-1))
elif L <= right+1 <= R:
nextlr.add((right+1, R))
LR = nextlr
LR = list(LR)
if len(LR) == 0:
print("Game cheated!")
elif len(LR) == 1 and LR[0][0] == LR[0][1]:
print(LR[0][0])
else:
print("Data not sufficient!")
``` | instruction | 0 | 99,826 | 13 | 199,652 |
No | output | 1 | 99,826 | 13 | 199,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that
* The root is number 1
* Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
Input
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively.
The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, <image>), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
Output
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
Examples
Input
3 1
3 4 6 0
Output
7
Input
4 3
4 10 14 1
3 6 6 0
2 3 3 1
Output
14
Input
4 2
3 4 6 1
4 12 15 1
Output
Data not sufficient!
Input
4 2
3 4 5 1
2 3 3 1
Output
Game cheated!
Note
Node u is an ancestor of node v if and only if
* u is the same node as v,
* u is the parent of node v,
* or u is an ancestor of the parent of node v.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
<image>
Submitted Solution:
```
from collections import *
h,q=map(int,input().split())
d=defaultdict(lambda:0)
d[2**h]=0
for _ in range(q):
i,l,r,a=map(int,input().split())
l,r=l*2**(h-i),(r+1)*2**(h-i)
if a:d[1]+=1;d[l]-=1;d[r]+=1
else:d[l]+=1;d[r]-=1
s=0
l=0
D=sorted(d.items())
for (a,x),(b,_) in zip(D,D[1:]):
s+=x
if s==0:q=a;l+=b-a
print(("Game cheated!",q,"Data not sufficient!")[min(l,2)])
``` | instruction | 0 | 99,827 | 13 | 199,654 |
No | output | 1 | 99,827 | 13 | 199,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that
* The root is number 1
* Each internal node i (i ≤ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
Input
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 105), the height of the tree and the number of questions respectively.
The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2i - 1 ≤ L ≤ R ≤ 2i - 1, <image>), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
Output
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
Examples
Input
3 1
3 4 6 0
Output
7
Input
4 3
4 10 14 1
3 6 6 0
2 3 3 1
Output
14
Input
4 2
3 4 6 1
4 12 15 1
Output
Data not sufficient!
Input
4 2
3 4 5 1
2 3 3 1
Output
Game cheated!
Note
Node u is an ancestor of node v if and only if
* u is the same node as v,
* u is the parent of node v,
* or u is an ancestor of the parent of node v.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
<image>
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def ReadIn():
height, n = [int(x) for x in input().split()]
queries = [tuple(int(x) for x in input().split())
for q in range(n)]
return height, queries
def MoveToLeaves(height, queries):
leaves = []
for level, left, right, yn in queries:
shift = height - level
leaves.append(tuple([
left << shift,
(right << shift) | ((1 << shift) - 1),
yn]))
return leaves
def RangeIntersection(ranges):
# print(ranges)
ret = ranges[0][:2]
for r in ranges:
ret = (max(r[0], ret[0]), min(r[1], ret[1]))
return ret
def RangeUnion(ranges):
if len(ranges) == 0: return []
ranges.sort(key=lambda r: r[0])
ret = []
now = ranges[0][:2]
for r in ranges:
if r[0] > now[1] + 1:
ret.append(now)
now = r
else:
now = (now[0], max(now[1], r[1]))
ret.append(now)
return ret
def Solve(height, queries):
# print(height, queries)
queries = MoveToLeaves(height, queries)
# print(queries)
range_in = RangeIntersection(
[(1 << (height - 1), (1 << height) - 1, 1)] +
list(filter(lambda q: q[2] == 1, queries)))
# print(range_in)
ranges_out = RangeUnion(
list(filter(lambda q: q[2] == 0, queries)))
if range_in[0] > range_in[1]:
print('Game cheated!')
return
for r in ranges_out:
if r[0] <= range_in[0] and range_in[1] <= r[1]:
print('Game cheated!')
return
if range_in[0] < r[0] and r[1] < range_in[1]:
print('Data not sufficient!')
return
for r in ranges_out:
if r[0] == range_in[0] + 1:
print(range_in[0])
return
if r[1] == range_in[1] - 1:
print(range_in[1])
return
for l, r in zip(ranges_out[:-1], ranges_out[1:]):
if r[0] - l[1] == 2: continue
pos = l[1] + 1
if range_in[0] <= pos <= range_in[1]:
print(pos)
return
print('Data not sufficient!')
if __name__ == '__main__':
height, queries = ReadIn()
Solve(height, queries)
``` | instruction | 0 | 99,828 | 13 | 199,656 |
No | output | 1 | 99,828 | 13 | 199,657 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | instruction | 0 | 99,941 | 13 | 199,882 |
Tags: dfs and similar, graphs
Correct Solution:
```
# coding: utf-8
n, m, k = list(map(int, input().split()))
govs = list(map(int, input().split()))
graph = [[] for _ in range(n+1)]
for _ in range(m):
u, v = list(map(int, input().split()))
graph[u].append(v)
graph[v].append(u)
visited = [False] * (n+1)
components = []
has_gov = []
def dfs(node, i):
if visited[node]:
return
visited[node] = True
if node in govs:
has_gov[i] = True
components[i].append(node)
for neighbour in graph[node]:
dfs(neighbour, i)
i = -1
max_component_size = -1
biggest_component = 0
for node in range(1, n+1):
if visited[node]:
continue
i += 1
components.append([])
has_gov.append(False)
dfs(node, i)
if len(components[i]) > max_component_size and has_gov[i]:
max_component_size = len(components[i])
biggest_component = i
for i in range(len(components)):
if has_gov[i]:
continue
no_gov_component = components[i]
for j in range(len(no_gov_component)):
components[biggest_component].append(no_gov_component[j])
new_edges = 0
for i in range(len(components)):
if not has_gov[i]:
continue
component = components[i]
s = len(component)
edges = (s*(s-1)) // 2
removed_edges = 0
for j in component:
for k in component:
if j != k and k in graph[j]:
removed_edges += 1
removed_edges = removed_edges // 2
new_edges += (edges - removed_edges)
print(new_edges)
``` | output | 1 | 99,941 | 13 | 199,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | instruction | 0 | 99,942 | 13 | 199,884 |
Tags: dfs and similar, graphs
Correct Solution:
```
#inputs
n, m, ngovs = [int(x) for x in input().split()]
govs=[int(i)-1 for i in input().split()]
#build graph
graph=[list([]) for i in range(n)]
visited=[False for i in range(n)]
for i in range(m):
verts = tuple(int(x) -1 for x in input().split())
graph[verts[0]].append(verts[1])
graph[verts[1]].append(verts[0])
#DFS
res = 0
cur_max = 0
def dfs(node):
if not visited[node]:
visited[node]=1
seen[0]+=1
for i in graph[node]:
if not visited[i]:
dfs(i)
for i in govs:
seen=[0]
dfs(i)
res+=seen[0]*(seen[0]-1)//2
cur_max=max(cur_max,seen[0])
res-=cur_max*(cur_max-1)//2
for i in range(n):
if not visited[i]:
seen=[0]
dfs(i)
cur_max+=seen[0]
res= res - m+cur_max*(cur_max-1)//2
print(res)
``` | output | 1 | 99,942 | 13 | 199,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | instruction | 0 | 99,943 | 13 | 199,886 |
Tags: dfs and similar, graphs
Correct Solution:
```
V, E, K = map(int, input().split())
C = set(map(int, input().split()))
C = set(map(lambda x: x - 1, C))
g = [[] for i in range(V)]
for i in range(E):
u, v = map(int, input().split())
u, v = u - 1, v - 1
g[u].append(v)
g[v].append(u)
components = list()
visited = set()
def dfs(u, c):
visited.add(u)
components[c].add(u)
for v in g[u]:
if not (v in visited):
dfs(v, c)
c = 0
for i in range(V):
if i in visited:
continue
components.append(set())
dfs(i, c)
c += 1
countries = set()
mc = 0
mcl = 0
for comp in range(c):
if len(components[comp] & C):
countries.add(comp)
if len(components[comp]) > mcl:
mcl = len(components[comp])
mc = comp
for comp in range(c):
if not (comp in countries):
for t in components[comp]:
components[mc].add(t)
# components[mc] = components[mc] | components[comp]
components[comp] = set()
t = 0
for comp in range(c):
l = len(components[comp])
t += l * (l - 1) // 2
print(t - E)
``` | output | 1 | 99,943 | 13 | 199,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | instruction | 0 | 99,944 | 13 | 199,888 |
Tags: dfs and similar, graphs
Correct Solution:
```
def solve():
order = list
length = len
unique = set
nodes, edges, distinct = order(map(int, input().split(" ")))
govt = {x-1: 1 for x in order(map(int, input().split(" ")))}
connections = {}
# Add edges
for _ in range(edges):
x, y = order(map(int, input().split(" ")))
if x-1 not in connections:
connections[x-1] = [y-1]
else:
connections[x-1].append(y-1)
if y-1 not in connections:
connections[y-1] = [x-1]
else:
connections[y-1].append(x-1)
discovered = {}
cycles = {m: [] for m in ["G", "N"]}
for i in range(nodes):
is_govt = False if i not in govt else True
# Node is already been lookd at
if i in discovered:
continue
cycle = [i]
# Nodes with no edges to other nodes
if i not in connections:
discovered[i] = 1
if is_govt:
cycles["G"].append(cycle)
else:
cycles["N"].append(cycle)
continue
path = connections[i]
# Find all the nodes reachable
while length(path) > 0:
node = path.pop(0)
if node in discovered:
continue
discovered[node] = 1
if node in govt:
is_govt = True
path = connections[node] + path
cycle.append(node)
if is_govt:
cycles["G"].append(order(unique(cycle)))
else:
cycles["N"].append(order(unique(cycle)))
ordered_cycles = sorted(cycles["G"], key=len)
highest = length(ordered_cycles[-1])
ordered_cycles.pop(length(ordered_cycles) - 1)
for cycle in cycles["N"]:
highest += length(cycle)
total = highest * (highest - 1) // 2
for j in ordered_cycles:
total += length(j) * (length(j) - 1) // 2
print(total - edges)
solve()
``` | output | 1 | 99,944 | 13 | 199,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | instruction | 0 | 99,945 | 13 | 199,890 |
Tags: dfs and similar, graphs
Correct Solution:
```
class graph:
def __init__(self,size):
self.G=dict()
for i in range(size):
self.G[i]=set()
self.sz=size
self.ne=0
def ae(self,u,v):
self.G[u].add(v)
self.G[v].add(u)
self.ne+=1
def se(self,u):
return self.G[u]
def nume(self):
return self.ne
def dfs(G,v):
num,mk=1,mark[v]
vv[v]=1
for u in G.se(v):
if not vv[u]:
n1,mk1=dfs(G,u)
num+=n1
mk|=mk1
return num,mk
n,m,k=(int(z) for z in input().split())
G=graph(n)
hh=[int(z)-1 for z in input().split()]
mark=[0]*n
vv=[0]*n
for i in hh:
mark[i]=1
for i in range(m):
u,v=(int(z)-1 for z in input().split())
G.ae(u,v)
sunmk=0
mkcc=[]
for u in range(n):
if not vv[u]:
n2,mk2=dfs(G,u)
if mk2:
mkcc.append(n2)
else:
sunmk+=n2
mkcc.sort()
ans=0
##print(mkcc,sunmk)
for i in mkcc[:len(mkcc)-1]:
ans+=i*(i-1)//2
ans+=(mkcc[-1]+sunmk)*(mkcc[-1]+sunmk-1)//2
ans-=m
print(ans)
``` | output | 1 | 99,945 | 13 | 199,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | instruction | 0 | 99,946 | 13 | 199,892 |
Tags: dfs and similar, graphs
Correct Solution:
```
class Union:
def __init__(self, n):
self.ancestors = [i for i in range(n+1)]
self.size = [0]*(n+1)
def get_root(self, node):
if self.ancestors[node] == node:
return node
self.ancestors[node] = self.get_root(self.ancestors[node])
return self.ancestors[node]
def merge(self, a, b):
a, b = self.get_root(a), self.get_root(b)
self.ancestors[a] = b
def combination(number):
return (number * (number - 1)) >> 1
n, m, k = map(int, input().split())
biggest, others, res = 0, n, -m
homes = list(map(int, input().split()))
union = Union(n)
for _ in range(m):
a, b = map(int, input().split())
union.merge(a, b)
for i in range(1, n+1):
union.size[union.get_root(i)] += 1
for home in homes:
size = union.size[union.get_root(home)]
biggest = max(biggest, size)
res += combination(size)
others -= size
res -= combination(biggest)
res += combination(biggest + others)
print(res)
``` | output | 1 | 99,946 | 13 | 199,893 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | instruction | 0 | 99,947 | 13 | 199,894 |
Tags: dfs and similar, graphs
Correct Solution:
```
entrada = input().split(" ")
n = int(entrada[0])
m = int(entrada[1])
k = int(entrada[2])
lista = []
nodes = list(map(int, input().split(" ")))
for i in range(n):
lista.append([])
for i in range(m):
valores = input().split(" ")
u = int(valores[0])
v = int(valores[1])
lista[u - 1].append(v - 1)
lista[v - 1].append(u - 1)
usado = [False] * n
parc1 = 0
parc2 = -1
def calc(valor):
global x, y
x += 1
y += len(lista[valor])
usado[valor] = True
for i in lista[valor]:
if not usado[i]:
calc(i)
for i in range(k):
x = 0
y = 0
calc(nodes[i] - 1)
parc1 += (x * (x - 1) - y) // 2
parc2 = max(parc2, x)
n -= x
aux3 = 0
lenght = len(lista)
for i in range(lenght):
if not usado[i]:
aux3 += len(lista[i])
parc1 += ((parc2 + n) * (n + parc2 - 1) - parc2 * (parc2 - 1)) // 2
maximumNumber = parc1 - (aux3 // 2)
print(maximumNumber)
``` | output | 1 | 99,947 | 13 | 199,895 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | instruction | 0 | 99,948 | 13 | 199,896 |
Tags: dfs and similar, graphs
Correct Solution:
```
import sys
class YobaDSU():
def __init__(self, keys, weights):
self.A = [[i,0,w] for i, w in zip(keys, weights)]
self.size = len(self.A)
def get(self, i):
p = i
while self.A[p][0] != p: p = self.A[p][0]
j = self.A[i][0]
while j != p:
self.A[i][0] = p
i, j = j, self.A[j][0]
return (p, self.A[p][2])
def __getitem__(self, i):
return self.get(i)[0]
def union(self, i, j):
u, v = self[i], self[j]
if u == v: return
self.size -= 1
if self.A[u][1] > self.A[v][1]:
self.A[v][0] = u
self.A[u][2] += self.A[v][2]
else:
self.A[u][0] = v
self.A[v][2] += self.A[u][2]
if self.A[u][1] == self.A[v][1]:
self.A[v][1] += 1
def __len__(self): return self.size
class WeightedDSU(YobaDSU):
def __init__(self, weights):
self.A = [[i,0,w] for i, w in enumerate(weights)]
self.size = len(self.A)
class DSU(YobaDSU):
def __init__(self, n):
self.A = [[i,0,1] for i in range(n)]
self.size = n
def solve():
n, m, k = map(int, input().split())
C = [int(x)-1 for x in input().split()]
D = DSU(n)
for line in sys.stdin:
u, v = map(int, line.split())
D.union(u-1, v-1)
S = [D.get(c)[1] for c in C]
free = n - sum(S)
argmax = max(enumerate(S), key = lambda x: x[1])
S[argmax[0]] += free
return sum(s*(s-1)//2 for s in S) - m
print(solve())
``` | output | 1 | 99,948 | 13 | 199,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def solve():
nodes, edges, distinct = list(map(int, input().split(" ")))
govt = {x-1: 1 for x in list(map(int, input().split(" ")))}
connections = {}
# Add edges
for _ in range(edges):
x, y = list(map(int, input().split(" ")))
if x-1 not in connections:
connections[x-1] = [y-1]
else:
connections[x-1].append(y-1)
if y-1 not in connections:
connections[y-1] = [x-1]
else:
connections[y-1].append(x-1)
discovered = {}
cycles = {m: [] for m in ["G", "N"]}
for i in range(nodes):
is_govt = False if i not in govt else True
# Node is already been lookd at
if i in discovered:
continue
cycle = [i]
# Nodes with no edges to other nodes
if i not in connections:
discovered[i] = 1
if is_govt:
cycles["G"].append(cycle)
else:
cycles["N"].append(cycle)
continue
path = connections[i]
# Find all the nodes reachable
while len(path) > 0:
node = path.pop(0)
if node in discovered:
continue
discovered[node] = 1
if node in govt:
is_govt = True
path = connections[node] + path
cycle.append(node)
if is_govt:
cycles["G"].append(list(set(cycle)))
else:
cycles["N"].append(list(set(cycle)))
ordered_cycles = sorted(cycles["G"], key=len)
highest = len(ordered_cycles[-1])
ordered_cycles.pop(len(ordered_cycles) - 1)
for cycle in cycles["N"]:
highest += len(cycle)
total = highest * (highest - 1) // 2
for j in ordered_cycles:
if len(j) == 1:
continue
total += len(j) * (len(j) - 1) // 2
print(total - edges)
solve()
``` | instruction | 0 | 99,949 | 13 | 199,898 |
Yes | output | 1 | 99,949 | 13 | 199,899 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
entrada = input().split(" ")
n = int(entrada[0])
m = int(entrada[1])
k = int(entrada[2])
lista = []
nodes = list(map(int, input().split(" ")))
for i in range(n):
lista.append([])
for i in range(m):
valores = input().split(" ")
u = int(valores[0])
v = int(valores[1])
lista[u - 1].append(v - 1)
lista[v - 1].append(u - 1)
usado = [False] * n
aux1 = 0
aux2 = -1
def calc(valor):
global x, y
x += 1
usado[valor] = True
y += len(lista[valor])
for i in lista[valor]:
if not usado[i]:
calc(i)
for i in range(k):
# global x, y
x = 0
y = 0
calc(nodes[i] - 1)
aux1 += (x * (x - 1) - y) // 2
aux2 = max(aux2, x)
n -= x
aux3 = 0
lenght = len(lista)
for i in range(lenght):
if not usado[i]:
aux3 += len(lista[i])
aux1 += ((aux2 + n) * (n + aux2 - 1) - aux2 * (aux2 - 1)) // 2
maximumNumber = aux1 - aux3 // 2
print(maximumNumber)
``` | instruction | 0 | 99,950 | 13 | 199,900 |
Yes | output | 1 | 99,950 | 13 | 199,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def dfs(u,vis):
vis.add(u)
for v in g[u]:
if v not in vis:
dfs(v,vis)
n,m,k = map(int,list(input().split()))
govs_ind = map(int,list(input().split()))
orig = set()
countries = set(range(1,n+1))
g = [ [] for i in range(n+1) ]
for i in range(m):
u,v = map(int,list(input().split()))
if(u>v):
u,v = v,u
orig.add((u,v))
g[u].append(v)
g[v].append(u)
gov_nods = []
for u in govs_ind:
vis = set()
dfs(u,vis)
gov_nods.append(vis)
no_govs = countries.copy()
nvoss = 0
for reg in gov_nods:
no_govs -= reg
size = len(reg)
nvoss += (size*(size-1))//2
size = len(no_govs)
nvoss += (size*(size-1))//2
maxi = 0
for i in range(len(gov_nods)):
if len(gov_nods[i]) > len(gov_nods[maxi]) :
maxi = i
max_gov = gov_nods[maxi]
nvoss += len(max_gov)*len(no_govs)
nvoss -= len(orig)
print(nvoss)
# nvos = set()
# for reg in gov_nods:
# for u in reg:
# for v in reg:
# if u!=v:
# if u<v:
# nvos.add((u,v))
# else:
# nvos.add((v,u))
# for u in no_govs:
# for v in no_govs:
# if u!=v:
# if u<v:
# nvos.add((u,v))
# else:
# nvos.add((v,u))
# maxi = 0
# for i in range(len(gov_nods)):
# if len(gov_nods[i]) > len(gov_nods[maxi]) :
# maxi = i
# max_gov = gov_nods[maxi]
# for u in max_gov :
# for v in no_govs:
# if u!=v:
# if u<v:
# nvos.add((u,v))
# else:
# nvos.add((v,u))
# res = nvos-orig
# print(len(res))
# for reg in gov_nods:
# print("size: ", len(reg))
# C:\Users\Usuario\HOME2\Programacion\ACM
``` | instruction | 0 | 99,951 | 13 | 199,902 |
Yes | output | 1 | 99,951 | 13 | 199,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
import sys
from copy import deepcopy
input = sys.stdin.readline
v, e, g = map(int, input().split())
connect = [set() for i in range(v)]
gov = list(map(int, input().split()))
for i in range(e):
x,y = map(int, input().split())
connect[x-1].add(y)
connect[y-1].add(x)
sizes = []#
for i in gov:
reached = {i}
while True:
old = deepcopy(reached)
for j in range(v):
if j+1 in reached:
reached.update(connect[j])
elif not connect[j].isdisjoint(reached):
reached.add(j+1)
if old == reached:
break
sizes.append(len(reached))
ans = -e
for i in sizes:
ans += i*(i-1)//2
big = max(sizes)
for i in range(v-sum(sizes)):
ans += big
big += 1
print(ans)
``` | instruction | 0 | 99,952 | 13 | 199,904 |
Yes | output | 1 | 99,952 | 13 | 199,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def dfs(x,v,g,ks,kk):
rtv = 0
if v.__contains__(x) == False:
v.add(x)
if ks.__contains__(x):
kk.add(x)
rtv = 1
for i in range(1,n+1):
if g[x][i] == 1 and v.__contains__(i) == False :
rtv += dfs(i,v,g,ks,kk)
return rtv
n,m,k = map(int,input().strip().split(' '))
ks = set(map(int,input().strip().split(' ')))
g = [ [0]*(n+1) for i in range(n+1)]
for i in range(m):
x,y = map(int,input().strip().split(' '))
g[x][y] = 1
subts = [0]*(n+1)
subtk = [0]*(n+1)
v = set({})
for i in range(1,n+1):
kk = set({})
subts[i] = dfs(i,v,g,ks,kk)
if len(kk) > 0:
subtk[i] = 1
ans = 0
mk = 0
mi = 0
for i in range(1,n+1):
if subtk[i] == 1:
if mk < subts[i]:
mk = subts[i]
mi = i
for i in range(1,n+1):
if subtk[i] == 0:
subts[mi] += subts[i]
subts[i] = 0
for i in range(1,n+1):
if subts[i] != 0:
ans += int((subts[i]*(subts[i] - 1))/2)
#print(subts,subtk)
print(ans - m)
``` | instruction | 0 | 99,953 | 13 | 199,906 |
No | output | 1 | 99,953 | 13 | 199,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def dfs(x,v,g,ks,kk):
rtv = 0
if v.__contains__(x) == False:
v.add(x)
if ks.__contains__(x):
kk.add(x)
rtv = 1
for i in range(1,n+1):
if g[x][i] == 1 and v.__contains__(i) == False :
rtv += dfs(i,v,g,ks,kk)
return rtv
n,m,k = map(int,input().strip().split(' '))
ks = set(map(int,input().strip().split(' ')))
g = [ [0]*(n+1) for i in range(n+1)]
for i in range(m):
x,y = map(int,input().strip().split(' '))
g[x][y] = 1
subts = [0]*(n+1)
subtk = [0]*(n+1)
v = set({})
for i in range(1,n+1):
kk = set({})
subts[i] = dfs(i,v,g,ks,kk)
if len(kk) > 0:
subtk[i] = 1
ans = 0
mk = 0
cnk = 0
for i in range(1,n+1):
ans += int((subts[i]*(subts[i] - 1))/2)
if subtk[i] == 1:
mk = max(mk,subts[i])
for i in range(1,n+1):
if subtk[i] == 0:
ans += mk*subts[i]
#print(subts,subtk)
print(ans - m)
``` | instruction | 0 | 99,954 | 13 | 199,908 |
No | output | 1 | 99,954 | 13 | 199,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
n, m, k = map(int, input().split())
governments = list(map(int, input().split()))
vis = [False]*(n+1)
g = [ set() for i in range(n+1) ]
lista = []
def dfs(v, lista):
vis[v] = True
lista[0].add(v)
lista[1] += len(g[v])
if (v in governments):
lista[2] = v
for u in g[v]:
if (not vis[u]):
dfs(u, lista)
return lista
for i in range(m):
a, b = map(int, input().split())
g[a].add(b)
g[b].add(a)
for v in range(1, len(g)):
if (not vis[v]):
lista.append(dfs(v, [set(), 0, None]))
biggest_group = [-1, None]
for group, n_edges, government in lista:
if (government):
tmp_group = [len(group), government]
if(tmp_group[0] > biggest_group[0]):
biggest_group = tmp_group
nodes = 0
edges = 0
off = 0
for group, n_edges, government in lista:
n_edges = n_edges/2
if (not government or government == biggest_group[1]):
nodes += len(group)
edges += n_edges
else:
off += (len(group)*(len(group) -1 )/2)-n_edges
print(int((nodes*(nodes-1)/2)-edges) + int(off))
``` | instruction | 0 | 99,955 | 13 | 199,910 |
No | output | 1 | 99,955 | 13 | 199,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Examples
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
<image> Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.
For the second sample test, the graph looks like this:
<image> We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Submitted Solution:
```
def dfs(node):
tot = 0
edge = 0
stack = [node]
while stack:
ele = stack.pop(-1)
seen[ele] = 1
tot += 1
for each in adj[ele]:
if seen[each] == 0:
stack.append(each)
return tot
n,m,k = map(int,input().split())
arr = list(map(int,input().split()))
seen = [0] * (n+1)
adj = [list() for i in range(n+1)]
for _ in range(m):
a,b = map(int,input().split())
adj[a].append(b)
adj[b].append(a)
mx = 0
totEdge = n
ans = 0
for each in arr:
s = dfs(each)
mx = max(s,mx)
ans += s*(s-1)//2
totEdge -= s
ans += (totEdge+mx) * (totEdge+mx-1) // 2
ans -= mx*(mx-1) // 2 + m
print(ans)
``` | instruction | 0 | 99,956 | 13 | 199,912 |
No | output | 1 | 99,956 | 13 | 199,913 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.